var Images_array = new Array('infview.gif', 'check_on.gif', 'reject.gif', 'autopay.gif', 'manualpay.gif', 'page_go.gif', 'infedit.gif','ledon.gif','ledoff.gif','campaings.gif','arrow.gif','up.gif','mail_confirm.gif','mail_not_confirm.gif','preview.gif','reject2.gif','print.gif');
var Sel_Images_array = new Array('infview_sel.gif', 'check_on_sel.gif','reject_sel.gif', 'autopay_sel.gif', 'manualpay_sel.gif', 'page_go_sel.gif', 'infedit_sel.gif','ledon_sel.gif','ledoff_sel.gif','campaings_sel.gif','arrow_sel.gif','up_sel.gif','mail_confirm_sel.gif','mail_not_confirm_sel.gif','preview_sel.gif','reject2_sel.gif','print_sel.gif');
var Images = [];
var Sel_Images = [];

if (typeof userid != 'undefined') setCookie("userid", userid, 0, "/", 0, 0);

for (var i=0; i<Images_array.length; i++)
{
	Images[i] = new Image();
	Sel_Images[i] = new Image();
	Images[i].src = "images/"+Images_array[i];
	Sel_Images[i].src = "images/"+Sel_Images_array[i];
}

function img_flat(cur_img, isflat, num)
{
 cur_img.src = (isflat) ? Sel_Images[num].src : Images[num].src;
}

function group_check(fnum,check)
{ 
	for (var i=0; i<document.forms[fnum].elements.length; i++) {
		if ( (document.forms[fnum].elements[i].type == "checkbox") && 
				(document.forms[fnum].elements[i].name != "filter_field[]") &&
				(document.forms[fnum].elements[i].name != "none") )
			document.forms[fnum].elements[i].checked = check;
	}
} 

function submit_form(act,form_name)
{
	eval("document."+form_name+".action.value = '"+act+"';");
	eval("document."+form_name+".submit();");
}

function date_from_to_status(sel_elem)
{
 var elem_status = false;
	if (sel_elem.options[sel_elem.selectedIndex].value != "c") {
		elem_status = true; calendar_status = 'hidden';
	}
	else {
		elem_status = false; calendar_status = 'visible';
	}
	document.frmperiodpage.date_from.disabled = elem_status;
	document.frmperiodpage.date_to.disabled = elem_status;
	span_from.style.visibility = calendar_status;
	span_to.style.visibility = calendar_status;
}

function payment_amount_status(sel_elem,cvalue)
{
 var elem_status = false;
	if (sel_elem.options[sel_elem.selectedIndex].value == cvalue) elem_status = true;
	else elem_status = false;
	document.mainform.amount.disabled = elem_status;
	document.mainform.amount_cb.disabled = !elem_status;
}

function OpenMyWindow(url)
{
	MyWindow = window.open(url,'','toolbar=no,scrollbars=no,directories=no,resizable=no,width=200,height=200');
 return false;
}


function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if ( node == null ) node = document;
	if ( tag == null ) tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;

	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
 return classElements;
}

function move_filter_form()
{
	var obj = getElementsByClass('filterclass',null,'tr');
	var curimg = "images/m_head_btn_up_tr.gif";
	for(i=0; i<obj.length; i++)
	{
		if (obj[i].style.display == 'none') {
			obj[i].style.display = '';
			curimg = "images/m_head_btn_up_tr.gif";
		}
		else {
			obj[i].style.display = 'none';
			curimg = "images/m_head_btn_down_tr.gif";
		}
	}
	document.getElementById('filter_img').src = curimg;
}



function dropFile(btn)
{
	if (document.getElementById) {
		tr = btn;
		while (tr.tagName != 'TR')
			tr = tr.parentNode;
		tr.parentNode.removeChild(tr);
		checkForLast();
	}
}

function addFile(btn)
{
	if (document.getElementById) {
		tr = btn;
		while (tr.tagName != 'TR')
			tr = tr.parentNode;
		var idSuffix = Math.round(Math.random()*1000);
		var newTr = tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
		thisChilds = newTr.getElementsByTagName('td');
		for (var i = 0; i < thisChilds.length; i++)
		{
			if (thisChilds[i].className == 'header') thisChilds[i].innerHTML = '';
			if (thisChilds[i].className == 'files') thisChilds[i].innerHTML = '<input class="data" type="text" name="msc[]" id="msc[]"  value="" maxlength="220" style="width:250px" />&nbps;<input class="data" type="text" name="mscq[]" id="mscq[]"  value="" maxlength="220" style="width:40px"  />';
		}
		checkForLast();
	}
}

