
function inArray(arr, value)
{
	var i;
	for (i=0; i < arr.length; i++) {
        if (arr[i] === value) {
			return true;
        }
    }
    return false;
}

function func_ajax_request(url, query_string, method, callback, preaction, postaction) {
	var request_object = null;
    
	try {
        request_object = new XMLHttpRequest();
    }
    catch(e) {
        try {
            request_object = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e1) {
            try {
                request_object = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e2) {
                try {
                    request_object = new ActiveXObject("Msxml2.XMLHTTP.4.0");
                }
                catch(e3) {
                    request_object = null;
                }
            }
        }
    }

    if (!request_object || request)
        return -1;

    request = request_object;
    request_object.open(method, url, true);
    request_object.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request_object.onreadystatechange = function () {
        _ajax_callback(callback, postaction);
    }
	
	if (preaction)
		eval(preaction);
	
	return request_object.send(query_string);
}

function _ajax_callback(js_callback, postaction) {
    if (request && request.readyState == 4) {
		if (request.status != 200) {
			error_handler(request.statusText, false);
		}
		else {
			error_handler('', true);
			if (eval(js_callback)) {
	            eval(js_callback+'(request.responseText);');
	        }
		}
		if (postaction)
			eval(postaction);
		request = false;
    }
}

function error_handler(error, clr) {
	var error_section = document.getElementById('ajax_error');
	if (error_section) {
		if (clr)
			error_section.innerHTML = '';
		else
			error_section.innerHTML = '<P class="ErrorMessageSmall">'+ajax_error_msg+' '+error+'</P>';
	}
}

