jQuery(document).ready(function() {
	//Пилим прокрутку
	jQuery('#up_scroller').click(function() {
		jQuery('html, body').stop().animate({
                        scrollTop: 0},
			1500,
			'easeInOutExpo');
	});
	
	if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
		jQuery('#up_scroller').remove();
	}
	
	jQuery(window).scroll(function () {
		if( jQuery(window).scrollTop() > 800 ){
			if( !jQuery('#up_scroller').hasClass('scroller_show') ){
				jQuery('#up_scroller').removeClass('scroller_hide');
				jQuery('#up_scroller').addClass('scroller_show');
				jQuery('#up_scroller').fadeIn();
			}
		}
		
		if( jQuery(window).scrollTop() < 800 ){
			if( !jQuery('#up_scroller').hasClass('scroller_hide') ){
				jQuery('#up_scroller').removeClass('scroller_show');
				jQuery('#up_scroller').addClass('scroller_hide');
				jQuery('#up_scroller').fadeOut();
			}
		}
	});
	
	//Отслеживаем нажатие ctrl+enter для функционала "сообщить об ошибке"
	jQuery(document).keypress(function(event){
		if( (event.ctrlKey) && ( (event.keyCode == 0xA) || (event.keyCode == 0xD) ) ){
			var modMinHeight = 290;
			var txt = '';
			if (window.getSelection) {
			    txt = window.getSelection();
			} else if (document.getSelection) {
			    txt = document.getSelection();
			} else if (document.selection) {
			    txt = document.selection.createRange().text;
			}
			txt = txt.toString();
			
			if(txt != '' && txt.length <= 500){
				txt = 'Выделенный текст: <i>«'+txt+'»</i>';
				
				if( jQuery('form#error table').has('tr td#err_selected_txt').length == 0 ){
					jQuery('form#error table tr:eq(0)').after('<tr><td id="err_selected_txt">'+txt+'</td></tr><tr><td></td></tr>');
				}else{
					jQuery('form#error table td#err_selected_txt').html(txt);
					jQuery('form#error input[name=error_selected_text]').remove();
				}
				jQuery('form#error').append('<input type="hidden" name="error_selected_text" value="'+txt+'" />');
				
				modMinHeight = modMinHeight + txt.length/3.5;
			}
			jQuery('form#error').modal({close: true, overlayClose:true, minHeight: modMinHeight});
		}
	})
	
	if (jQuery('#right_news').length>0) {
		jQuery('#right_news hr:last').remove(); //Нет, ничуть не стыдно.
	}

	if (jQuery('input#city')) {
		sg_city=getLocation();
		jQuery('input#city').val(sg_city);
	}

	jQuery('#google_translate a').click(function(e) {
		jQuery('#gtrslt').css({
			left: jQuery('#google_translate').position().left
		});
		jQuery('#gtrslt').toggle('fast');return false;
		e.preventDefault();
	});


	jQuery('.msg_svc a.btn_close').live('click', function() {
		jQuery('.msg_svc').fadeOut('fast', function() {
			jQuery('.msg_svc').remove()
		});
		return false;
	});

	jQuery('.msg_svc_err a.btn_close').live('click', function() {
		jQuery('.msg_svc_err').fadeOut('fast', function() {
			jQuery('.msg_svc_err').remove()
		});
		return false;
	});
	
		jQuery('#demo_order_button').click(function(){
		jQuery('form#demo').modal({close: true, overlayClose:true});
	});
	
	jQuery('form.ajax_uni_form input[type=button]').button();
	
	jQuery('form.ajax_uni_form input.city').focusin(function(){
		if(jQuery(this).val() == 'Москва'){
			jQuery(this).val('');
		}
	});
	
	jQuery('form.ajax_uni_form input.city').focusout(function(){
		if(jQuery(this).val() == ''){
			jQuery(this).val('Москва');
		}					    
	});
	
	
	/*
	  Универсальный обработчик аяксовых форм для сайта
	  Антибардак!
	*/
	
	jQuery('form.ajax_uni_form input[type=button]').click(function(){
		//Проверка заполненности полей
		var zero_flag = false;
		
		var form_type = jQuery(this).parents('form.ajax_uni_form').attr('id');
		
		jQuery('form#'+form_type+'.ajax_uni_form .req').each(function(){
			
			if( jQuery(this).val() == '' ){
				zero_flag = true;
				jQuery(this).css('background-color','red');
				
				jQuery(this).focusin(function(){
					jQuery(this).css('background-color','white');
				});
				
				jQuery(this).focusout(function(){
					
					if( jQuery(this).val() == '' ){
						jQuery(this).css('background-color','red');
					}
				});
			}else{
				jQuery(this).css('background-color','white');
			}
		});
		
		if( zero_flag === true ){
			jQuery('form#'+form_type+'.ajax_uni_form td.about_form_msg').html('<span class="red">Необходимо заполнить все поля формы!</span>');
			return false;
		}else{
			jQuery('form#'+form_type+'.ajax_uni_form td.about_form_msg').html('&nbsp;');
		}
		
		//Отправим стафф
		var data_to_send = jQuery('form#'+form_type+'.ajax_uni_form').serialize();
		
		//Если надо будет получить инфу откуда юзер заполнял форму
		data_to_send    += '&from_page='+window.document.location.href;
		
		//UPD 14.09.2011 Доп. инфа о браузере
		data_to_send    += '&browser_name='+navigator.appName;
		data_to_send    += '&browser_vervion='+navigator.appVersion;
		data_to_send    += '&browser_resolution='+screen.availWidth +'x'+ screen.availHeight;
		
		jQuery.ajax({
			type: 'POST',
			url: '/ajax/uni_form_send.php',
			data: data_to_send,
			beforeSend: function(){
				jQuery('form#'+form_type+'.ajax_uni_form img.ajax_form_load').show();
			},
			success: function(msg){
				
				//Google Analitycs tracking
				_gaq.push(['_trackPageview', '/goal/'+form_type]);
				//Yandex.Metrika tracking
				yaCounter35825.reachGoal(form_type);
				
				jQuery('form#'+form_type+'.ajax_uni_form img.ajax_form_load').hide();
				jQuery('form#'+form_type+'.ajax_uni_form td.about_form_msg').html('<span style="color: green;">'+msg+'</span>');
				window.setTimeout('jQuery.modal.close();', 3000)
			},
			error: function(){
				jQuery('form#'+form_type+'.ajax_uni_form img.ajax_form_load').hide();
				jQuery('form#'+form_type+'.ajax_uni_form td.about_form_msg').html('<span class="red">Произошла ошибка!</span>');
			}
		});
		
		
		
	});
	
    jQuery('#sale_form input[type=button]').button();
    
    jQuery('#sale_form input[type=text]').each(function(){
        bind_auto_text_values(this, jQuery(this).val());
    })
    bind_auto_text_values(jQuery('#sale_form input[name="mail_from"]'), 'Укажите корректный e-mail!');
    jQuery('#sale_form input[type=button]').click(function(){
            //Проверка заполненности полей
            var zero_flag = false;
            
            jQuery('#sale_form input[type=text]').each(function(){
                    
                    if( jQuery(this).val() == '' || jQuery(this).val() == 'ФИО' || jQuery(this).val() == 'Телефон' || jQuery(this).val() == 'E-mail' || jQuery(this).val() == 'Укажите корректный e-mail!'){
                            zero_flag = true;
                            jQuery(this).css('background-color','red');
                            
                            jQuery(this).focusin(function(){
                                    jQuery(this).css('background-color','white');
                            });
                            
                            jQuery(this).focusout(function(){
                                    
                                    if( jQuery(this).val() == '' ){
                                            jQuery(this).css('background-color','red');
                                    }
                            });
                    }else{
                            jQuery(this).css('background-color','white');
                    }
            });
            
            if( zero_flag === true )
                    return false;
		
		var regexp_mail = /[0-9a-z_]+@[0-9a-z_^.]+.[a-z]{2,3}/i;
		var mail_form   = jQuery('#sale_form input[name="mail_from"]').val();
		//Проверка электропочты
		if( jQuery('#sale_form input[name="mail_from"]').length > 0 ){
			if( !regexp_mail.test(mail_form) ){
				jQuery('#sale_form input[name="mail_from"]').val('Укажите корректный e-mail!');
				jQuery('#sale_form input[name="mail_from"]').css('background-color','red');
				return false;
			}
		}
	    
            //Отправим стафф
            var data_to_send = jQuery('#sale_form form').serialize();
            
            //Если надо будет получить инфу откуда юзер заполнял форму
            data_to_send    += '&from_page='+window.document.location.href;
            
            //UPD 14.09.2011 Доп. инфа о браузере
            data_to_send    += '&browser_name='+navigator.appName;
            data_to_send    += '&browser_vervion='+navigator.appVersion;
            data_to_send    += '&browser_resolution='+screen.availWidth +'x'+ screen.availHeight;
            data_to_send    += '&browser_resolution='+screen.availWidth +'x'+ screen.availHeight;
            
            jQuery.ajax({
                    type: 'POST',
                    url: '/ajax/uni_form_send.php',
                    data: data_to_send,
                    beforeSend: function(){
                            jQuery('#sale_form form img.ajax_form_load').show();
                    },
                    success: function(msg){
                            
                            //Google Analitycs tracking
                            _gaq.push(['_trackPageview', '/goal/sale_form']);
			    //Yandex.Metrika tracking
			    yaCounter35825.reachGoal('sale_form');
                            
                            jQuery('#sale_form').html('<span style="color: green;">'+msg+'</span>');
                    }
            });
    });

});




city='Москва';
function getLocation()
{/*
	try {
		navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
	} catch (error) {

	}
	return city;*/
}
function foundLocation(position) //Есть предположение что функция, как и соседи, не используется
{
  	var lat = position.coords.latitude;
  	var lon = position.coords.longitude; 	
	jQuery.get('/user_modules/gk.php', {lat: lat, lon: lon}, function(ret) {
		city=jQuery('LocalityName:eq(0)', ret).text();
	}, 'xml');
}
function noLocation() 	
{
}

function bind_auto_text_values(elem, value){
    jQuery(elem).focusin(function(){
        if(jQuery(this).val() == value){
            jQuery(this).val('');
        }
    });
	
    jQuery(elem).focusout(function(){
        if(jQuery(this).val() == ''){
            jQuery(this).val(value);
        }					    
    });
}
