function lexica ($n,$a,$b,$c) {
        $n=parseInt($n);
        $x= Math.abs($n>9? (($n+'').substr(-2)) :$n);
        return (($x%=100)>9&&$x<20||($x%=10)>4||$x==0?$c:($x==1?$a:$b));
}
function getCookie(name) {
        var cookie = " " + document.cookie;
        var search = " " + name + "=";
        var setStr = null;
        var offset = 0;
        var end = 0;
        if (cookie.length > 0) {
            offset = cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = cookie.indexOf(";", offset)
                if (end == -1) {
                    end = cookie.length;
                }
                setStr = unescape(cookie.substring(offset, end));
            }
        }
		return(setStr);
}
function showCartDialog() {
	var offset = $(window).scrollTop();
	
	var item_id = $(this).attr("item_id");
	var form_key = '#form_item' + item_id;
	
	var dlh = $(".dialog_buy_params").height();
	var bh = $("body").height();
	
	$(".dialog_buy").css({top: offset+(bh-dlh)/2});
	$(".dialog_buy").show('fast');
				
	var prod = getCookie('cart_count');
	$(".cart").html("<span>"+prod+"</span> "+lexica(prod,"продукт", "продукта", "продуктов"));
	$(".dialog_buy span").text(prod+" "+lexica(prod,"продукт", "продукта", "продуктов"));
}

function cartSumm(){
	var cnt   = $("#basketform input.js_cnt");
	var price = $("#basketform .js_price");
	var summ  = $("#basketform .js_summ");
	var total_cnt = 0;
	var total_summ = 0;
	
	for (var i=0,l=cnt.length ; i<l ; i++){
		total_cnt += parseInt($(cnt[i]).val()) || 0;
		total_summ += ( $(cnt[i]).val() * ( parseInt($(price[i]).text()) || 0) ) || 0;
		$(summ[i]).text(( $(cnt[i]).val() * ( parseInt($(price[i]).text()) || 0) ) || 0);
	}
	
	$(".js_total_cnt").text(total_cnt);
	$(".js_total_summ").text(total_summ);
}


function updatePriceAtCount(item_id, set_count) {
	if(typeof set_count != 'boolean') {
		set_count = false;
	}
	$("#tovar_count"+item_id).val($("#tovar_count"+item_id).val().replace(/[^0-9]/gi, ''));
	var cnt = parseInt($("#tovar_count"+item_id).val());
	if(cnt <= 0 || isNaN(cnt)) {
		cnt = 1;
		if(set_count) {
			$("#tovar_count"+item_id).val(cnt);
		}
	} else {
		$("#tovar_count"+item_id).val(cnt);
	}
	
	price = parseFloat($("#price_main"+item_id).html());
	$("select.params_tovarp").each(function() {
		var price_add = parseFloat($(this).find('option:selected').attr("price"))
		price = price + price_add;
	});
	price = price*cnt;
	
	$("#price_new"+item_id).html(price);
	//$("#hiddenprice"+item_id).val(price);
}
function showCartDialogParams(itemid) {
	var offset = $(window).scrollTop();
	
	var item_id = $(this).attr("item_id");
	var form_key = '#form_item' + item_id;
	
	var dlh = $(".dialog_buy_params").height();
	var bh = $("body").height();
	
	$(".dialog_buy_params").css({top: offset+(bh-dlh)/2});
	$(".dialog_buy_params").show('fast', function() {
		$(".dialog_buy_params .ctrlp_text").html($("#param_div"+itemid).html());
		
		$("select.params_tovarp").mousedown(function() {
			$(this).find(".params_tovarp_empty").html('');
		});
		
		$("select.params_tovarp").change(function() {
			var item_id = $(this).attr('item_id');
			updatePriceAtCount(item_id);
		});
		$("input.params_tovarp").keyup(function() {
			var item_id = $(this).attr('item_id');
			updatePriceAtCount(item_id);
		});
	});
}

