$(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"][value="0"]').parent().html($('input[name="from"][value="0"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по Красноярску" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="from"][value="1"]').parent().html($('input[name="from"][value="1"]').parent().html() + ' <a href="javascript://" class="dialog" title="Доставка по Красноярскому краю" style="color:#900; font-size:8px;">[?]</a>');
    $('input[name="from"][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="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="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="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:'input[name="phone2"]:blank', mobile:'true'},
            phone2:{required:'input[name="phone"]:blank', phone:'true'},
            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:'Пароли не совпадают'},
            phone:{required:'Необходимо указать хотя бы один телефон.'},
            phone2:{required:'Необходимо указать хотя бы один телефон.'}
        },
        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 не зарегистрирован.'}
        }
    });
    
    $('input[name="from"], select[name="ems"]').click(function(){
        
        //if ($('#table_order').css('display')!='none') {
            $('.td_delivery').show(); // Показываем поле про доставку
        //}
        
        $('#delivery0, #delivery1, #delivery2').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();
            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);
            }
            $('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();
            $('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();
            $('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;
        }
    });
    
    // Корзина
    
    $('#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 parseInt($('input[name="from"]:checked').val())!=0}},
            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',
            from:'required',
            paytype:{required:function(){return parseInt($('input[name="from"]:checked').val())!=0}}, 
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{
            phone:{required:'Необходимо указать хотя бы один телефон.'},
            phone2:{required:'Необходимо указать хотя бы один телефон.'}
        },
        invalidHandler:function(){
            $('#form_basket input[dis]').attr('dis', false).attr('disabled', true);
        },
        submitHandler:function(form){
            
            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) {
                    $('#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 (parseFloat(data.cost)<parseFloat($('#order_min').html()) && parseInt($('#form_basket input[name="from"]:checked').val())) {
                            $('#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(){
        basket_calc();
    });
    
    $('#form_basket select[name="ems"]').change(function(){
        basket_calc();
    });
    
    $('#form_basket input[name="ems_off"]').change(function(){
        if ($('#table_order').css('display')!='none') {
            $('.td_delivery').show(); // Показываем поле про доставку
        }
        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_child').click(function(){location.href='/child/';});
    $('#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:400,
        buttons:{
            'Отправить':function(){
                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'));
    });
    
    $('div.makequestion from, .validate').validate();
    
    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();
    });
    
});

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() {
    
    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();
    }
    
    $.getJSON(url, null, function(data){
        $('#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) {
            $('#form_basket input[name="count['+i+']"]').val(data.count[i]);
        }
        if ($('#basket_cost_min').length) {
            if (parseFloat(data.cost)<parseFloat($('#order_min').html()) && parseInt($('#form_basket input[name="from"]:checked').val())) {
                $('#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);
    });
    
}

$.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);
}, 'Пожалуйста, введите настоящие фамилию, имя и отчество.');