$(document).ready(function(){
    
    // Основные
    
    $('a[rel^="prettyPhoto"], a.prettyPhoto, a.lightbox').prettyPhoto();
    
    $('#logo img').ifixpng('/i/spacer.gif');
    
    $('#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());
    }
    
    // Подстказывалки в полях
    
    $('.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'));
        }
    });
    
    // Корзина
    
    $('#form_basket input[name="submit_calc"]').hide();
    
    $('#form_basket').validate({
        rules:{
            name:'required',
            email:{required:true, email:'true'},
            phone:{required:true, phone:'true'},
            address:'required',
            keystring:{required:true, remote:'/captcha/check/'}
        },
        submitHandler:function(form){
            $('#form_basket').attr('action', $('#form_basket').attr('action')+'submit-1/');
            form.submit();
        }
    });
    
    $('.count').live('keyup', function(){
        $(this).val(isNaN(parseInt($(this).val())) ? '' : parseInt($(this).val()));
        $.getJSON('/basket/calc/?'+$('#form_basket .count').serialize(), null, function(data) {
            $('#basket').html(data.html);
            $('#basket_total').html(data.total);
            for(i in data.ids) {
                id = data.ids[i];
                $('#basket_cost_'+id).html(data.costs[id]);
                $('#basket_total_'+id).html(data.totals[id]);
            }
        });
        
    });
    
    // Логин и регистрация
    
    $('#form_login').validate({
        rules:{
            email:{required:true, email:true, remote:'/signup/email/exists/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail не зарегистрирован.'}
        }
    });
    
    $('#form_signup').validate({
        rules:{
            email:{required:true, email:true, remote:'/signup/email/free/'},
            name:'required',
            pass:{required:$('#form_signup input[name="email"]').length>0, minlength:4},
            pass2:{required:$('#form_signup input[name="email"]').length>0, equalTo:'#form_signup input[name="pass"]'},
            phone:'phone',
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail уже зарегистрирован. <a href="/signup/forgot/" target="_blank">Забыли пароль?</a>'},
            pass2:{equalTo:'Пароли не совпадают'}
        }
    });
    
    $('#form_forgot').validate({
        rules:{
            email:{required:true, email:'true'},
            keystring:{required:true, remote:'/captcha/check/'}
        }
    });
    
});

function to_basket(id) {
    
    $('#basket').load('/basket/add/id-'+id+'/', null, function(){
        $('#basket').show();
        $('<div title="Корзина"></div>').load('/basket/mini/').dialog({
            modal:true,
            width:800,
            buttons:{
                'Оформить заказ':function(){
                    $('#form_basket').submit();
                },
                'Закрыть':function(){
                    $(this).dialog('close');
                }
            }
        });
    });
    
    return false;

}

$.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('login', function(value, element) {
    return this.optional(element) || /^[0-9a-z_\-]+$/i.test(value);
}, 'Пожалуйста, введите корректный логин.');

