var recounter = $("#content");
recounter.resize(function(){
    //   this.he
    });



$(document).ready(function() {
    if ($.browser.msie) {
	IEpngFix();
    };
	
    var maxWidth = 1240; // max width
    var minWidth = 1000; // min width
    var selector = $("#main"); // selector
    var windowWidthTemp = 0;
    var windowWidth = 0;
	
    mmheight();
    function mmheight() {
	$("#nav1").height("");
	$("#nav2").height();
	var colHeight = $("#column").height();
	var contHeight = $("#content").height();
	var razn = contHeight - colHeight;
	//        var nav1_h = $("#nav1").height();
	//        var nav2_h = $("#nav2").height();
	if (razn > 0) {
	    $(".allrozpr").height(razn + 230);
	}
    };
	
    $("#content").resize(function() {
	mmheight();
    });
	
    //png fix for ie
    function IEpngFix() {
	if ($.browser.msie) {
	    var transparentImage = "i/tr.gif";
			
	    oImg = $("img[src$=.png].png");
	    lImg = $("img[src$=.png].png").length;
			
	    for (i = 0; i < lImg; i++) {
		srcImg = $(oImg[i]).attr("src");
		$(oImg[i]).attr({
		    src: transparentImage
		});
		oImg[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + srcImg + "',sizingMethod='scale')";
		oImg[i].style.display = "inline-block";
	    }
	}
    }
    if ($('ul.images').length > 0) {
	$('ul.images').jcarousel({
	    scroll: 3
	});
    }
    inputValue();
    if ($(".search .text").length > 0) {
	inputValue(".search .text");
    }
    function inputValue(input) {
	var asInitVals = new Array;
	$(input).each(function(i) {
	    asInitVals[i] = $(this).val();
	});
	$(input).focus(function() {
	    if ($(this).val() == asInitVals[$(input).index(this)]) {
		$(this).val("");
	    }
	});
	$(input).blur(function(i) {
	    if (!(jQuery.trim($(this).val()))) {
		$(this).val(asInitVals[$(input).index(this)]);
	    }
	});
    }
	
    if ($("#podbor select").length > 0) {
	podbor("#podbor select");
    }
    
    if ($("#podbor_cross select").length > 0) {
	podbor("#podbor_cross select");
    }
    
    
    function podbor(pSelector) {
	initPodbor(pSelector);
	$("body").delegate(pSelector, "change", function() {
	    //tName = $(this).attr("name");
	    tName = $(this).attr("id");
	    $(this).parents(".podborholder").append("<div class='wait'></div>");
	    $("#resetpodbor").show();
	    // если выбран cat, значит мы не на странице каталога, а на другой странице
	    // и необходимо подгрузить все атрибуты для подбора этого каталога
	    if(tName == 'cat') loadBasePodbor(tName);
	    else ajaxQuestion(pSelector, tName);
	});
		
	$("#resetpodbor").live("click", function(event) {
	    event.preventDefault();
	});
	$("#resetpodbor").live("click", function() {
	    $(this).parents("form").find("select option").removeAttr("disabled").removeAttr("selected");
	    $(this).hide();
//	    $("#search_btn span").text("подобрать");
            $("#search_btn").attr('disabled','disabled');
            $("#search_btn").val('Подобрать');
	});
		
	var cookieOptions = {
	    path: '/',
	    expires: 7
	};
		
	$("#search_more").click(function(event) {
	    event.preventDefault();
	});
	opend = $.cookie("open_dopsearch");
	if (opend) {
	    opend2 = 0;
	}
	opend = opend * 1;
	$("#search_more").click(function() {
	    if (!opend) {
		//ajaxlink = "/ajax/doppodbor.html";
		ajaxlink = "/ajax/dopparam";
		var param = "";
		fAction = "/";
		var catVal = $("#cat").val();
		fAction += "cat/" + catVal + "/";
		var brandVal = $("#podbor_brand_id").val();
		if (brandVal > 0) 
		    fAction += "brand/" + brandVal + "/";
		var attr_param = '';
		$("#podbor select").each(function(i, pItem) {
		    thisName = $(this).attr("id");
		    thisVal = $(this).val();
		    if (i == 0 || i == 1) { // для цен и коллекций
			if (thisVal > 0) 
			    fAction += thisName + "/" + thisVal + "/";
		    }
		    else { // для атрибутов
			if (thisVal > 0) {
			    attr_id = thisName.replace(/^attr_/, '');
			    attr_param += "a" + attr_id + 'v' + thisVal;
			}
		    }
		});
				
		if (attr_param.length > 0) 
		    attr_param = 'at/' + attr_param + '/';
				
		param = fAction + attr_param;
		fAction += attr_param;
		ajaxlink += param;
				
		$(this).parents(".podborholder").append("<div class='wait'></div>")
		$(".search_more").load(ajaxlink, function() {
		    wait = $(".wait").length;
		    if (wait > 0) {
			$(".wait").remove();
		    };
		    $("#search_more").text("меньше параметров");
					
		    $.cookie("open_dopsearch", "1", cookieOptions);
		    initPodbor(pSelector);
		});
		opend = 1;
		opend2 = 0;
	    }
	    else {
		if (opend2) {
		    $(".search_more").slideDown();
		    $("#search_more").text("меньше параметров");
		    $.cookie("open_dopsearch", "1", cookieOptions);
		    opend2 = 0;
		}
		else {
		    $(".search_more").slideUp();
		    $("#search_more").text("больше параметров");
		    $.cookie("open_dopsearch", "0", cookieOptions);
		    opend2 = 1;
		}
	    }
	})
    };
	
    $("#search_btn").live("click", function(event) {
	event.preventDefault();
    });
    $("#search_btn").live("click", function() {
	thisURL = $(this).parents("form").attr("action");
	window.location = thisURL;
    });

    function loadBasePodbor(){
	var catVal = $("#cat").val();
	var ajaxlink = "/ajax/basepodbor/cat/" + catVal;
	$.getJSON(ajaxlink, function(data) {
	    $("#podbor-param").html(data.param);
	    $("#search_btn span").html('найти');
	    initPodbor("#podbor select");
	});
    }

    function ajaxQuestion(thisSelector, fName) {
	var ajaxlink = "/ajax/podbor";
	var param = "";
	fAction = "/";
	var catVal = $("#cat").val();
	
	// Выясняем какой подбор пришёл
	if (thisSelector == '#podbor_cross select'){
	     fAction += catVal + "/all/";
	} else	
	    fAction += "cat/" + catVal + "/";
	//	fAction += catVal;
	var brandVal = $("#podbor_brand_id").val();
	if (brandVal) 
	    fAction += "brand/" + brandVal + "/";
	var attr_param = '';
	$(thisSelector).each(function(i, pItem) {
	    thisName = $(this).attr("id");
	    thisVal = $(this).val();
	    if (thisName == 'price' || thisName == 'collect') { // для цен и коллекций
		if (thisVal > 0) 
		    fAction += thisName + "/" + thisVal + "/";
	    }
	    else { // для атрибутов
		if (thisVal > 0) {
		    attr_id = thisName.replace(/^attr_/, '');
		    attr_param += "a" + attr_id + 'v' + thisVal;
		}
	    }
	});
		
	if (attr_param.length > 0) 
	    attr_param = 'at/' + attr_param + '/';
		
	param = fAction + attr_param + "fname/" + fName + "/";
	fAction += attr_param;
	ajaxlink += param;
		
	$(thisSelector).parents("form").attr({
	    "action": fAction
	});
		
	$.getJSON(ajaxlink, null, function(data) {
	    $.each(data.name, function(i) {
		thisID = '';
		for (var name in this) {
		    thisID += name
		};
		thisObj = eval("this." + thisID);
		$(thisObj).each(function(j) {                                    
		    if (!this.dis) {
			$("#" + thisID + "_" + this.val).attr({
			    "disabled": "disabled"
			});
		    }
		    else {
			$("#" + thisID + "_" + this.val).attr({
			    "disabled": ""
			});
		    }
		});
				
	    });
//	    $("#search_btn span").text(data.finds);
            $("#search_btn").val(data.finds);
            $("#search_btn").removeAttr('disabled');

	    wait = $(".wait").length;
	    if (wait > 0) {
		$(".wait").remove();
	    };
	});
    }
    function initPodbor(sel) {
	$(sel).each(function() {
	    var thisID = $(this).attr("id");
	    var thisName;
	    $(this).find("option").each(function(i) {
		thisVal = $(this).val();
		$(this).attr({
		    "id": thisID + "_" + thisVal
		});
	    });
	});
    }
	
	
    function callBackTov(result) {
	$(".basket .list").html(result.res);
	wait = $(".wait").length;
	if (wait > 0) {
	    $(".wait").remove();
	}
    }
	
	
	
    $(".product-selection").live("click", function(event) {
	event.preventDefault();
    });
    var cookieOptions = {
	path: '/',
	expires: 7
    };

    function add2Cart(thisTovar, ajaxlink, callBackFunc) {
	id = $(thisTovar).attr("id");
	realID = id.replace("it-", "");
	// передаем ID товара
	ajaxlink += 'item_id/' + realID + '/';
	count = $("input." + id).val();
	// передаем атрибуты: необходимое кол-во товара (и доп.атр. типа "ширина рулона" если необходимо)
	ajaxlink += 'at/a0v' + count;
		
	//alert('count2='+count2+',length='+count2.length);
	if ($("select." + id).val()) {
	    //alert ('ok');
	    strAttrID = $("select." + id).attr("id");
	    attrID = strAttrID.replace("attr_", "");
	    ajaxlink += 'a' + attrID + 'v' + $("select." + id).val();
	}
	ajaxlink += '/';
		
	//alert(ajaxlink);
		
	$.getJSON(ajaxlink, null, function(data) {
	    callBackFunc(data);
	});
    };
	
	
	
    popup(".show a");
    $("#sendphone").live("click", function() {
	//ajaxurl="/ajax/phone.php"
	ajaxurl = "/ajax/leavephone/";
	var phone = $(this).parents("form").serialize();
	thisBTN = $(this);
	$.getJSON(ajaxurl, phone, function(data) {
	    valid = data.valid * 1;
	    if (valid) {
		$(thisBTN).parents("form").find(".row").remove();
		$(thisBTN).parents("form").find(".time").remove();
		$(thisBTN).parents("form").find(".errhold").html(data.mess);
		$(thisBTN).remove();
		setTimeout(popupchickClose, 1500)
	    }
	    else {
		$(thisBTN).parents("form").find(".errhold").html(data.mess);
	    }
	})
    });
    function popupchickClose() {
	$(".popupchik").remove();
    }
	
    function popup(open_btn) {
	
	$(".close, .close-popup").live("click", function(event) {
	    event.preventDefault();
	});
	$(".close, .close-popup").live("click", function() {
	    $(".popupchik").remove();
	});
	$(open_btn).click(function(event) {
	    event.preventDefault();
	});
	$(open_btn).click(function(e) {
	    $(".popupchik").remove();
	    $("*:not(.popupchik)").click(function(e) {
		kids = e.target;
		var _a = kids;
		while (true) {
		    _atag = _a.tagName;
		    if (_atag && ($(_a).hasClass('popupchik'))) {
			break;
		    }
		    else {
			if (!_atag) {
			    $(".popupchik").remove();
			    break;
			}
			_a = _a.parentNode;
		    }
		}
	    });
	    //selector = $(this).parent();
			
	    ajaxlink = $(this).attr("href");
	    $.get(ajaxlink, function(data) {
		$("body").append('<div class="popupchik"></div>');
		$(".popupchik").css({
		    right: winWidth - e.pageX,
		    top: e.pageY
		});
		selector = $(".popupchik");
		$(selector).prepend(data);
		inputValue(".text");
	    });
			
	});
    }
	
    $(".submitform").live("click", function() {
	$(this).parents("form").submit();
    });
    if ($('.zakaznuber').length > 0) {
	$('.zakaznuber').toggle(function() {
	    $(this).addClass("aaa");
	    $(".aaa span").addClass('open');
	    $(this).find("em").css({
		display: "none"
	    });
	    $(this).next().slideDown("slow");
	}, function() {
	    $(this).find("em").css({
		display: "block"
	    });
	    $(".aaa span").removeClass('open');
	    $(this).removeClass("aaa");
	    $(this).next().slideUp("slow");
	})
    }
    if ($(".gallery2 .list li").length > 0) {
	$(window).load(function() {
	    hFix($(".gallery2 .list li"));
	});
    }
    if ($(".tovars li").length > 0) {
	$(window).load(function() {
	    hFix(".tovars li");
	});
    }
    function hFix(tov) {
	
	var tovar = $(tov);
	$(tovar).height("auto");
	var tovarLength = $(tovar).length;
	var maxHeight = 0;
	for (i = 0; i < tovarLength; i++) {
	    tovHeight = $(tovar[i]).height();
	    if (maxHeight < tovHeight) {
		maxHeight = tovHeight;
	    }
	}
	$(tovar).height(maxHeight);
		
    }
    //    menu_slider();
    function menu_slider() {
	$(".side-nav ul").hide();
	$(".side-nav #current").addClass("active").parents("ul").show();
	$(".side-nav #current").parents("li").addClass("active");
	$(".side-nav #current")
		
		
	$(".side-nav li a").click(function(event) {
	    activ = $(this).parent().hasClass("active")
	    nextTag = $(this).next().attr("tagName");
	    if ((!activ) && (nextTag == "UL")) {
		event.preventDefault();
		$(this).parent().addClass("active");
		$(this).next().slideDown(500);
	    }
	    else {
		if (nextTag == "UL") {
		    event.preventDefault()
		    thisParent = $(this).parent();
		    thisNext = $(this).next();
		    $(thisNext).slideUp(500);
		    $(thisNext).queue(function() {
			$(thisParent).removeClass("active");
			$(this).dequeue();
		    });
		}
		else {
		    return true
		};
	    }
	});
    }
	
    by_popup();
    function by_popup() {
	byCalc = $("<div class='by_calc'><div>").hide().appendTo("body");
	winWidth = $("body").width();
	var keyUpTime = 700; // Время задержки между вводом колличества товара
	var keyUpTimeout;
		
	var tovID;
	$('.by_calc .close , .by_calc .cancel').live("click", function() {
	    $(byCalc).fadeOut(250);
			
	});
	$(".add-btn").click(function(event) {
	    event.preventDefault();
	    $(byCalc).fadeOut(250);
	    $("body").undelegate(".by_calc input[type=radio]", "change");
	    $("body").undelegate(".by_calc input[type=text]", "keyup");
	    tovID = $(this).parents("tr").attr("id");
	    tovID = tovID.replace('tov', '');
	    ajaxurl = "/ajax/calc/id/" + tovID + '/';
	    //ajaxurl = "/ajax/calc_by.html";
	    $.get(ajaxurl, tovID, function(data) {
		$('.by_calc').css({
		    right: winWidth - event.pageX,
		    top: event.pageY
		}).html(data).fadeIn(250);
	    });
	    $("body").delegate(".by_calc input[type=radio]", "change", function() {
		calculate(tovID);
	    });
	    $("body").delegate(".by_calc input[type=text]", 'keyup', function() {
		clearTimeout(keyUpTimeout);
		keyUpTimeout = setTimeout(
		    function(){
			calculate(tovID)
		    },
		    keyUpTime
		    )
	    })
	});
	if ($("#tovar").length>0){
	    tovID = $("#tovar").find(".by_calc").attr("id");
	    tovID = tovID.replace('tov', '');
	    //            var keyUpTime = 700; // Время задержки между вводом колличества товара
	    //            var keyUpTimeout;
	    $("body").delegate(".by_calc input[type=radio]", "change", function() {
		calculate(tovID);
	    });
	    $("body").delegate(".by_calc input[type=text]", 'keyup', function() {
		clearTimeout(keyUpTimeout);
		keyUpTimeout = setTimeout(function(){
		    calculate(tovID)
		    }, keyUpTime);
	    });
	}
	function calculate(thisID) {
	    //var ajaxurl = '/ajax/calc.json';
	    // FIXME: URL сделать константой
	    var ajaxurl = '/ajax/calcpricejson/';
	    var fields = $(".by_calc input[type=text]");
	    var pm = '';
			

	    $.each(fields, function(i, field) {
		if (field.value) {
		    var fv = field.value;
		    var correct = fv.replace(/[^0-9,.]/g,'');
		    $(".by_calc input[type=text]").val(correct);
		    pm += 'a' + 0 + 'v' + correct;
		}
	    });
	    $(".by_calc").prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
	    param = 'item_id/' + thisID + "/at/";
	    param += pm;
	    if ($(".by_calc input[type=radio]").length>0){
		rulonWidth = $(".by_calc input[type=radio]:checked");
		rulonWidthAttr = $(rulonWidth).attr("name");
		rulonWidthAttr = rulonWidthAttr.replace('attr_', '');
		rw = "a" + rulonWidthAttr + "v" + $(rulonWidth).val();
		param += rw;
	    }
	    ajaxurl += param+'/';
	    // TODO: Меняем кнопку на неактивную
	    // do somthing
	    $.getJSON(ajaxurl, function(data) {
		$(".by_calc .total em").html(data.total);
		$(".by_calc .sale em").html(data.price);
		$(".by_calc .count").html(data.count);
		if (data.sale) $("#sale").html(data.sale);
		else $("#sale").html("");
		// TODO: Меняем кнопку на активную
		$("#tov_overlay").remove();
				
	    })
	}

        
	$('.by_calc .btn-add').live("click", function(event) {
	    event.preventDefault();
	});
        
	$('.by_calc .btn-add:not(#tovar .btn-add)').live("click", function() {
	    $(".by_calc").prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
	    clickingAdd(tovID);
	});
        
	$('.btn-add').live("click", function(event) {
	    event.preventDefault();
	});
        
	/*$('.by_calc .btn-add:not(#tovar .btn-add)').live("click", function() {
            //var ajaxurl = '/ajax/bytov.json';
            var ajaxurl = '/ajax/addcart/';
            var fields = $(".by_calc input[type=text]");
            var pm = '';
                				
                				
            $.each(fields, function(i, field) {
                if (field.value) {
                    pm += 'a' + 0 + 'v' + field.value;
                }
            });
            param = 'item_id/' + tovID + "/at/";
            $(".by_calc").prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
            param += pm;
            if ($(".by_calc input[type=radio]").length>0){
                rulonWidth = $(".by_calc input[type=radio]:checked");
                rulonWidthAttr = $(rulonWidth).attr("name");
                rulonWidthAttr = rulonWidthAttr.replace('attr_', '');
                rw = "a" + rulonWidthAttr + "v" + $(rulonWidth).val();
                param += rw;
            }
            thisBTN = $(this);
            ajaxurl += param;
            $.getJSON(ajaxurl, function(data) {
                $(".basket .list").html(data.cart_html);
                //$("#tov" + tovID).find(".item-price").after("<div class='bytext'>" + data.by_text + "</div>");
                $("#tov" + tovID).find(".bytext").html(data.by_text);
                //$(thisBTN).parents("tr").before("<tr><td colspan='2'>" + data.by_text_item + "</td></tr>")
                $(".by_calc .item-bytext").html(data.by_text_item);
                $("#tov_overlay").remove();
            })
        });
        */
		
		
	$('.btn-add').click(function() {
	    if ($.trim($("#kolvo_unit").val()) =='') return;
	    $("#tov"+tovID).prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
	    clickingAdd(tovID);
	})
    };
    
    /**
     * Добавить товар в корзину
     * @param tovID ID товара для добавления
     */
    function clickingAdd(tovID){
	//var ajaxurl = '/ajax/bytov.json';
	var ajaxurl = '/ajax/addcart/';
//	var fields = $(".by_calc input[type=text]");
        var fields = $("#kolvo_unit");
	var pm = '';                       
	$.each(fields, function(i, field) {
	    if (field.value != '') 
		pm += 'a' + 0 + 'v' + $.trim(field.value);
                
	});
            
	if (!pm) {
	    $("#tov_overlay").remove();
	    return false;
	}
	param = 'item_id/' + tovID + "/at/";
       
	param += pm;

	$.each($("td input[id^=attr]:checked") ,function(index, fields){
	    rulonWidthAttr = fields.name;
	    rulonWidthAttr = rulonWidthAttr.replace('attr_', '');
	    rw = "a" + rulonWidthAttr + "v" + fields.value;
	    param += rw;
	});

	//                         if ($(".by_calc input[type=radio]").length>0){
	//                            rulonWidth = $(".by_calc input[type=radio]:checked");
	//                            rulonWidthAttr = $(rulonWidth).attr("name");
	//                            rulonWidthAttr = rulonWidthAttr.replace('attr_', '');
	//                            rw = "a" + rulonWidthAttr + "v" + $(rulonWidth).val();
	//                            param += rw;
	//                        }
	thisBTN = $(this);
	ajaxurl += param + "/";
	$.getJSON(ajaxurl, function(data) {
	    //	    $(".basket .list").html(data.cart_html);
	    // Устанавливаем значения общей суммы и товаров в корзине
	    $(".basket .list li:first span").html(data.total_amount);
	    $(".basket .list li:eq(1) span:first").html(data.total_cost);
	    
	    
	    //$("#tov" + tovID).find(".item-price").after("<div class='bytext'>" + data.by_text + "</div>");
	    //            $("#tov" + tovID).find(".item-bytext").html(data.by_text_item);
	    $(".item-bytext").html(data.by_text_item);
	    $(".cart-bytext").html(data.by_text);
	    $("#kolvo_unit").val('');
	    $("#tov_overlay").remove();
	})
        
    }
    
    
    
    if ($("#tabs li").length) {
	tabs("#tabs");
    }
    else {
	$("#tab_content").hide();
    }
    function tabs(tab) {
	$(tab).find("li a").click(function(event) {
	    event.preventDefault();
	});
	var activeTab = $(tab).find("li:first").addClass("active").attr("id");
	var thold = $(tab).parents('.tabsholder');
	if ($(thold).find(".tb").length) {
	    $(thold).find(".tb").hide();
	    $(thold).find(".tb").css({
		"visibility": "visible"
	    });
	    $(thold).find("." + activeTab).show();
	    $(tab).find("li").click(function() {
		activeTab = $(this).attr("id");
		$(thold).find(".tb").hide();
		$(thold).find("." + activeTab).show();
		$(tab).find("li").removeClass("active");
		$(this).addClass("active");
		if ($(".gallery2 .list li").length > 0) {
		    hFix($(".gallery2 .list li"));
		}
		if ($(".tovars li").length > 0) {
		    hFix(".tovars li");
		}
	    })
	}
    }
    /**Корзина**/
	
    // Отрабатываем выбор доставки    
    $("select[name=delivery_select]").change(function() {
	$(".shopcart .table").parent("div").prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
        
	ajaxlink = '/ajax/changedelivery/dost/' + $(this).val();
	$.getJSON(ajaxlink, function(data) {
            
	    //            $('#totalprice em').text(data.total);
	    $('#total_dost em').text(data.total_dost);
            
	    $("#tov_overlay").remove();
	});
        
    });    
    

    // Отрабатываем удаление из корзины
    var shopcard = ".shopcart .table";
    var arrKolvo = new Array;
    removTov(shopcard);
    function removTov(table) {
	$("#remove").hide();
	//$("#salelist").hide();
	var thisTr = $(table + ' tbody tr.formadd');
	//        var thisTrLength = $(thisTr).length;
	var thisCheckbox = $(thisTr).find("input:checkbox ");
	//	$(thisCheckbox).change(function() {
	//	    cartCheckForDelete(this);
	//	});
	
	$(thisCheckbox).live('click', function(event, aParam) {
	    if (!aParam)  cartCheckForDelete(this);
	});
    }
    
    
    function cartCheckForDelete(cursor){
	var thisTr = $('.shopcart .table tbody tr.formadd');
	var thisTrLength = $(thisTr).length;
	var thisCheckbox = $(thisTr).find("input:checkbox ");
	var checked = false;
	checked = $(cursor).attr("checked");
	indexCheck = $(thisCheckbox).index(cursor);
	thisCount = $(thisTr[indexCheck]).find("input.count");
	if (checked) {
	    arrKolvo[indexCheck] = $(thisCount).val();
	    $(thisCount).val("0");
	    thisID = $(cursor).parents('tr.formadd').attr('id');
	    incValueLoad(shopcard, thisID);
	}
	else {
	    $(thisCount).val(arrKolvo[indexCheck]);
	    thisID = $(cursor).parents('tr.formadd').attr('id');
	    incValueLoad(shopcard, thisID);
	}
	var checked3;
	for (i = 0; i < thisTrLength; i++) {
	    checked2 = $(thisCheckbox[i]).attr("checked");
	    checked3 = checked3 || checked2;
	    if (checked3) {
		$("#remove").show();
	    }
	    else {
		$("#remove").hide();
	    }
	}
    }
    
    /**
	 * Функция серверного расчёта цен
	 */
    if ($("#remove").length > 0) {
	$("#remove").click(function() {
	    var thisTr = $(shopcard + ' tr');
	    var thisChecked = $(thisTr).find("input:checked");
	    var thisCheckbox = $(thisTr).find("input:checkbox");
	    var lenTD;
	    if ($(thisCheckbox).length == $(thisChecked).length) {
		ajaxlink = "/ajax/clearcart/";
		//ajaxlink = "/ajax/cart.json";
		$.getJSON(ajaxlink, function(data) {
		    $(".shopcart").html(data.cart_text);
		    $(".basket .list").html(data.cart_html);
		});
	    }
	    else {
		removed = $(thisChecked).parents('.formadd');
		lenTD = $(removed).find('td').length;
		ajaxlink = "/ajax/delitem/";
		//ajaxlink = "/ajax/cart.json";
		$.getJSON(ajaxlink, function(data) {
		    $(removed).hide();
		    $(removed).before("<tr><td colspan=" + lenTD + " align='left'><a class='undo' href='#'>Отменить удаление товара</a></td></tr>");
		    $(".basket .list").html(data.cart_html);
		    $("#remove").hide();
		});
	    }
	});
    }
    $('.undo').live("click", function(event) {
	event.preventDefault();
	$(this).parents("tr").next(".formadd").show();
	$(this).parents("tr").remove();
    })
    if ($("#clearcart").length > 0) {
	$("#clearcart").click(function() {
	    if (confirm('Вы уверены, что хотите удалить из корзины все товары?')) {
		ajaxlink = "/ajax/clearcart/";
		//ajaxlink = "/ajax/cart.json";
		$.getJSON(ajaxlink, function(data) {
		    $(".shopcart").html(data.cart_text);
		    $(".basket .list").html(data.cart_html);
		});
	    }
	});
    }
    /**
      * Формируем и отсылаем URL для пересчёта корзины
      * @param table
      * @param thisId
      */
    function incValueLoad(table, thisId) {
	$(table).parent("div").prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
	var thisTr = $(table + ' tbody tr');
	var thisTrLength = $(thisTr).length;
	var thisCheckbox = $(thisTr).find("input:checkbox ");
	var checked3;
	var itm_str = thisId.replace('itm_', '');
	itm_id_tmp = itm_str.indexOf("_");
	if(itm_id_tmp > 0){
	    itm_id = itm_str.slice(0,itm_id_tmp);
	    itm_unit = itm_str.slice(itm_id_tmp+1,itm_str.length);
	}
	else{
	    itm_id = itm_str;
	    itm_unit =  '';
	}
	var itm_count = $('#' + thisId).find('.count').val();
	//var itm_unit = $('#' + thisId).attr('itm_unit');
	var dost = $('#dost select').val();
	//var ajaxlink = '/ajax/cart.json';
	var ajaxlink = '/ajax/rcart/' + 'item_id/' + itm_id + '/at/a0v' + itm_count;
        
	
	//	if(itm_unit) ajaxlink += itm_unit;
	ajaxlink += '/cId/'+itm_unit;
	if(dost) ajaxlink += '/dost/' + dost;
		
		
	for (i = 0; i < thisTrLength; i++) {
	    checked2 = $(thisCheckbox[i]).attr("checked");
	    checked3 = checked3 || checked2;
	    if (i == thisTrLength - 1) {
		if (checked3) {
		    $("#remove").show();
		}
		else {
		    $("#remove").hide();
		}
	    }
	}
	$.getJSON(ajaxlink, function(data) {
	    $('#totalprice em').text(data.total);
	    $(".basket .list").html(data.cart_html);
	    $('#total_dost em').text(data.total_dost);
	    if (data.sale){
		$("#salelist").show();
		$('#sale em').text(data.sale);
	    }else{
		$("#salelist").hide();
	    }
	    $(data.prices).each(function(i) {
		$("#" + this.id).find(".cena1 em").text(this.price);
		$("#" + this.id).find(".cena2 em").text(this.cena);
		//				$("#" + this.id).find(".p_up span").text(this.p_up);
		$("#" + this.id).find(".z_kol").text(this.z_kol);
		$("#" + this.id).find(".r_kol").text(this.r_kol);
	    //				$("#" + this.id).find(".kol_up span").text(this.kol_up);
	    })
	    $("#tov_overlay").remove();
	//$(".basket .list").html(data.cart_html);
	});
    }
    /**
	 * Функция инкрементирования и декрементирования значений колличества товаров
	 */
    if ($('.counter .count').length > 0) {
	incValue();
    }
    function incValue() {
	/*		var incVal;
		$('.plus, .minus').live("click", function(event) {
			event.preventDefault();
		});
		$('.plus').click(function() {
			thisInc = $(this).parent().prev();
			incVal = $(thisInc).val();
			if (incVal == 0) {
				$(this).parent().parent().parent().parent().find("input:checkbox").trigger('click');
			}
			incVal++;
			$(thisInc).val(incVal);
			thisID = $(this).parents('tr.formadd').attr('id');
			incValueLoad(shopcard, thisID);
		})
		$('.minus').click(function() {
			thisInc = $(this).parent().prev();
			incVal = $(thisInc).val();
			if (incVal > 0) {
				incVal--;
				if (incVal == 0) {
					$(this).parent().parent().parent().parent().find("input:checkbox").trigger('click');
				}
				$(thisInc).val(incVal);
			}
			thisID = $(this).parents('tr.formadd').attr('id');
			incValueLoad(shopcard, thisID);
		});*/
		
	var valBefore;
	var keyUpTimeout;
	var keyUpTime = 700;
	$(".count").focus(function(e) {
	    valBefore = $(this).val();
	});
	$(".count").keyup(function(e) {
            
            
            
	    var fv = $(this).val();
	    var correct = fv.replace(/[^0-9,.]/g,'');
	    $(this).val(correct);
	    checkInputForDelete = $(this).parent().parent().parent().find("input:checkbox");
		
	    if (valBefore == 0) {
		    
		//		checkInputForDelete.die('click');	
		    
		checkInputForDelete.trigger('click', ["gt"]);
	    //		    $(thisCheckbox).change(function() {
	    //			cartCheckForDelete(this);
	    //		    });
	    }
	    else {
		$(this).parent().parent().parent().find("input:checkbox").attr({
		    "checked": ""
		});
	    }
	    thisID = $(this).parents('tr.formadd').attr('id');
	    clearTimeout(keyUpTimeout);
	    keyUpTimeout = setTimeout(
		function(){
		    incValueLoad(shopcard, thisID);
		},
		keyUpTime
		)
            
            
	/*
	    if (((48 <= e.which) && (e.which <= 57)) || ((96 <= e.which) && (e.which <= 105)) || (e.which == 8) || (e.which == 39) || (e.which == 37) || (e.which == 46) || (e.which == 27) || (e.which == 17) || (e.which == 16)) {
		thisKolvo = $(this).val();
		valBefore = $(this).val();
		checkInputForDelete = $(this).parent().parent().parent().find("input:checkbox");
		
		if (valBefore == 0) {
		    
//		checkInputForDelete.die('click');	
		    
		checkInputForDelete.trigger('click', ["gt"]);
		//		    $(thisCheckbox).change(function() {
		//			cartCheckForDelete(this);
		//		    });
		}
		else {
		    $(this).parent().parent().parent().find("input:checkbox").attr({
			"checked": ""
		    });
		}
		thisID = $(this).parents('tr.formadd').attr('id');
		clearTimeout(keyUpTimeout);
		keyUpTimeout = setTimeout(
		    function(){
			incValueLoad(shopcard, thisID);
		    },
		    keyUpTime
		    )
				
	    }
	    else {
		$(this).val(valBefore);
		thisID = $(this).parents('tr.formadd').attr('id');
		clearTimeout(keyUpTimeout);
		keyUpTimeout = setTimeout(
		    function(){
			incValueLoad(shopcard, thisID);
		    },
		    keyUpTime
		    )
	    }*/
	});
    };
    
    
    
    if ($(".ask").length > 0) {
	$(".ask").hide();
	$("#oformit").toggle(function() {
	    $(".ask").slideDown();
	    //            $("body").scrollTo($("a[href=#bottom_sender]"), 800, {onAfter:function(){
	    //                    
	    //                     $(".ask").slideDown();
	    //            }});
           
	    $("body").scrollTo('5004%', 800);
	}, function() {
	    $(".ask").slideUp()
	});
    }
	
    $('.zakaznuber').toggle(function() {
	$(this).addClass("aaa");
	$(".aaa span").addClass('open');
	$(this).find("em").css({
	    display: "none"
	});
	$(this).next().slideDown("slow");
    }, function() {
	$(this).find("em").css({
	    display: "block"
	});
	$(".aaa span").removeClass('open');
	$(this).removeClass("aaa");
	$(this).next().slideUp("slow");
    });
	
    $(".send-btn").click(function(event) {
	event.preventDefault();
    });
    $(".send-btn").click(function() {
	var errorVal = "поле обязательно для заполнения";		
	var starLenght;
	var k = 0;
	star = $("#cart_form span");
	starLenght = $(star).length;
	for (i = 0; i < starLenght; i++) {
	    idInput = $(star[i]).parent().attr("for");
	    valInput = $("#" + idInput).val();
	    if ((valInput == "") || (valInput == errorVal)) {
		k++;
		$("#" + idInput).addClass("star").val(errorVal);
	    }
	}
	if (k == 0) {
	    $('#cart_form').submit();
	}
	else {
	    formInputVal();
	}
    });
    function formInputVal() {
	formInput = "#cart_form input";
	className = "star";
	var asInitVals = new Array();
	$(formInput).each(function(i) {
	    asInitVals[i] = $(this).val();
	});
		
	$(formInput).focus(function() {
	    if ($(this).hasClass(className)) {
		$(this).removeClass(className);
		$(this).val("");
	    }
	});
	$(formInput).blur(function(i) {
	    thisValue = $.trim(this.val());
	    if (thisValue == "") {
		$(this).addClass(className);
		this.val(asInitVals[$(formInput).index(this)]);
	    }
	});
    }
});

