$(document).ready(function(){     	$(".mini_imgs a").click(function() {		$(".mini_imgs a").removeClass("active");		$(this).addClass("active");	});
    	var hash = location.hash;	if (hash == '#oformlen') {		$(".undercart_wrap.history .head a").removeClass("active");		$(".undercart_wrap.history .head a:eq(1)").addClass("active");			$(".undercart_wrap.history .body .contentTab").hide();		$(".undercart_wrap.history .body .contentTab:eq(1)").show();	}	if (!$("#main_menu").hasClass("noDel")) {		$("#main_menu").remove();	}	$.get("/public/menu.txt", function(data){				$("#menuCont").append(data);	});		$("#allBrands").change(function() {		var e = $(this);		location.href = e.attr("value");			});		$(".showText").click(function() {				$(this).toggleClass("active");		$(this).next().slideToggle(300,'swing');		return false;			});
    if ($("input#region-1").attr('checked')) {
        $("#town-wrap").show();
    } else {
        $("input#region-0").attr('checked', true);
    }    
    if ($("#password_choose-1").attr('checked')) {
        $("#pass-wrap").show();
    } else {
        $("#password_choose-0").attr('checked', true)
    }
		 
    $("#loginForm .input input").attr("value","");

    $("#loginForm .input").click(function(){
        $(this).find("label").css("top","-99999px");
    });
    $("#loginForm .input input").focus(function(){
        $(this).prev().css("top","-99999px");
    });

    $("#loginForm .input input").blur(function(){

        if ($(this).val() == '') {
            $(this).prev().css("top","1px");
        }
    });        
	
    $("div.submit button#login").click(function(){
        var username = $("#login-inp").val();
        var password = $("#pass-inp").val();
        
        jQuery.ajax({                      
            type: "POST",
            url: '/user/check',
            data: "username="+ username + "&passwd="+ password,
            success: function(data){ 
                if ($("#popupChoose")) {
                    $("#popupChoose").remove();
                    ClosePopup();
                }
                if (data.error == null) {
                    $("#userMenu div.left").html(data.text);
                } else {
                    $("body").append("<div id='popupChoose' class='red'></div>");
                    $("#popupChoose").html("<h2>Ошибка</h2>");
                    $("#popupChoose").append("<div>"+data.error+"</div>");

                    ClosePopupDelay();
                }                                                
            },
            error: function(){
                alert('Ошибка !');
            },
            cache: false
        });
        
        return false;
    });
	$(".zakaz_po_tel").click(function() {				$("body").append("<div id='zakazTel'></div>");		$("#zakazTel").html("<h2>Заказ по телефону</h2>");		$("#zakazTel").append("<div>Вы можете сделать заказ, позвонив по телефону в Москве +7 (495) 364-11-94. Также мы можем перезвонить на Ваш контактный телефон.</div>");				var text = '';		text+='	<div style="text-align: right; padding: 5px 20px 0pt;">';		text+='		<span>имя:</span> &nbsp; <input type="text" name="name_call" id="name_call" style="width: 168px;">'		text+='	</div>'		text+='	<div style="text-align: right; padding: 5px 20px 0pt;">'		text+='		<span>телефон:</span> &nbsp; <input type="text" name="phone_call" id="phone_call" style="width: 168px;">'		text+='	</div>'		text+='	<div style="text-align: right; padding: 5px 20px 3px 0pt;">'		text+='		<input type="button" value="Позвоните мне!" style="width: 110px;" id="send_phone"> <input type="button" value="Отмена" id="candel_c" style="width: 60px;">'		text+='	</div>'				$("#zakazTel").append(text);		$("#closePopupChoose, #popupBg, #candel_c").live('click', function() {			$("#zakazTel, #popupBg").remove();		});				$('input#send_phone').live('click', function(){						var name = $('input#name_call').val();			var phone = $('input#phone_call').val();						jQuery.ajax({                      	            type: "POST",	            url: '/mail/tel/',	            data: "name="+name+"&phone="+phone,	            success: function(data){ 					$("#zakazTel").html('<div style="border:5px solid #A94E97;padding:5px">Спасибо за обращение. Ваш вопрос принят. С Вами свяжутся сотрудники интернет-магазина. </div>');	            	setTimeout('$("#zakazTel, #popupBg").remove()',3000);	            },	            error: function(){	                alert('Ошибка !');	            },	            cache: false	        });	       		});		$("body").append("<div id='popupBg'></div>");		return false;			});
    $("#addToCart").click(function() {
        var size = $("td input[name]='size':checked").attr("value");        
        if (size == null) {        	
            $("body").append("<div id='popupChoose'></div>");
            $("#popupChoose").html("<h2>Внимание</h2>");
            $("#popupChoose").append("<div>Укажите пожалуйста размер</div>");
            $("#closePopupChoose, #popupBg").live('click', function() {
                $("#popupChoose, #popupBg").remove();
            });
            $("body").append("<div id='popupBg'></div>");
            ClosePopupDelay();
            return false;
        }
    });
    $("#redir").live('click', function() {
        window.location= $(this).attr("href");
    });        $("input#asksubmit.submit").live('click', function() {    	var name = $('form#bistr div #name').val();    	var email = $('form#bistr div #email').val();    	var userphone = $('form#bistr div #userphone').val();    	var comment = $('form#bistr div #comment').val();    	var from = $('form#bistr div #from').val();    			if ((name =='' || name == 'Имя') || ((email =='' || email=='E-mail') && (userphone=='' || userphone=='Телефон')) || (comment=='' || comment=='Текст сообщения')) {			alert('Введите сначала все данные');			return false;		} else {					jQuery.ajax({                      				type: "POST",				url: '/mail/ask/',				data: "name="+name+"&email="+email+"&userphone="+userphone+"&comment="+comment+"&from="+from,				success: function(data){ 					$('form#bistr').hide(100).after('<div style="border:5px solid #A94E97;padding:5px">Спасибо за обращение. Ваш вопрос принят. С Вами свяжутся сотрудники интернет-магазина. </div><br />');				},				error: function(){					alert('Возникли какие то неполадки, приносим свои извинения.');				},				cache: false			});		}        return false;    });
    $(".korz_kol-vo .plus").click(function() {    	
        var parentCont = $(this).parent();
        var countWrap = parentCont.find(".val");
        var countWrapValue = parseInt(countWrap.text());
        var articul = $(this).parent().parent().prev().prev().prev().html();
        var size = $("#"+articul+".item_size").html();
        countWrapValue++;
        countWrap.text(countWrapValue);                           
        jQuery.ajax({                      
            type: "POST",
            url: '/cart/count',
            data: "articul="+ articul + "&qty="+ countWrapValue +"&size=" + size,
            success: function(data){  
                $("#cart b").html(data.count);
                $("div.itogo3").html(data.total);
                $("#sub_total").html(data.subTotal);
                $("#once_discount").html(data.discount.toFixed() + " %");
                $("#"+articul+" span.lineCost").html(data.lineCost);                $("#"+articul+" div.trueLineCost").html(data.trueLineCost);                                var subTotal = Number(data.subTotal.substr(0, data.subTotal.length - 5).replace(/\s+/g, "").replace(',', '.'));                var total = Number(data.total.substr(0, data.total.length - 5).replace(/\s+/g, "").replace(',', '.'));                var econom = subTotal - total;                $("p.purple.econom").html('Ваша экономия: '+econom.toFixed(2)+ ' руб.');
            },
            error: function(){
                alert('Возникли какие то неполадки, приносим свои извинения.');
            },
            cache: false
        });
        return false;
    });
    $(".korz_kol-vo .minus").click(function() {
        var parentCont = $(this).parent();
        var countWrap = parentCont.find(".val");
        var countWrapValue = parseInt(countWrap.text());
        var articul = $(this).parent().parent().prev().prev().prev().html();
        var size = $("#"+articul+".item_size").html();
        if (countWrapValue == 1) {
            return false
        }else {
            countWrapValue = countWrapValue - 1;
            countWrap.text(countWrapValue);
            jQuery.ajax({                      
                type: "POST",
                url: '/cart/count',
                data: "articul="+ articul + "&qty="+ countWrapValue +"&size=" + size,
                success: function(data){  
                    $("#cart b").html(data.count);
                    $("div.itogo3").html(data.total);
                    $("#sub_total").html(data.subTotal);
                    $("#once_discount").html(data.discount.toFixed() + " %");
                    $("#"+articul+" span.lineCost").html(data.lineCost);                    $("#"+articul+" div.trueLineCost").html(data.trueLineCost);                                        var subTotal = Number(data.subTotal.substr(0, data.subTotal.length - 5).replace(/\s+/g, "").replace(',', '.'));                    var total = Number(data.total.substr(0, data.total.length - 5).replace(/\s+/g, "").replace(',', '.'));                    var econom = subTotal - total;                    $("p.purple.econom").html('Ваша экономия: '+econom.toFixed(2)+ ' руб.');
                },
                error: function(){
                	alert('Возникли какие то неполадки, приносим свои извинения.');
                },
                cache: false
            });
            return false;
        }
    });
    $(".mini_imgs a").click(function() {
        var bigImg = $(this).attr("href");
        $("#big_img img").attr("src",bigImg);
        $("#big_img").attr("href",bigImg);        
        $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
        return false;
    });
    $(".undercart_wrap .head a").click(function() {
        var currA = $(this);
        var wrap = currA.parent().parent();
        currA.parent().find("a").removeClass("active");
        currA.addClass("active");
        var ind = currA.index();
        wrap.find(".contentTab").hide();
        wrap.find(".contentTab:eq("+ind+")").show();
        return false;
    });		$(".sizesWrap .head a").click(function() {        var currA = $(this);        var wrap = currA.parent().parent();        currA.parent().find("a").removeClass("active");        currA.addClass("active");        var ind = currA.index();        wrap.find(".wr").hide();        wrap.find(".wr:eq("+ind+")").show();        return false;    });

    $('.auto_hide_input').focus(function() {
        var val = $(this).attr("rel");
        if ($(this).attr("value") == val) {
            $(this).attr("value","");
        }
    });
    $('.auto_hide_input').blur(function() {
        var val = $(this).attr("rel");
        if ($(this).attr("value") == "") {
            $(this).attr("value",val);
        }
    });
    $(".refine-controls .refine-control-header .toggleControl").click(function() {
        var toggleBlock = $(this).parent().parent().next();
        toggleBlock.slideToggle(0);
        $(this).toggleClass("closed");
        return false
    });       
    $("a.del").live('click', function() {
        var articul = $(this).parent().prev().prev().prev().prev().html();        
        jQuery.ajax({                      
            type: "POST",
            url: '/cart/remove',
            data: "articul="+ articul,
            success: function(data){  
                $("#"+articul).animate({
                    opacity: "hide"
                }, "slow");
                $("#cart b").html(data.count);
                $("div.itogo3").html(data.total);
                $("#sub_total").html(data.subTotal);
                var discount = data.discount * 100;
                $("#once_discount").html(discount.toFixed()+" %");                                var subTotal = Number(data.subTotal.substr(0, data.subTotal.length - 5).replace(/\s+/g, "").replace(',', '.'));                var total = Number(data.total.substr(0, data.total.length - 5).replace(/\s+/g, "").replace(',', '.'));                var econom = subTotal - total;                $("p.purple.econom").html('Ваша экономия: '+econom.toFixed(2)+ ' руб.');
            },
            error: function(){
                //alert('По каким-то причинам товар не удалось удалить из корзины, приносим свои извинения.');				location.href="/cart/";
            },
            cache: false
        });
       
        return false;
    });
    $(".refine-controls .attribute-items li a").click(function() {
        $(this).toggleClass("selected");
        var selectedCount = $(".refine-controls .attribute-items li a.selected").length;
        if (selectedCount == 0) {
            $(this).parent().parent().prev().find(".clear").hide();
        } else {
            $(this).parent().parent().prev().find(".clear").show();
        }

        return false
    });

    $(".refine-controls .refine-control-header .clear").click(function() {
        var ulBlock = $(this).parent().next();
        ulBlock.find("a").removeClass("selected");
        $(this).hide();
		$(this).next().hide();
        return false
    });

    $(".refine-controls .colourWrap div").click(function() {
        $(this).toggleClass("active");
        var selectedCount = $(".refine-controls .colourWrap div.active").length;
        if (selectedCount == 0) {
            $(this).parent().prev().find(".clearColor").hide();
        } else {
            $(this).parent().prev().find(".clearColor").show();
        }
    });

    $(".refine-controls .refine-control-header .clearColor").click(function() {
        $(".refine-controls .colourWrap div").removeClass("active");
        $(this).hide();
        return false
    });
});

