$(document).ready(function(){
    
    // Основные
    
    $.ifixpng('/i/spacer.gif');
    $('.png, img[src$=".png"]').ifixpng();
    
    $('a[rel^="prettyPhoto"], a.prettyPhoto, a.lightbox').prettyPhoto();
    
    $('#captcha').click(function(){
        $(this).attr('src', '/captcha/rand-'+parseInt(Math.random()*999999999)+'/');
    });
    
    // Подвал - в подвал
    
    if ($('body').outerHeight()<$(window).height()) {
        $('#filler').attr('height', $(window).height()+$('#filler').parent().outerHeight()-$('body').outerHeight());
    }
    
    if ($('body').outerWidth()>1100) {
        $('.wideable').attr('width', 1200);
    }
    
    if ($('#table111').height()>$('#table222').height()) {
        $('#table222').attr('height', $('#table111').height());
    }
    if ($('#table222').height()>$('#table111').height()) {
        $('#table111').attr('height', $('#table222').height());
    }
    
    // Картиночки
    
    $('<img>').attr('src', '/i/contacts_over.png');
    $('<img>').attr('src', '/i/delivery_over.png');
    $('<img>').attr('src', '/i/discounts_over.png');
    $('<img>').attr('src', '/i/searchfailed_over.png');
    $('.m_over').mouseover(function(){
        $(this).attr('src', $(this).attr('src').replace(/\.png/, '_over.png'));
    });
    $('.m_over').mouseout(function(){
        $(this).attr('src', $(this).attr('src').replace(/_over\.png/, '.png'));
    });
    
    $('input[name="from"][type="radio"][value="0"], input[name="ems"][type="radio"][value^="city"]').parent().html($('input[name="from"][value="0"], input[name="ems"][type="radio"][value^="city"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по городу" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="from"][type="radio"][value="1"], input[name="ems"][type="radio"][value^="region"]').parent().html($('input[name="from"][type="radio"][value="1"], input[name="ems"][type="radio"][value^="region"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по краю (области)" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="from"][type="radio"][value="2"]').parent().html($('input[name="from"][value="2"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по России" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="from"][type="radio"][value="10"], input[name="ems"][type="radio"][value="10"]').parent().html($('input[name="from"][type="radio"][value="10"], input[name="ems"][type="radio"][value="10"]').parent().html() + ' <a href="javascript://" class="dialog" title="Самовывоз" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="ems_off"][value="0"]').parent().html($('input[name="ems_off"][value="0"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по России - EMS Экспресс доставка" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="ems_off"][value="1"]').parent().html($('input[name="ems_off"][value="1"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по России - Почта России 1 класс" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="Оплата курьеру лично"]').parent().html($('input[name="paytype"][value="Оплата курьеру лично"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата курьеру" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="Qiwi"]').parent().html($('input[name="paytype"][value="Qiwi"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата через терминалы Qiwi" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="Visa"]').parent().html($('input[name="paytype"][value="Visa"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата картой Visa/Master Card" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="WebMoney"]').parent().html($('input[name="paytype"][value="WebMoney"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата электронными деньгами WebMoney" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="Yandex.money"]').parent().html($('input[name="paytype"][value="Yandex.money"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата электронными деньгами Yandex.Деньги" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="Сбербанк ПД-4"]').parent().html($('input[name="paytype"][value="Сбербанк ПД-4"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата в отделении Сбербанка России" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="vtb24"]').parent().html($('input[name="paytype"][value="vtb24"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата через банк ВТБ24" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="paytype"][value="ПлатежноеПоручение"]').parent().html($('input[name="paytype"][value="ПлатежноеПоручение"]').parent().html() + ' <a href="javascript://" class="dialog" title="Оплата через платежное поручение (юр. лицо)" style="color:#900; font-size:8px;">[?]</a>');
    if (!$('#bigsearch input[name^="from"]:checked').length) {
        $('#bigsearch input[name^="from"]').attr('checked', 1);
    }
    
    // Логин и регистрация
    
    $('#form_login').validate({
        rules:{
            email:{required:true, email:true, remote:'/signup/email/exists/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail не зарегистрирован.'}
        }
    });
    
    $('#form_signup').validate({
        rules:{
            name1:'required',
            name2:'required',
            name3:'required',
            email:{required:true, email:true, remote:'/signup/email/free/'},
            pass:{minlength:4},
            pass2:{equalTo:'#form_signup input[name="pass"]'},
            phone:{required:true, mobile:true},
            phone2:'phone',
            zip:{number:true, rangelength:[6, 6]},
            region:'required',
            district:{required:function(){return (parseInt($('input[name="from"]:checked').val())==2 && !$('select[name="ems"]').val().match(/^city/)) || !$('input[name="city"]').val().length>0;}},
            city:{required:function(){return (parseInt($('input[name="from"]:checked').val())==2 && $('select[name="ems"]').val().match(/^city/)) || !$('input[name="district"]').val().length>0;}},
            punkt:{required:function(){return parseInt($('input[name="from"]:checked').val())==1 && $('input[name="district"]').val().length>0 && !$('input[name="city"]').val().length>0;}},
            street:'required',
            house:'required',
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail уже зарегистрирован. <a href="/signup/forgot/" target="_blank">Забыли пароль?</a>'},
            pass2:{equalTo:'Пароли не совпадают'}
        },
        submitHandler:function(form){
            $('#form_signup input, #form_signup select').removeAttr('disabled');
            form.submit();
        }
    });
    
    $('#form_forgot').validate({
        rules:{
            email:{required:true, email:'true', remote:'/signup/email/exists/'},
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail не зарегистрирован.'}
        }
    });
	
	//120131oleg
	function fuckf() {
		city = 0;
		if (
			$('input[name="from"]:checked').val() == 0
			||
			/city/.test($('input[name="ems"]:checked').val())
		) {
			city = 1;
		}
		if ($('input[name="from"]:checked').val() == 10 || $('input[name="ems"]:checked').val() == 10) {
			city = 2; //самовывоз
		}
		
		//чертова помойка //#TODO:
		if (city == 1) { //доставка в город
			$("#delivery_type").html('Доставка <a href="/special/type-2/" class="gray" target="_blank">(подробнее о бесплатной доставке)</a>');
			$(".tr_sampun").hide(); $(".tr_sampun select").attr('disabled', true);
			$(".tr_sampun_hide").show(); $(".tr_sampun_hide input").attr('disabled', false);
			$("#sampun1").html("Данные, необходимые для службы доставки:");
			$("#sampun2").html("Комментарий для доставки");
			$('#deliverytime_').attr('disabled', false);
			$('.tr_deliverytime').show();
			$('#metro_').attr('disabled', false);
			$('.tr_metro').show();
		} else if (city == 2) { //самовывоз
			$("#delivery_type").html("Самовывоз");
			$(".tr_sampun").show(); $(".tr_sampun select").attr('disabled', false);
			$(".tr_sampun_hide").hide(); $(".tr_sampun_hide input").attr('disabled', true);
			$("#sampun1").html("Данные, необходимые для формирования заказа:");
			$("#sampun2").html("Комментарий для заказа");
			$('#deliverytime_').attr('disabled', true);
			$('.tr_deliverytime').hide();
			$('#metro_').attr('disabled', true);
			$('.tr_metro').hide();
		} else { //россия/край/область
			$("#delivery_type").html('Доставка <a href="/special/type-2/" class="gray" target="_blank">(подробнее о бесплатной доставке)</a>');
			$(".tr_sampun").hide(); $(".tr_sampun select").attr('disabled', true);
			$(".tr_sampun_hide").show(); $(".tr_sampun_hide input").attr('disabled', false);
			$("#sampun1").html("Данные, необходимые для службы доставки:");
			$("#sampun2").html("Комментарий для доставки");
			$('#deliverytime_').attr('disabled', true);
			$('.tr_deliverytime').hide();
			$('#metro_').attr('disabled', true);
			$('.tr_metro').hide();
		}
	}
	//при выборе пункта для самовывоза
	$("select[name='sampun']").change(function() {
		$(".sampun_div").hide(); $(".sampun_div[title='sampunsm"+$(this).val()+"']").show(); //описание меняем
		basket_calc(); //пересчитываем корзину
	});
	
	if ($('input[name="from"]:checked').length || $('input[name="ems"]:checked').length) {
		fuckf();
	}
    
    $('input[name="from"], select[name="ems"]').click(function(){
		
		//120125-26oleg
		fuckf();
		
		if ($('input[name="from"]:checked').val() == 1) { //для регионов - оплата курьеру
			$('#tr_courier').show();
		} else {
			$('#tr_courier').hide();
		}
		
        if ($('#table_order').css('display')!='none') {
            $('.td_delivery').show(); // Показываем поле про доставку
        }
        
        $('#delivery0, #delivery1, #delivery2, #delivery10').hide();
        $('#delivery'+parseInt($('input[name="from"]:checked').val())).show();
        switch (parseInt($('input[name="from"]:checked').val())) {
            case 2:
            $('.tr_signup_ems').show();
            $('.tr_signup_address').show();
            $('#tr_jur').show();
            $('#tr_visa').show();
            var ems_str = $('select[name="ems"]').val();
            if (ems_str.match(/^city/)) { // Это город
                $('.td_signup_district').hide();
                $('.td_signup_city').show();
                var m = ems_str.match(/region.*/);
                if ($('select[name="ems"] option[value="'+m+'"]').length) {
                    $('input[name="region"]').val($('select[name="ems"] option[value="'+m+'"]').html());
                    $('input[name="region"]').attr('disabled', true);
                }
                else {
                    $('input[name="region"]').val('');
                    $('input[name="region"]').attr('disabled', false);
                }
                $('input[name="city"]').val($('select[name="ems"] option[value="'+ems_str+'"]').html());
                $('input[name="city"]').attr('disabled', true);
            }
            else { // Это регион
                $('.td_signup_district').show();
                $('.td_signup_city').hide();
                $('input[name="region"]').val($('select[name="ems"] option[value="'+ems_str+'"]').html());
                $('input[name="region"]').attr('disabled', true);
                $('input[name="city"]').val('');
                $('input[name="city"]').attr('disabled', false);
            }
			
			 //OLEG120123
            //$('input[name="region"]').attr('disabled', false);
            //$('input[name="city"]').attr('disabled', false);
			$('input[name="region_"]').val($('input[name="region"]').val());
			$('input[name="city_"]').val($('input[name="city"]').val());
			
            $('input[name="zip"]').attr('disabled', false);
            break;
            case 1:
            $('.tr_signup_ems').hide();
            $('.tr_signup_address').show();
            $('.td_signup_district').show();
            $('.td_signup_city').show();
            $('#tr_jur').hide();
            $('#tr_visa').show();
            $('input[name="region"]').val('Красноярский край');
            $('input[name="city"]').val('');
            $('input[name="region"]').attr('disabled', true);
            $('input[name="city"]').attr('disabled', false);
            $('input[name="zip"]').attr('disabled', false);

            break;
            default:
            $('.tr_signup_ems').hide();
            $('.tr_signup_address').hide();
            $('#tr_jur').hide();
            $('#tr_visa').hide();
            $('input[name="region"]').val('Красноярский край');
            $('input[name="city"]').val('г.Красноярск');
            $('input[name="region"]').attr('disabled', true);
            $('input[name="city"]').attr('disabled', true);
            $('input[name="zip"]').attr('disabled', true);
            break;
        }
    });
    
    $('input[type=radio][name=ems]').click(function(){
		
		fuckf(); //oleg
		
        if (/city/.test($(this).val()) || $(this).val() == 10) { // Город //oleg про 10
            $('.tr_signup_address').hide();
        }
        else { // Область
            $('.tr_signup_address').show();
        }
    });
    
    // Корзина
    
    $('#form_basket input[name="submit_calc"]').hide();
    
    $('#form_basket').validate({
        rules:{
            name1:{required:true},
            name2:{required:true},
            name3:{required:true},
            email:{required:true, email:'true'},
            phone:{required:'input[name="phone2"]:blank', mobile:'true'},
            phone2:{required:'input[name="phone"]:blank', phone:'true'},
            zip:{number:true, rangelength:[6, 6]},
            region:{required:function(){return $('input[type=radio][name=from]') ? false  : parseInt($('input[name="from"]:checked').val())!=0}},
            district:{required:function(){return $('input[type=radio][name=from]') ? false  : (parseInt($('input[name="from"]:checked').val())==2 && !$('select[name="ems"]').val().match(/^city/)) || !$('input[name="city"]').val().length>0;}},
            city:{required:function(){
				if ($('input[name="from"]:checked').val() == 10 || $('input[name="ems"]:checked').val() == 10) {
				 return false; //самовывоз
				}
                if ($('input[name=sub]').length) {
                    return !(/city/.test($('input[name="ems"]:checked').val()));
                }
                return $('input[type=radio][name=from]') ? false  : (parseInt($('input[name="from"]:checked').val())==2 && $('select[name="ems"]').val().match(/^city/)) || !$('input[name="district"]').val().length>0;
            }},
            punkt:{required:function(){return $('input[type=radio][name=from]') ? false  : parseInt($('input[name="from"]:checked').val())==1 && $('input[name="district"]').val().length>0 && !$('input[name="city"]').val().length>0;}},
            street:{required:function(){
				if ($('input[name="from"]:checked').val() == 10 || $('input[name="ems"]:checked').val() == 10) {
				 return false; //самовывоз
				}
				return true;
			}},
            house:{required:function(){
				if ($('input[name="from"]:checked').val() == 10 || $('input[name="ems"]:checked').val() == 10) {
				 return false; //самовывоз
				}
				return true;
			}},
            from:'required',
            deliverytime:'required',
            sampun:'required',
            paytype:{required:function(){
				if ($('input[name="from"]:checked').val() == 10 || $('input[name="ems"]:checked').val() == 10) {
				 return false; //самовывоз
				}
                if ($('input[name=sub]').length) {
                    return !(/city/.test($('input[name="ems"]:checked').val()));
                }
                return parseInt($('input[name="from"]:checked').val())!=0;
            }},
            ems_off:{required:function(){
                return parseInt($('input[type=radio][name=from]:checked').val())==2;
            }},
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{
            phone:{required:'Необходимо указать хотя бы один телефон.'},
            phone2:{required:'Необходимо указать хотя бы один телефон.'}
        },
        invalidHandler:function(){
            $('#form_basket input[dis]').attr('dis', false).attr('disabled', true);
        },
        errorPlacement:function(error, element){
            if (element.attr('type')=='radio') {
                $('<br />').appendTo(error);
                error.prependTo($('#form_basket input[name="'+element.attr('name')+'"]:first').parent().parent());
            }
            else {
                error.insertAfter(element);
            }
        },
        submitHandler:function(form){
		
			/*if ($("#district_").is(':visible') && $("#district_").is(':disabled')) {
				$("#district__").val($("#district_").val());
				$("#district__").removeAttr("disabled");
			}
			if ($("#city_").is(':visible') && $("#city_").is(':disabled')) {
				$("#city__").val($("#city_").val());
				$("#city__").removeAttr("disabled");
			}*/
            
            if ($('#form_basket').attr('action')=='/basket/submit-1/') {
                form.submit();
            }
            
            url = '/basket/calc/correct-1/'+($('#form_basket input[name="from"]:checked').length ? 'delivery-1/' : '')+'?' + $('#form_basket .count').serialize() + '&from=' + $('#form_basket input[name="from"]:checked').val() + '&ems_off=' + $('#form_basket input[name="ems_off"]:checked').val();
            if ($('#form_basket input[name="from"]:checked').val()==2 && $('#form_basket input[name="ems_off"]:checked').val()!=1) {
                url += '&' + $('#form_basket select[name="ems"]').val();
            }
            
            $.getJSON(url, null, function(data){
                if (data.ok) {
                    if ($('input[name=sub]').length) {
                        //$('#form_basket input[disabled], #form_signup select[disabled]').remove();
                    }
                    else {
                        $('#form_basket input, #form_signup select').removeAttr('disabled');
                    }
                    $('#form_basket').attr('action', $('#form_basket').attr('action')+'submit-1/');
                    $('#form_basket').submit();
                }
                else {
                    $('#basket_cost').html(data.cost);
                    $('#basket_cost_discount').html(data.cost_discount);
                    $('.delivery_cost').html(data.delivery_cost);
                    $('.basket_sum').html(data.cost_sum);
                    for (i in data.total) {
                        $('#basket_total'+i).html(data.total[i]);
                    }
                    for (i in data.count) {
                       if ($('#form_basket input[name="count['+i+']"]').val()!=data.count[i]) { // Это отличие от backet_calc
                           $('#form_basket input[name="count['+i+']"]').css('color', '#900');
                       }
                       $('#form_basket input[name="count['+i+']"]').val(data.count[i]);
                    }
                    
                    if ($('#basket_cost_min').length) {
                        if ((parseInt($('#form_basket input[name="from"]:checked').val()) && parseFloat(data.cost)<parseFloat($('#order_min').html())) || (parseFloat(data.cost_cos) && parseFloat(data.cost_cos)<parseFloat($('#order_min_cos').html()))) {
                             $('#basket_cost_min').show();
                            $('#basket_cost_normal, #table_order').hide();
                        }
                        else {
                             $('#basket_cost_min').hide();
                            $('#' + ($('#order_btn').css('display')=='none' ? 'table_order' : 'basket_cost_normal')).show();
                        }
                    }
                    $('#basket').html(data.html);
                    
                    $('<div title="Внимание!">Количество заказанного товара было скорректировано согласно реального наличия товара, сумма заказа изменилась.</div>').dialog({modal:true, buttons:{'Закрыть':function(){$(this).dialog('close');}}});
                    
                }
                
            });
         }
    });
    $('#form_basket input[name="submit_order"]').click(function(){
        $('#form_basket input[disabled]').attr('disabled', false).attr('dis', true);
    });
    
    $('#form_basket .count').live('keyup', function(){
        $(this).val(isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val()));
        $(this).css('color', '');
        basket_calc();
    });
    
    $('#form_basket input[name="from"]').change(function(){
        $('.td_delivery').show(); // Показываем поле про доставку
        basket_calc();
    });
    
    $('#form_basket *[name="ems"]').change(function(){
        $('.td_delivery').show(); // Показываем поле про доставку
        basket_calc();
    });
    
    $('#form_basket input[name="ems_off"]').change(function(){
        if ($('#table_order').css('display')!='none') {
            $('.td_delivery').show(); // Показываем поле про доставку
        }
        basket_calc();
    });
	
	$('#submit_probnik').click(function() {
		$.post("/basket/", { probnik_add: 1, probnik_id: $('#probnik').val() },
		function(data) {
			//location.reload(true);
			window.location = window.location.href;
		});
	});
    
    basket_calc();
    
    // Спецпредложения
    if ($('#special_form input[type="submit"]').length && !$('#special_form input[type="submit"]').attr('count')) {
        $('#special_form input[type="submit"]').css('display', 'inline');
    }
    $('#special_form input[type="checkbox"]').change(function(){
        $('.special_table[i="'+$(this).val()+'"]').css('background', $(this).attr('checked') ? 'url(/i/specialbg.gif) repeat-x' : '');
        $('#special_form input[type="submit"]').css('display', $('#special_form input[type="checkbox"]:checked').length==$('#special_form input[type="submit"]').attr('count') ? 'inline':'none');
    });
    
    // Подстказывалки в полях
    
    $('.hint').focus(function(){
        if ($(this).css('font-style')=='italic') {
            $(this).css('font-style', 'normal');
            $(this).attr('val_old', $(this).val());
            $(this).val('');
        }
    });
    
    $('.hint').blur(function(){
        if (!$(this).val().length) {
            $(this).css('font-style', 'italic');
            $(this).val($(this).attr('val_old'));
        }
    });
    
    // Дизайновые
    
    $('#button_woman').click(function(){location.href='/woman/';});
    $('#button_man').click(function(){location.href='/man/';});
    $('#button_cos').click(function(){location.href='/cos/';});
    $('#button_oil').click(function(){location.href='/oil/';});
    $('.overable').hover(function(){
        $(this).css('background-color', '#f6f6f6');
    }, function(){
        $(this).css('background-color', '');
    });
    
    // Поиск
    $('#bigsearch input[name^="from"]').click(function(){
        if (!$('#bigsearch input[name^="from"]:checked').length) {
            $(this).attr('checked', 1);
        }
        $('#search_refresh').load('/catalogue/search/refresh/?'+$('#bigsearch').serialize());
    });
    $('#bigsearch input[name="flags[]"]').click(function(){
        $('#search_refresh').load('/catalogue/search/refresh/?'+$('#bigsearch').serialize());
        $('#bigsearch').attr('action', '/catalogue/search/'+($('#bigsearch input[name="flags[]"]:checked').length || $('#bigsearch [name="producer_name"]').val() ? 'items-1/' : ''));
    });
    $('#bigsearch select').change(bigsearch_select_change);
    
    $('.tooltip').each(function(){
        if ($('#'+this.id+'_2').length) {
            $('#'+this.id).easytooltip(this.id+'_2');
        }
    });
    
    $('a.dialog:not(.makequestion)').live('click', function(){
        var title = $(this).attr('title') ? $(this).attr('title') : $(this).html();
        $('div[title="'+title+'"]').clone().dialog({width:400});
        //$('div[title="'+title+'"]').clone().dialog({position:($(this).attr('rel')!='no' ? [event.x, event.y] : 'center')});
    });
    
    $('a.makequestion').click(function(){
        $('div.makequestion').dialog('open');
    });

    $('div.makequestion').dialog({
        autoOpen:false,
        width:500,
        buttons:{
            'Отправить':function(){
                $('.validate').validate({
                    rules:{
                        keystring:{required:true, remote:'/captcha/check/'}
                    }
                });
                if ($(this).find('form').valid()) {
                    $(this).find('form').submit();
                }
            }
        }
    });
    
    $('.smallsmallred').live('click', function(){
        if ($(this).attr('rel')=='from' || $(this).attr('rel')=='flags') {
            $('#bigsearch input[name^="'+$(this).attr('rel')+'"]').attr('checked', true);
        }
        else {
            $('#bigsearch select[name^="'+$(this).attr('rel')+'"]').val('');
            $('#search_refresh').load('/catalogue/search/refresh/?'+$('#bigsearch').serialize()+'&select='+$(this).attr('rel'));
        }
    });
    
    $('.tophover:not([src$="_sel.gif"])').hover(function(){
        $(this).attr('src', $(this).attr('src').replace(/\.gif$/, '_sel2.gif'));
    },
    function(){
        $(this).attr('src', $(this).attr('src').replace(/_sel2\.gif$/, '.gif'));
    });
    
    $('.validate').validate({
        rules:{
            keystring:{required:true, remote:'/captcha/check/'}
        }
    });
    
    var other_obj = {};
    $('.other').append('<option value="#other#">Другое...</option>');
    $('.other').live('click', function(){
        if ($(this).val()=='#other#') {
            var name = $(this).attr('name');
            other_obj[name+'_back'] = $(this).clone().val('');
            $(this).replaceWith('<table width="100%" border="0" cellpadding="0" cellspacing="0" id="'+name+'_back"><tr><td width="0%" style="padding-right:5px;"><input type="button" name="'+name+'_back" value="&laquo; Список" class="fields other_back" style="width:65px;" /></td><td width="100%"><input name="'+name+'" type="text" class="fields required" style="width:120px;" /></td></tr></table>');
            $('input[name="'+name+'"]').focus();
        }
    });
    $('.other_back').live('click', function(){
        other_obj[$(this).attr('name')].insertAfter('#'+$(this).attr('name'));
        $('#'+$(this).attr('name')).remove();
    });
    
    $('#form_signup input').change(function(){
        $('#profile_btn').show();
    });
    $('#form_signup input').keyup(function(){
        $('#profile_btn').show();
    });
    $('#form_signup input').click(function(){
        $('#profile_btn').show();
    });
    
    $('.domain').change(function(){
        location.href = 'http://' + $(this).val() + '.24parfum.ru/';
    });
    
});

function bigsearch_select_change() {
    
    $('#search_refresh').load('/catalogue/search/refresh/?'+$('#bigsearch').serialize()+'&select='+$(this).attr('name'), null, function (){
        $('#bigsearch select').change(bigsearch_select_change);
    });
    $('#bigsearch').attr('action', '/catalogue/search/'+($('#bigsearch input[name="flags[]"]:checked').length || $('#bigsearch [name="producer_name"]').val() ? 'items-1/' : ''));
    
}

function to_basket(id) {
    
    $('#basket').load('/basket/add/id-'+id+'/', null, function(){
        $('<div></div>').load('/basket/mini/').dialog({
            modal:true,
            width:800,
            buttons:{
                'Оформить заказ':function(){
                    $('#form_basket').submit();
                },
                'Вернуться в каталог':function(){
                    $(this).dialog('close');
                }
            }
        });
    });
    
}

function basket_calc() {
    
    if ($('#form_basket input[name="from"][type=radio]').length) { // Мы на www
        url = '/basket/calc/'+($('#form_basket input[name="from"]:checked').length ? 'delivery-1/' : '')+'?' + $('#form_basket .count').serialize() + '&from=' + $('#form_basket input[name="from"]:checked').val() + '&ems_off=' + $('#form_basket input[name="ems_off"]:checked').val();
        if ($('#form_basket input[name="from"]:checked').val()==2 && $('#form_basket input[name="ems_off"]:checked').val()!=1) {
            url += '&' + $('#form_basket select[name="ems"]').val();
        }
    }
    else {
        from = /city/.test($('#form_basket input[name="ems"]:checked').val()) ? 0 : 1;
		if ($('#form_basket input[name="ems"]:checked').val() == 10) from = 10; //oleg
        url = '/basket/calc/delivery-1/?' + $('#form_basket .count').serialize() + '&from=' + from;
    }
    
	//oleg
	if ($("select[name='sampun']:visible").length) {
		url += '&sampun=' + $("select[name='sampun']").val();
	}
	
    $.getJSON(url, null, function(data){
        $('#basket_cost').html(data.cost);
        $('#basket_cost_discount').html(data.cost_discount);
        $('.delivery_cost').html(data.delivery_cost);
	 
		//oleg120127
		//$('.basket_sum').html(data.cost_sum);
		if (!$("input[name=from]:checked").length && !$("input[name=ems]:checked").length) { //куда доставка - не выбрано
			$('.basket_sum').html(data.cost_discount); //без стоимости доставки
		} else {
			$('.basket_sum').html(data.cost_sum);
		}
        
        for (i in data.total) {
            $('#basket_total'+i).html(data.total[i]);
        }
        for (i in data.count) {
            $('#form_basket input[name="count['+i+']"]').val(data.count[i]);
        }
        if ($('#basket_cost_min').length) {
            if (
                (
                    (
					    (
							parseInt($('#form_basket input[name=from]:checked').val())>0
							&&
							parseInt($('#form_basket input[name=from]:checked').val()) != 10
						)
						||
						(
							$('#form_basket input[name=from][type=hidden]').length>0
							&&
							$('#form_basket input[name=ems]:checked').length>0
							&&
							!(/city/.test($('#form_basket input[name=ems]:checked').val())))
							&&
							$('#form_basket input[name=ems]:checked').val() != 10
					  )
                 && parseFloat(data.cost)<parseFloat($('#order_min').html())
                )
             || (parseFloat(data.cost_cos) && parseFloat(data.cost_cos)<parseFloat($('#order_min_cos').html()))
			  
            ) {
                $('#basket_cost_min').show();
                $('#basket_cost_normal, #table_order').hide();
            }
            else {
                $('#basket_cost_min').hide();
                if ($('#form_basket input[name=from]:checked, #form_basket input[name=from][type=hidden]').length) {
					if ($('#form_basket input[name=ems]').length && !$('#form_basket input[name=ems]:checked').length) {
						//msk - не выбрали область/город
					} else {
						$('#' + ($('#order_btn').css('display')=='none' ? 'table_order' : 'basket_cost_normal')).show();
					}
                }
            }
        }
        $('#basket').html(data.html);
    });
    
}

$.validator.addMethod('phone', function(ph, element) {
    if (this.optional(element)) {
        return true;
    }
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, '');
    // 6 is the minimum number of numbers required
    return ((/\d{6,}/i).test(stripped));
}, 'Пожалуйста, введите корректный номер телефона.');

$.validator.addMethod('mobile', function(value, element) {
    return this.optional(element) || /^89\d{9}$/i.test(value);
}, 'Пожалуйста, введите сотовый телефон в формате 89xxxxxxxxx.');

$.validator.addMethod('login', function(value, element) {
    return this.optional(element) || /^[0-9a-z_\-]+$/i.test(value);
}, 'Пожалуйста, введите корректный логин.');

$.validator.addMethod('fio', function(value, element) {
    return this.optional(element) || /([^\s]+)\s+([^\s.])[^\s.]*(?:\s|\.)([^\s.])[^\s.]*/i.test(value);
}, 'Пожалуйста, введите настоящие фамилию, имя и отчество.');