function checkForLast()
{
	btns = document.getElementsByName('drop');
	for (i = 0; i < btns.length; i++)
	{
		btns[i].disabled = (btns.length == 1) ? true : false;
	}
}


//
/* -- Prodeuct info functions -- (front-end) -- */
//
var caution = false;
function setCookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "")
	if (!caution || (name + "=" + escape(value)).length <= 4000) document.cookie = curCookie
	else 
	if (confirm("Cookie length more then 4KB! Saved as many as possible.")) document.cookie = curCookie
}

function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + '=' +
            ( ( path ) ? ';path=' + path : '') +
            ( ( domain ) ? ';domain=' + domain : '' ) +
            ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function get_element(s_id)
{
	return (document.all ? document.all[s_id] : (document.getElementById ? document.getElementById(s_id) : null));
}

function add_product(prodid, quantity_field)
{
	var prod_list = document.cookie.split(';');
	var p = -1;
	var qty = 1;

	var qty_elem = get_element(quantity_field);
	if (qty_elem) {
		var qty_selInd = get_element(quantity_field).selectedIndex;
		var qty = Number( qty_elem[qty_selInd].value );
	}

	for (i=0; i<prod_list.length; i++)
	{
		p = prod_list[i].lastIndexOf("product["+prodid+"]");
		if ( p >=0 ) {
			p = prod_list[i].lastIndexOf("=");
			if ( p >=0 ) {
				cur_qty = Number( prod_list[i].substr(p + 1) );
				qty = qty + cur_qty;
				break;
			}
		}
	}
	setCookie("product["+prodid+"]", qty, 0, "/", 0, 0);
	//		document.cookie = "product["+prodid+"]="+qty;

	var list = getElementsByClass('additionalfield-for-product',null,null);
	for (var i=0; i<list.length; i++)
	{
		name = list[i].name;
		if (name == undefined) continue;
		else if (name == '') continue;

		name_parts = name.split('-');
		if ( (name_parts.length == 3) && (name_parts[0] == 'additionalfield') && (name_parts[2] == prodid) ) {
			if ( (list[i].type == "checkbox") && !list[i].checked) {
				var dtExpires = new Date();
			  dtExpires.setTime(dtExpires.getTime() - 10);
				setCookie("additionalfield["+name_parts[1] + "-" + prodid + "]", list[i].value, dtExpires, "/", 0, 0);
			}
			else {
				if ( (list[i].type == "radio") && !list[i].checked) continue;
				setCookie("additionalfield["+name_parts[1] + "-" + prodid + "]", list[i].value, 0, "/", 0, 0);
			}
		}
	}

	refresh_cart();
}

function refresh_cart()
{
	var items_qty = 0;
	var items_price = 0.0;
	var prod_list = document.cookie.split(';');
	for (i=0; i<prod_list.length; i++)
	{
		if (prod_list[i].indexOf("product") < 0) continue;
		p_s = prod_list[i].lastIndexOf("product[");
		p_e = prod_list[i].lastIndexOf("]=");
		if ( (p_s >=0) && (p_e >=0) ) {
			prodid = Number( prod_list[i].substring(p_s + 8, p_e) );
			qty = Number( prod_list[i].substr(p_e + 2) );
			items_qty += qty;
			items_price += Number( prod_prices[prodid] ) * qty;
		}
	}

	var es_shopping_cart_items = get_element('es_shopping_cart_items');
	if (es_shopping_cart_items) es_shopping_cart_items.innerHTML = items_qty;

	var es_shopping_cart_total = get_element('es_shopping_cart_total');
	if (es_shopping_cart_total) es_shopping_cart_total.innerHTML = c_p(items_price);
}

function sync_cookies()
{
	var req = new JsHttpRequest();
	// Code automatically called on load finishing.
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			remove_array_cookies("product");
			remove_array_cookies("additionalfield");
			add_array_cookes(req.responseJS.res);

			refresh_cart();
		}
	}
  // Prepare request object (automatically choose GET or POST).
  req.open(null, shopcart_url + 'basket_sync_cookie.php', true);
  // Send data to backend.
  req.send( { q: '1' } );
	
	refresh_cart();
}