function classFilter(r,m,not){
    m = " " + m + " ";
    var tmp = [];
    for ( var i = 0; r[i]; i++ ) {
        var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
        if ( not ^ pass )
            tmp.push( r[i] );
    }
    return tmp;
}


function add2Cart() {
	                      
    var articul = $("span.articul").html();    
    var size = $("td input[name]='size':checked").attr("value");
    
    jQuery.ajax({                      
        type: "POST",
        url: '/cart/add',
        data: "articul="+ articul + "&qty="+ 1 + "&size=" + size,
        success: function(data){  
            $("#cart div.inner").html("<h3>Корзина</h3><p>у Вас в корзине<br /><b>"+data.count+"</b> объектов</p><a href=\"/cart\">Оформить заказ</a>");
            jQuery.ajax({                      
                type: "POST",
                url: '/cart/getinfo',
                data: null,
                success: function(data){  

                    $("body").append("<div id='popupChoose'></div>");
                    $("#popupChoose").html("<h2>Товар добавлен в корзину</h2>");
                    $("#popupChoose").append("<div>В корзине <b>"+data.count+"</b> товара");
                    $("#popupChoose").append("<div>На сумму <b>"+data.total+"</b> рублей</div>");
                    $("#popupChoose").append("<button href='' id='closePopupChoose'>Продолжить покупки</button> <button id=\"redir\" href='/cart/'>Перейти в корзину</button> ");

                    $("#closePopupChoose, #popupBg").live('click', function() {
                        $("#popupChoose, #popupBg").remove();
                    });
                    $("body").append("<div id='popupBg'></div>");
                },
                cache: false
            });
        },
        error: function(){
            alert('По каким-то причинам товар не был добавлен, приносим свои извинения.');
        },
        cache: false
    });
    
//return false;
}

