$(document).ready(function(){
	$(".contact_window").colorbox();
    $(".count1").keypress(function(event){if (event.keyCode==13){recount();}});
	$(".count1").click(function(){if($(this).val()=="0")$(this).val("");});
    $(".refresh").click(recount);
    $(".delete").click(deleteGood);
    $("tr.line:odd").css("background-color","#eeeeee");
    $(".refresh,.delete").hover(function(){
		$(".refresh,.delete").css("cursor","pointer");if($(this).attr("class")=="delete"){
		$(this).attr("src","http://www.bypowerlifting.ru/templates/Powerlifting/shop/icon/002.gif");} else 
		$(this).attr("src","http://www.bypowerlifting.ru/templates/Powerlifting/shop/icon/001.gif");},
			function(){$(".refresh,.delete").css("cursor","default");if($(this).attr("class")=="delete"){
				$(this).attr("src","http://www.bypowerlifting.ru/templates/Powerlifting/shop/icon/002b.gif");} else
				$(this).attr("src","http://www.bypowerlifting.ru/templates/Powerlifting/shop/icon/001b.gif");});
});

function serialize(mixed_value) {
    var _getType = function( inp ) {
        var type = typeof inp, match;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function" && ktype == "object") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

function shop(form) {
	$(".scount").attr("disabled", "disabled");
	$(".sbutton").attr("disabled", "disabled");
	$(".cart_success").show(900,function () { sleep(500);$(".cart_success").hide(1000);});
	$.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru/post.php",
		data: "id="+form.id.value+"&work=add&count="+form.scount.value,
		success: cartAddResponse
	});
}

function AddComp(id, cat) {
	
	$.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru//engine/modules/shop/ajax/comparison.php",
		data: "id="+id+"&cat="+cat,
		success: ComparisonResponse
	});
}

function DelComp(id) {
	$.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru//engine/modules/shop/ajax/comparison_del.php",
		data: "id="+id,
		success: ComparisonDelTd
	});
}

function CompClear() {
	$.ajax({
		type: "POST",
		url: "http://shop//engine/modules/shop/ajax/comparison_clear.php",
		data: "",
		success: function() { $("#comp").css('background-color','#ff6666'); $("#comp").fadeOut(); $("#s_comp").text('0');}
	});
}

function ComparisonDelTd(id) {
	$(".ctd_"+id).css('background-color','#ff6666');
	$(".ctd_"+id).fadeOut();
	$("#s_comp").text(parseInt($("#s_comp").text())-1);
}

function recount()
{
    $(".count1").attr("disabled", "disabled");
    var id = new Array();
	var count = new Array();
	num = ($(".count1")).length;
	for(i=0;i<num;i++)
	{
		quantValue = $(".count1:eq("+i+")").val();
		count[count.length] = quantValue;
		idValue = $(".id:eq("+i+")").val();
		id[id.length] = idValue;
	}
	count = serialize(count);
	id = serialize(id);
	$.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru/post.php",
		data: "id="+escape(id)+"&count="+escape(count)+"&work=recount",
		success: cartRecountResponse
	});
}

function removeTr(obj)
{
    var link=obj.parent().parent();
    link.css('background-color','#ff6666');
    link.fadeOut();
}

function deleteGood()
{
    $(".count1").attr("disabled", "disabled");
	var id = $(this).parent().siblings().children(".id").val();
    $.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru/post.php",
		data: "id="+escape(id)+"&work=delete",
		success: cartDeleteResponse
	});
    removeTr($(this));
}

function CompNoSov() {
	$("#comp tr").each(function(){
     var a = $(this).children("td:not(:first)");
	 var count = 0;
     for(var i=1;i<a.length;i++) {
		if(a[i].innerHTML == a[0].innerHTML) count++;
	 }
	 if(count == a.length-1) {
		a.parent().css('background-color','#ff6666');
		a.parent().fadeOut();
	 }
  });
}

function showNewPrice(textVal)
{
    var tmp = textVal.split(';');
	var tovar = tmp[0];
	var summa = tmp[1];
	var discount = tmp[2];
	$("#tovar").text(tovar);
	$("#summa").text(summa);
	$("#discount").text(discount);

    return summa;
}
function cartDeleteResponse(response)
{
    var summa = showNewPrice(response);
		$("#summa_cart").text(summa);
		$(".count1").attr("disabled", "");
}

function ComparisonResponse(response) {
	response = response.split(';');
	if(response[0]==1) {
		$("#c_"+response[1]).text('Убрать');
	} else {
		$("#c_"+response[1]).text('Добавить');
	}
	$("#s_comp").text(response[2]);
}

function cartAddResponse(response)
{
	showNewPrice(response);
	$(".button").attr("disabled", "");
}

function cartRecountResponse(response)
{
    var num = ($(".count1")).length;

	for(var i=0;i<num;i++)
	{
        var quantVal = $(".count1:eq("+i+")").val();
        
		if(quantVal==0)
        {
            removeTr($(".count1:eq("+i+")"));
        }
        else
        {
            var price = $(".price:eq("+i+")").text();
            var newSum = Number(quantVal)*Number(price);
            $(".sum:eq("+i+")").text(newSum.toFixed(2));
        }
	}

    cartDeleteResponse(response);
}

function send_contact() {
$.ajax({
	type: "POST",
	url: 'http://www.bypowerlifting.ru/engine/modules/shop/contact.php',
	dataType: 'html',
	data: $('.go_contact').serialize() + '&zakaz=send',
	cache: false,
	complete: function (xhr) {
		if(xhr.responseText=='ok') {
			DelAll();
			$.fn.colorbox({html: '<h3 style="text-align:center;">Ваш заказ принят!<h3>'});
		} else {
			alert(xhr.responseText);
		}
	}
	});
return false;
}

function DelAll()
{
	var link = document.getElementById("cart_content");
	while (link.firstChild)
		link.removeChild(link.firstChild);
}

function IlusiaRating(rate) {
	 $.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru/engine/modules/shop/ajax/ilusirating.php",
		dataType: 'html',
		data: 'rate='+rate,
		cache: false,
		complete: function (xhr) {
		document.getElementById('add_comm_hide').value = rate;
		$('#add_comm_rating').html(xhr.responseText).fadeIn(200);
		}
	});
}

function ShopRating(rate, id) {
    $.ajax({
		type: "POST",
		url: "http://www.bypowerlifting.ru/engine/modules/shop/ajax/rating.php",
		dataType: 'html',
		data: 'rate='+rate+'&id='+id,
		cache: false,
		complete: function (xhr) {
		$('#ratig-layer_'+id).html(xhr.responseText).fadeIn(200);
		}
	});
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	while ((new Date().getTime() - start) < milliseconds){}
}