function common_callback(response) {
    var target_div = document.getElementById('minicart_content');
	if (target_div) {
	    target_div.innerHTML = response;
	}
	var current_page = current_location.replace(/.*\//g, '');
	if (current_page == 'cart.php')
        location.reload(true);
}

function change_quantity(evt, productindex) {
	evt = (evt) ? evt : event;
	var script = xcart_web_dir + "/minicart_content.php";
	var charCode = (evt.charCode) ? evt.charCode : ( (evt.keyCode) ? evt.keyCode : ( (evt.which) ? evt.which : 0 ) );
	if (charCode == '13') {
		product_quantity = document.getElementById('product_quantity_'+productindex);
	 	if (product_quantity) {
	 	 	var quantity = product_quantity.value;
			func_ajax_request(script, 'action=update&productindexes['+productindex+']='+quantity+'&charset='+default_charset, 'POST', 'common_callback', 'en_dis_div(document.getElementById(\'minicart_content\'), true);', 'en_dis_div(document.getElementById(\'minicart_content\'), false); update_add_to_cart_buttons();');
	 	}
	} 
}

function remove_cart_item(evt, productindex) {
	var script = xcart_web_dir + "/minicart_content.php";
	func_ajax_request(script, 'productindex='+productindex+'&mode=delete&&charset='+default_charset, 'POST', 'common_callback', 'en_dis_div(document.getElementById(\'minicart_content\'), true);', 'en_dis_div(document.getElementById(\'minicart_content\'), false); update_add_to_cart_buttons();');
}

function collect_quantities(target) {
		if (target && target.childNodes) { 
			 var i;
	         var quantites_string = '';
			 for(i = 0; i < target.childNodes.length; i++) {
			 	 var quantities = collect_quantities(target.childNodes[i]);
				 quantites_string += (quantites_string == '') ? quantities : (quantities != '') ? '&'+quantities : '';
				 if (target.childNodes[i].id && target.childNodes[i].id.match('product_quantity[0-9]*')) {
				 	var quantity = 'productindexes['+target.childNodes[i].id.replace(new RegExp('product_quantity_'), '')+']='+target.childNodes[i].value;
				 	quantites_string += (quantites_string == '') ? quantity : '&'+quantity;
				 }
	         }
			 return quantites_string;
		}
		return ''; 
}

function collect_tags_values(target, idcriteria) {
   if (target && target.childNodes) {
       var tags = '';
       var i = 0;
       for (i = 0; i < target.childNodes.length; i++) {
           var child_tags = collect_tags_values(target.childNodes[i], idcriteria);
           if (child_tags) tags += (tags == '') ? child_tags : ','+child_tags;
           if ((!idcriteria) || (idcriteria && target.childNodes[i].id && target.childNodes[i].id.match(idcriteria))) {
               tags += (tags == '') ? (target.childNodes[i].value ? target.childNodes[i].value : '') : ','+(target.childNodes[i].value ? target.childNodes[i].value : ''); 
           }
       }
       return tags;
   }
   return null;
}

function collect_form_values(target, namecriteria) {
	var reginput = /input/i;
    var regselect = /select/i;
	var regradioinput = /radioinput/i;
	
	if (target && target.childNodes) {
		var i = 0;
		var params_string = '';
		for(i = 0; i < target.childNodes.length; i++) {
			var params = collect_form_values(target.childNodes[i], namecriteria);
			params_string += (params_string == '') ? params : (params != '') ? '&'+params : '';
			var namecriteria_passed = false;
			if (!namecriteria)
				namecriteria_passed = true;
			else 
				if	(target.childNodes[i].name && target.childNodes[i].name.match(namecriteria)) 
					namecriteria_passed = true;
			
			if (namecriteria_passed && target.childNodes[i].tagName && ((reginput.exec(target.childNodes[i].tagName) != null) || (regselect.exec(target.childNodes[i].tagName) != null) || (regradioinput.exec(target.childNodes[i].tagName) != null)) && target.childNodes[i].name != '') {
				var params = target.childNodes[i].name+'='+target.childNodes[i].value;
       	        params_string += (params_string == '') ? params : '&'+params;
			}
		}
		return params_string;
	}
	return '';
}

function update_cart() {
	var script = xcart_web_dir + "/minicart_content.php";
	func_ajax_request(script, 'action=update&'+collect_quantities(document.getElementById('minicart_content'))+'&charset='+default_charset, 'POST', 'common_callback', 'en_dis_div(document.getElementById(\'minicart_content\'), true);', 'en_dis_div(document.getElementById(\'minicart_content\'), false); update_add_to_cart_buttons();');
}

function add_to_cart(productid) {
	var script = xcart_web_dir + "/minicart_content.php";
	func_ajax_request(script, 'charset='+default_charset+'&'+collect_form_values(document.getElementById('orderform_'+productid), null), 'POST', 'common_callback', 'en_dis_div(document.getElementById(\'minicart_content\'), true); adding_show(\''+productid+'\', \'P\');', 'en_dis_div(document.getElementById(\'minicart_content\'), false); adding_show(\''+productid+'\', \'I\'); update_add_to_cart_buttons();');
}

function clear_cart() {
	var script = xcart_web_dir + "/minicart_content.php";
	func_ajax_request(script, 'mode=clear_cart&charset='+default_charset, 'POST', 'common_callback', 'en_dis_div(document.getElementById(\'minicart_content\'), true);', 'en_dis_div(document.getElementById(\'minicart_content\'), false); update_add_to_cart_buttons();');
}

function update_add_to_cart_buttons() {
	if (page_productids) {
		var i = 0;
		for(i = 0; i < page_productids.length; i++) {
			
			var options_values = collect_tags_values(document.getElementById('minicart_content'), 'cart_productid_'+page_productids[i]);
			
			if (options_values) options_values = options_values.split(/,/);
			var def_element = document.getElementById('default_options_'+page_productids[i]);
			var collected_options = collect_form_values(document.getElementById('orderform_'+page_productids[i]), 'product_options.*')
			var reg = /product_options\[(\w+)\]=(\w+)&?/g
			var options = collected_options.match(reg);
			if (options) {
				var j = 0;
				for (j = 0; j < options.length; j++) {
					options[j] = options[j].replace(reg, 'i:$1;s:'+options[j].replace(reg, '$2').length+':"$2";');
				}
				
				collected_options = 'a:'+options.length+':{'+options.join('')+'}';
			}
			else 
				collected_options = 's:0:"";';
			
			if (def_element && def_element.value) 	{
				if (options_values && inArray(options_values, def_element.value)) 		{
					adding_show(page_productids[i], 'I');
				}
				else {
					adding_show(page_productids[i], 'A');
				}
			}
			else {
				if (options_values && collected_options && inArray(options_values, collected_options)) { 
					adding_show(page_productids[i], 'I');
				}	
				else {
					adding_show(page_productids[i], 'A');
				}
			}
		}
	}
}

function set_boxes_visiblity(productid, add_box, adding_box, added_box) {
	var element = document.getElementById('add_to_cart_box_'+productid);
    if (element) element.style.display = (add_box) ? '' : 'none';
	element = document.getElementById('adding_to_cart_box_'+productid);
	if (element) element.style.display = (adding_box) ? '' : 'none';
	element = document.getElementById('added_to_cart_box_'+productid);
	if (element) element.style.display = (added_box) ? '' : 'none';

}

function adding_show(productid, state) {
	switch(state) {
		case 'A':
		set_boxes_visiblity(productid, true, false, false);
		break;
		case 'I':
        set_boxes_visiblity(productid, false, false, true);
		break;
		case 'P':
		set_boxes_visiblity(productid, false, true, false);
		break;
	}
}

function en_dis_div(target, state) {
   if (target) { 
       var i;
       for(i = 0; i < target.childNodes.length; i++) {
		   en_dis_div(target.childNodes[i], state);
		   if (target.childNodes[i].id && target.childNodes[i].id.match('product_quantity[0-9]*') && target.childNodes[i].disabled != undefined) {
			   	   target.childNodes[i].disabled=state;
		   }	   
	   }
   }	   
}

function displayLink(id) {
	var link = document.getElementById(id);
	link.style.display = "";
}

function generateId(count) {
	var chars = "234567890abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var chars_length = chars.length;
	var id = "";

	for (var i = 0; i < count; i++) {
		var rand_no = Math.floor((60-4)*Math.random()) + 0;
		id += chars[rand_no];
	}
	
	return id;
}

// add product to cart product with needed quatity
function ajax_add_to_cart(productid, amount, link) {
	
	var mod = "";
	if (link) {
		var id = generateId(6);
		link.style.display = "none";
		link.id = id+"link";
		$(link).after('<strong id="'+id+'">'+plz_wait+'</strong>');
		mod = "$(document.getElementById('"+id+"')).remove(); displayLink('"+link.id+"')";
	}

	var script = xcart_web_dir + "/minicart_content.php";

	func_ajax_request(
		script, 
		"charset="+default_charset+"&mode=add&productid="+productid+"&amount="+amount, "POST", 
		"common_callback", 
		"en_dis_div(document.getElementById('minicart_content'), true); adding_show('"+productid+"', 'P');", 
		"en_dis_div(document.getElementById('minicart_content'), false); adding_show('"+productid+"', 'I'); update_add_to_cart_buttons();"+mod
	);
}

// add product to cart from wishlist
function ajax_wl_add_to_cart(item, elem) {
	en_dis_div(document.getElementById('minicart_content'), true);

	elem.style.display = "none";
	$(elem).after('<div id="loader'+item+'"><strong>'+plz_wait+'</strong></div>');

	$.getJSON('cart.php', { mode: 'wl2cart_ajax', wlitem: item },
		function (obj) {
			func_ajax_request("minicart_content.php", "charset="+default_charset, "POST", "alter_callback");
			elem.style.display = "";
			$("#loader"+item).remove();
		}
	);
}

function alter_callback(response) {
    var target_div = document.getElementById('minicart_content');
	if (target_div) {
	    target_div.innerHTML = response;
	}
}

// add forduct to wishlist
function ajax_add2wl(form, elem) {

	if (login == "") {
		alert(err_need_login);
		return false;
	}

	if (!form || !elem) {
		alert(err_add2wl);
		return false;
	}

	elem.style.display = "none";

	var data = {};
	for (var i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if (e.name.length > 0) {
			data[e.name] = e.value;
		}
	}
	data.mode = "add2wl_ajax";

	$(elem).after('<div id="loader'+data.productid+'"><strong>'+plz_wait+'</strong></div>');
	
	jQuery.post("cart.php", data, function (obj, rstatus) { 
		if (rstatus == "success") {
			if (obj.result === 1) {
				alert(updated_add2wl);
			} else if (obj.result == 2) {
				alert(success_add2wl);
			} else {
				alert(err_add2wl);
			}
		} else {
			alert(err_add2wl);
		}
		elem.style.display = "";
		$("#loader"+data.productid).remove();
	}, "json");

}