function ClosePopupDelay() {
    setTimeout('$("#popupChoose, #popupBg").remove();',3000);
}
function ClosePopup() {
    $("#popupChoose, #popupBg").remove();
}

function addFav(userId, productId) {
    if (userId == null) {
        $("body").append("<div class='red' id='popupChoose'></div>");
        $("#popupChoose").html("<h2>Внимание</h2>");
        $("#popupChoose").append("<div>Только зарегистрированные пользователи могут добавлять товары в избранное.</div>");

        $("#closePopupChoose, #popupBg").live('click', function() {
            $("#popupChoose, #popupBg").remove();
        });
        $("body").append("<div id='popupBg'></div>");
        ClosePopupDelay();
        return false;
    }
    
    jQuery.ajax({                      
        type: "POST",
        url: '/user/addfav',
        data: "userId="+ userId + "&productId="+ productId,
        success: function(){  			
            $("body").append("<div id='popupChoose'></div>");
            $("#popupChoose").html("<h2>Внимание</h2>");
            $("#popupChoose").append("<div>Товар добавлен в избранное.</div>");

            $("#closePopupChoose, #popupBg").live('click', function() {
                $("#popupChoose, #popupBg").remove();
            });
            $("body").append("<div id='popupBg'></div>");
            ClosePopupDelay();
        },
        error: function(){
            alert('По каким-то причинам товар не был добавлен в избранное, приносим свои извинения.');
        },
        cache: false
    });
}
function delFav(articul) {
    jQuery.ajax({                      
        type: "POST",
        url: '/user/delfav',
        data: "articul="+ articul,
        success: function(){  
            $("#"+articul).animate({
                    opacity: "hide"
                }, "slow");
        },
        error: function(){
            alert('По каким-то причинам товар не был добавлен в избранное, приносим свои извинения.');
        },
        cache: false
    });
}
$(function() {
    $("#region-1").click(function() {
        if ($(this).val() == "on" || $(this).val() == "1") {
            $("#town-wrap").show();
        }
    });

    $("#region-0").click(function() {
        $("#town-wrap").hide();
    });

    $("#password_choose-1").click(function() {
        if ($(this).val() == "on" || $(this).val() == "1") {
            $("#pass-wrap").show();
        }
    });

    $("#password_choose-0").click(function() {
        $("#pass-wrap").hide();
    });		$("#why-need,#why-need1").click(function() {		return false;	});
    $("#why-need,#why-need1").mouseenter(function() {
        $("#why-need-popup").show();
        $("#why-need,#why-need1").mouseleave(function() {
            $("#why-need-popup").hide();
        });
    });	
    $("#forgot").mouseenter(function() {
        $("#forgot-popup").show();
        $("#forgot").mouseleave(function() {
            $("#forgot-popup").hide();
        });
    });
});
function buy(user) {	var comment = $('#user_comment').val();		jQuery.ajax({                              type: "POST",        url: '/cart/savecomment/',        data: "comment="+ comment,        success: function(){              if (user != null) {				window.location = '/cart/order';			} else {				window.location = '/cart/nonloginorder';			}        },        error: function(){            alert('По каким-то причинам товар не был добавлен в избранное, приносим свои извинения.');        },        cache: false    });    
};