function serialize(mixed_val) {
	switch (typeof(mixed_val)) {
		case "number":
			if (isNaN(mixed_val) || !isFinite(mixed_val)){
				return false;
			} else {
				return (Math.floor(mixed_val) == mixed_val ? "i" : "d") + ":" + mixed_val + ";";
			}
		case "string":
			return "s:" + mixed_val.length + ":\"" + mixed_val + "\";";
		case "boolean":
			return "b:" + (mixed_val ? "1" : "0") + ";";
		case "object":
			if (mixed_val == null) {
				return "N;";
			} else if (mixed_val instanceof Array) {
				var idxobj = { idx: -1 };
				var map = [];
				for(var i=0; i<mixed_val.length;i++) {
					idxobj.idx++;
					var ser = serialize(mixed_val[i]);
					if(ser) {
						map.push(serialize(idxobj.idx) + ser)
					}
				}
				
				return "a:" + mixed_val.length + ":{" + map.join("") + "}"
			} else {
				var class_name = get_class(mixed_val);
				
				if (class_name == undefined){
					return false;
				}
				
				var props = new Array();
				for (var prop in mixed_val) {
					var ser = serialize(mixed_val[prop]);
					
					if (ser) {
						props.push(serialize(prop) + ser);
					}
				}
				return "O:" + class_name.length + ":\"" + class_name + "\":" + props.length + ":{" + props.join("") + "}";
			}
		case "undefined":
			return "N;";
	}
	
	return false;
}

function unserialize(inp) {
	error = 0;
	if (!inp || inp == "" || inp.length < 2) {
		errormsg = "input is too short";
		return;
	}
	var val, kret, vret, cval;
	var type = inp.charAt(0);
	var cont = inp.substring(2);
	var size = 0, divpos = 0, endcont = 0, rest = "", next = "";
	
	switch (type) {
		case "N": // null
			if (inp.charAt(1) != ";") {
				errormsg = "missing ; for null";
			}
			// leave val undefined
			rest = cont;
		break;
		case "b": // boolean
			if (!/[01];/.test(cont.substring(0,2))) {
				errormsg = "value not 0 or 1, or missing ; for boolean";
			}
			val = (cont.charAt(0) == "1");
			rest = cont.substring(1);
			break;
		case "s": // string
			val = "";
			divpos = cont.indexOf(":");
			if (divpos == -1) {
				errormsg = "missing : for string";
				break;
			}
			size = parseInt(cont.substring(0, divpos));
			if (size == 0) {
				if (cont.length - divpos < 4) {
					errormsg = "string is too short";
					break;
				}
				rest = cont.substring(divpos + 4);
				break;
			}
			if ((cont.length - divpos - size) < 4) {
				errormsg = "string is too short";
				break;
			}
			if (cont.substring(divpos + 2 + size, divpos + 4 + size) != "\";") {
				errormsg = "string is too long, or missing \";";
			}
			val = cont.substring(divpos + 2, divpos + 2 + size);
			rest = cont.substring(divpos + 4 + size);
		break;
		case "i": // integer
		case "d": // float
			var dotfound = 0;
			for (var i = 0; i < cont.length; i++) {
				cval = cont.charAt(i);
				if (isNaN(parseInt(cval)) && !(type == "d" && cval == "." && !dotfound++)) {
					endcont = i;
					break;
				}
			}
			if (!endcont || cont.charAt(endcont) != ";") {
				errormsg = "missing or invalid value, or missing ; for int/float";
			}
			val = cont.substring(0, endcont);
			val = (type == "i" ? parseInt(val) : parseFloat(val));
			rest = cont.substring(endcont + 1);
		break;
		case "a": // array
			if (cont.length < 4) {
				errormsg = "array is too short";
				return;
			}
			divpos = cont.indexOf(":", 1);
			if (divpos == -1) {
				errormsg = "missing : for array";
				return;
			}
			size = parseInt(cont.substring(1, divpos - 1));
			cont = cont.substring(divpos + 2);
			val = new Array();
			if (cont.length < 1) {
				errormsg = "array is too short";
				return;
			}
			for (var i = 0; i + 1 < size * 2; i += 2) {
				kret = unserialize(cont, 1);
				if (error || kret[0] == undefined || kret[1] == "") {
					errormsg = "missing or invalid key, or missing value for array";
					return;
				}
				vret = unserialize(kret[1], 1);
				if (error) {
					errormsg = "invalid value for array";
					return;
				}
				val[kret[0]] = vret[0];
				cont = vret[1];
			}
			if (cont.charAt(0) != "}") {
				errormsg = "missing ending }, or too many values for array";
				return;
			}
			rest = cont.substring(1);
		break;
		case "O": // object
			divpos = cont.indexOf(":");
			if (divpos == -1) {
				errormsg = "missing : for object";
				return;
			}
			size = parseInt(cont.substring(0, divpos));
			var objname = cont.substring(divpos + 2, divpos + 2 + size);
			if (cont.substring(divpos + 2 + size, divpos + 4 + size) != "\":") {
				errormsg = "object name is too long, or missing \":";
				return;
			}
			var objprops = unserialize("a:" + cont.substring(divpos + 4 + size), 1);
			if (error) {
				errormsg = "invalid object properties";
				return;
			}
			rest = objprops[1];
			var objout = "function " + objname + "(){";
			for (key in objprops[0]) {
				objout += "" + key + "=objprops[0]['" + key + "'];";
			}
			objout += "}val=new " + objname + "();";
			eval(objout);
		break;
		default:
			errormsg = "invalid input type";
	}
	return (arguments.length == 1 ? val : [val, rest]);
}

