$(document).ready(function(){
    
    $.ifixpng('/i/spacer.gif');
    $('.png, .frame, img[src$=".png"]').ifixpng();
    
    if ($('body').outerHeight()<$(window).height()) {
        $('#filler').attr('height', $(window).height()+$('#filler').parent().outerHeight()-$('body').outerHeight());
    }
    
    $(".jMyCarousel").jMyCarousel({
        visible:jMyCarousel_calc_width(),
        eltByElt:true,
        circular:false
    });

    
    lightbox_init();
    
    $('#form_signup').validate({
        rules:{
            email:{required:true, email:true, remote:'/signup/email/free/'},
            phone:'phone',
            keystring:{required:true, remote:'/captcha/check/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail уже зарегистрирован. <a href="/signup/forgot/" target="_blank">Забыли пароль?</a>'}
        }
    });
    
    $('#form_forgot').validate({
        rules:{
            email:{required:true, email:'true'},
            keystring:{required:true, remote:'/captcha/check/'}
        }
    });
    
    $('#captcha').click(function(){
        $(this).attr('src', '/captcha/rand-'+parseInt(Math.random()*999999999)+'/');
    });
    
    $('#form_search input').focus(function(){
        if ($(this).css('font-style')=='italic') {
            $(this).css('font-style', '');
            $(this).css('color', '');
            $(this).val('');
        }
    });
    
    $('#form_search input').blur(function(){
        if (!$(this).val().length) {
            $(this).css('font-style', 'italic');
            $(this).css('color', '#555');
            $(this).val('Поиск по № объекта...');
        }
    });
    
    $('#form_estate_order').validate({
        rules:{
            cost_from:{min:1, number:true},
            cost_to:{min:1, number:true},
            area_from:{min:1, number:true},
            area_to:{min:1, number:true}
        }
    });
    
    $('#form_estate_reg').validate({
        rules:{
            email:{required:function(){return $('input[name="signup"]:checked').val()=='2'?true:false;}, email:true, remote:'/signup/email/free/'},
            email2:{required:function(){return $('input[name="signup"]:checked').val()=='1'?true:false;}, email:true, remote:'/signup/email/registered/'},
            pass:{required:function(){return $('input[name="signup"]:checked').val()=='1'?true:false;}, remote:'/signup/pass/check/'}
        },
        messages:{ 
            email:{remote:'Этот e-mail уже зарегистрирован. <a href="/signup/forgot/" target="_blank">Забыли пароль?</a>'},
            email2:{remote:'Этот e-mail не зарегистрирован'}
        }
    });
    
    $('#form_estate_reg input[name="email"]').focus(function(){$('input[name="signup"]').val(['2']);});
    $('#form_estate_reg input[name="email2"]').focus(function(){$('input[name="signup"]').val(['1']);});
    $('#form_estate_reg input[name="pass"]').focus(function(){$('input[name="signup"]').val(['1']);});
    
    estate_add_init();
    
    $('#img_estate_add').click(function(){location.href = '/estate/add/';});
    $('#img_estate_order').click(function(){location.href = '/estate/order/';});
    
    $(".tt").each(function(){
        $('#'+this.id).easytooltip(this.id+'_div');
    });
    
});

function lightbox_init() {
    
    $('#lightbox a, .lightbox').lightBox({
        imageLoading:'/i/jquery/lightbox/images/lightbox-ico-loading.gif',
        imageBtnClose:'/i/jquery/lightbox/images/lightbox-btn-close2.gif',
        imageBtnPrev:'/i/jquery/lightbox/images/lightbox-btn-prev2.gif',
        imageBtnNext:'/i/jquery/lightbox/images/lightbox-btn-next2.gif',
        imageBlank:'/i/jquery/lightbox/images/lightbox-blank.gif',
        txtImage:'Изображение',
        txtOf:'из'
    });
    
}

var jMyCarousel_width = 0;
function jMyCarousel_calc_width() {
    
    $(".jMyCarousel img").each(function(){
        jMyCarousel_width += this.width;
    });
    
    return jMyCarousel_width>$("#td_jMyCarousel").width() ? ($("#td_jMyCarousel").width()-10)+'px' : jMyCarousel_width+'px';
    
}

$.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);
}, 'Пожалуйста, введите корректный логин.');


$.validator.addMethod('pass', function(value, element) {
    
	//if ( $.validator.optional(element) )
	 //   return "dependency-mismatch";
			alert($.validator.previousValue(element));
			var previous = $.validator.previousValue(element);
			alert(previous);
			if (!$.validator.settings.messages[element.name] )
				$.validator.settings.messages[element.name] = {};
			$.validator.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			if ( previous.old !== value ) {
				previous.old = value;
				$.validator.startRequest(element);
				data[element.name] = value;
				$.ajax($.extend(true, {
					url: '/signup/pass/check/?email='+$('input[name="email2"]').val()+'&pass='+$('input[name="pass"]').val(),
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					success: function(response) {
						if ( response ) {
							var submitted = $.validator.formSubmitted;
							$.validator.prepareElement(element);
							$.validator.formSubmitted = submitted;
							$.validator.successList.push(element);
							$.validator.showErrors();
						} else {
							var errors = {};
							errors[element.name] =  response || $.validator.defaultMessage( element, "remote" );
							$.validator.showErrors(errors);
						}
						previous.valid = response;
						$.validator.stopRequest(element, response);
					}
				}, param));
				return "pending";
			} else if( $.validator.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
    
}, 'Неверный пароль. <a href="/signup/forgot/" target="_blank">Забыли пароль?</a>');

function query(url, div, data) {
    
    $.ajax({
        dataType:'json',
        url:url,
        data:data,
        success:function(response){
            $('#'+div).html(response.html);
            lightbox_init();
        }
    });
    
}