function remove_array_cookies(name)
{
	var clist = document.cookie.split(';');
	for (i=0; i<clist.length; i++)
	{
		if (clist[i].indexOf(name) < 0) continue;
		p_e = clist[i].lastIndexOf("]=");
		if (p_e >= 0) {
			deleteCookie(clist[i].substring(0,p_e+1),"/",0);
		}
	}
}

function add_array_cookes(cookie_str)
{
	var clist = cookie_str.split(';');
	for (i=0; i<clist.length; i++)
	{
		if (clist[i].indexOf("[") < 0) continue;
		p_e = clist[i].lastIndexOf("=");
		if (p_e >= 0) {
      setCookie(clist[i].substring(0,p_e), clist[i].substring(p_e+1,clist[i].length), 0, "/", 0, 0);
		}
	}
}

/* -- -- */

//
/* -- Basket functions -- (front-end) -- */
//
function c_p(v)
{
	v = String(c_r(v));
	var p = v.indexOf(".");
	if( p == -1 ) {
		v = v + ".00";
	}
	else {
		v = v + "00";
		v = v.substring(0, p + 3);
	}
 return v;
}

function c_r(v)
{
	v = Number(v);
	if (isNaN(v) || v == 0) { return( 0 ); }
	return (Math.round(v*100)/100);
}

function change_qty(qty_elem, price_elem_name, price)
{                        
	var price_value = qty_elem.options[qty_elem.selectedIndex].value*price;
	var price_elem = get_element(price_elem_name);
	price_elem.value = c_p(price_value);
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
					oldonload();
					func();
			}
	}
}

function SubmCbCvFrm(lnk)
{
	get_element('CbCvH').value = document.cookie;
	var frm = get_element('CbCvFrm');
	frm.action = lnk.href;
	frm.submit();
}

addLoadEvent(sync_cookies);

/* -- -- */


/*
function check_price(fnum)
{ 
	var sub_total = 0;
	var weight_total = 0;
	//Items
	for (var i=0; i<document.forms[fnum].elements.length; i++) {
		if (document.forms[fnum].elements[i].type == "select-one") {
			sname = document.forms[fnum].elements[i].name;
			if ( (sname.indexOf('compl_prod') != -1) && (sname.indexOf('qty') != -1) ) {
				num = get_id_from_string(sname);
				eval("var val = document.getElementById('compl_prod["+num+"][qty]').options[document.getElementById('compl_prod["+num+"][qty]').selectedIndex].value * "+
					"complex_product_price["+num+"][document.getElementById('compl_prod["+num+"][product]').options[document.getElementById('compl_prod["+num+"][product]').selectedIndex].value]");
				eval("var weight = document.getElementById('compl_prod["+num+"][qty]').options[document.getElementById('compl_prod["+num+"][qty]').selectedIndex].value * "+
					"complex_product_weight["+num+"][document.getElementById('compl_prod["+num+"][product]').options[document.getElementById('compl_prod["+num+"][product]').selectedIndex].value]");
				val = c_p(val);
				weight = c_p(weight);
				document.getElementById('compl_prod_qty['+num+']').value = '$'+val;
				sub_total += c_r(val);
				weight_total = parseFloat(weight_total) + c_r(weight);
			}
			else if (sname.indexOf('product[') != -1) {
				num = get_id_from_string(sname);
				eval("var val = document.getElementById('product["+num+"]').options[document.getElementById('product["+num+"]').selectedIndex].value * product_price["+num+"]");
				eval("var weight = document.getElementById('product["+num+"]').options[document.getElementById('product["+num+"]').selectedIndex].value * product_weight["+num+"]");
				val = c_p(val);
				weight = c_p(weight);
				document.getElementById('product_qty['+num+']').value = '$'+val;
				sub_total += c_r(val);
				weight_total = parseFloat(weight_total) + c_r(weight);
			}
		}
	}
	//Subtotal
	document.getElementById('sub_total').value = '$'+c_p(sub_total);
	//Total
	document.getElementById('total').value = '$'+c_p(sub_total - (discount * sub_total) / 100 );
	//Weight
	document.getElementById('weight').value = c_p(weight_total)+'kg';
} 
*/