function in_array(p_val, arr) {
	for(var i = 0, l = arr.length; i < l; i++)  {
		if(arr[i] == p_val) {
			return i;
		}
	}
	return false;
}

var ch_xhr;
var requestIndex = 0;
function diffProccess(e) {
	var cok = $.cookie('diff_items');
	var iids = unserialize(cok);
	if(typeof iids == 'undefined') {
		iids = new Array();
	}
	var el = $(e.target);
	if(__diff_type == 1) {
		var k = in_array(__item_id, iids);
		if(k !== false) {
			delete iids[k];
			__diff_type = 2;
			__diff_count--;
			el.text('Добавть к сравнению');
		}
	} else {
		if(in_array(__item_id, iids) === false) {
			iids.push(__item_id);
			__diff_type = 1;
			__diff_count++;
			el.text('Убрать из сравнения');
		}
	}
	$("#diff_counter").text(__diff_count);
	if(__diff_count > 1) {
		$("#diff_link").show();
	} else {
		$("#diff_link").hide();
	}
	var val = getDiffArr(iids);
	var sval = serialize(val);
	$.cookie('diff_items', sval, {expires:7,path:'/',domain:'opendive.ru'});
	return false;
}
function getDiffArr(arr) {
	var _arr = [];
	for(var i in arr) {
		if(arr[i] == '' || arr[i] <= 0) {
			continue;
		}
		_arr.push(arr[i]);
	}
	return _arr;
}

$(function() {
	$("#diff_act").click(diffProccess);
	
	$(".cart_add").removeAttr("onclick");

	$(".cart_add").click(function() {
		var item_id = $(this).attr("item_id");
		var form_key = '#form_item' + item_id;
		var offset = $(this).offset()
		
		if ($(form_key).length > 0) {
			if($(form_key).attr('is_main') == 1) {
				showCartDialogParams(item_id);
			} else {
				$.post(
					$(form_key).attr('action'),
					$(form_key).serialize(),
					showCartDialog
				);
			}
		} else {
			$.get(
				this.href,
				showCartDialog
			);
		}
		return false;
	});
        
	$(".dialog_buy .ctrl_close").click(function() {
		$(".dialog_buy").hide('fast');
		return false;
	} );
        
	$(".dialog_buy_params .ctrlp_close").click(function() {
		$(".dialog_buy_params").hide('fast');
		return false;
	});
	
	$(".dialog_buy_params .ctrlp_order").click(function() {
		var item_id = $(this).parent('.dialog_buy_params').find('form').attr("item_id");
		var form_key = '#form_item_params' + item_id;
		updatePriceAtCount(item_id, true);
		
		$(".dialog_buy_params").hide('fast');
		if ($(form_key).length > 0) {
			$.post(
				$(form_key).attr('action'),
				$(form_key).serialize(),
				showCartDialog
			);
		}
		return false;
	});
	
	$("#basketform input.js_cnt").keyup(cartSumm);

        $("select.params_tovar").mousedown(function(){
                $(this).find(".params_tovar_empty").html('');        
        });

	$("select.params_tovar").change(function() {
		price = parseFloat($("#price_main").html());
		
		$("select.params_tovar").each(function() {
			var price_add = parseFloat($(this).find('option:selected').attr("price"));
			price = price + price_add;
		});
		$("#price_new").html(price);
		$("#hiddenprice").val(price);
	});
});

function cardval()
{
        if($('[name=card]').val()!=""){
                $('[name=card_discount]').removeAttr('disabled');
        }
        else{
                $('[name=card_discount]').attr('disabled','disabled');
        }
        
        return false;
}






