$(
	function(){
		// Table highlight
		// $("table.data tr").hover(
		// 	function(){
		// 		$(this).addClass("hover");
		// 	},
		// 	function(){
		// 		$(this).removeClass("hover");
		// 	}
		// );
		
		
		// Poll
		$(".poll .poll_submit").click(
			function(){
				var pollingId = $("input[@name=polling_id]", $(this).parent()).val();
				var variantId = $("input:checked[@name=variant]", $(this).parent()).val();
				sendPoll(pollingId, variantId);
				$.cookie("polling_id", pollingId, { path: '/', expires: 100 });
			}
		);
		
		// Search placeholder
		if (!jQuery.browser.safari) {
			var searchField = $("#search_field");
			var inputPlaceholder = searchField.attr("placeholder");
			if(!searchField.val()) { searchField.val(inputPlaceholder).addClass("empty"); }
			searchField.focus( function() { if($(this).hasClass("empty")){ $(this).val("").removeClass("empty"); }  } );
			searchField.blur( function() { if(!$(this).val()){ $(this).val(inputPlaceholder).addClass("empty"); }  } )
		};
		
		$("#search_form").submit(
			function(){
				var searchField = $("#search_field");
				if((searchField.val() == '') || (searchField.hasClass("empty"))) {
					return false;
				}
			}
		);
		
		// Animated banners
		$("#top_promos .promo").hover(
			function(){
				$(this).stop().animate({width:320},1000,"easeOutCirc");// , paddingLeft:"5px", paddingRight:"5px"  //, paddingLeft:"0", paddingRight:"0"
				$(".info", this).stop().animate({marginLeft:"105px"});
				$("img", this).stop().animate({left:"23px"});
			},
			function(){
				$(this).stop().animate({width:100},800,"easeOutQuint"); //, paddingLeft:"0", paddingRight:"0"
				$(".info", this).stop().animate({marginLeft:"100px"});
				$("img", this).stop().animate({left:"19px"});
			}
		);
		
		$("#promos .promo").hover(
			function(){
				$("img", this).stop().animate({opacity:0.7}, 800);
				$(".slogan", this).stop().animate( { color: '#c9891c' }, 800);
			},
			function(){
				$("img", this).stop().animate({opacity:1}, 800);
				$(".slogan", this).stop().animate( { color: '#999999' }, 800);
			}
		);
		
		// Fade out when click link
		$("a[href*='/']").click(
			function(){
				if (!jQuery.browser.msie) {
					$("body").fadeOut("fast");
				}
				// else {
				// 	$("body").css({"filter":"progid:DXImageTransform.Microsoft.MotionBlur(strength=8, direction=180)"});
				// }
			}
		);
		
		// In text description animation
		$(".described .term").click(
			function(){
				var term = $(this).parent();
				var description = $(".description", term);
				if (term.hasClass("opened")){
					term.removeClass("opened");
					description.hasClass("big") ? description.slideUp("fast") : description.fadeIn("fast");
					
				}
				else {
					term.addClass("opened");
					description.hasClass("big") ? description.slideDown("fast") : description.fadeOut("fast");
				}
			}
		);
		
		// In text tooltip animation
		$(".tooltip").click(
			function(){
				var description = $(".description", $(this));
				if ($(this).hasClass("opened")){
					$(this).removeClass("opened");
					description.fadeOut("fast");
				}
				else {
					$(".tooltip").removeClass("opened");
					$(".description").fadeOut("fast");
					$(this).addClass("opened");
					description.fadeIn("fast");
				}
			}
		);
		
		$(".tooltip").hover(
			function(){ $(this).addClass("hovered") },
			function(){ $(this).removeClass("hovered") }
		);
		
		// Poll start checker
		$(".poll input:radio:first").attr("checked","checked");

		$("#communication").keyup(
			function(){
				var messageLength = $(this).val().length;
				
				if(messageLength > 160){
					$(this).val($(this).val().substring(0, 160));
					$("#char_counter").text(160);
				}
				else { $("#char_counter").text(messageLength); }
			}
		);
		$("#communication").blur(
			function(){
				var messageLength = $(this).val().length;
				if(messageLength > 160){
					$(this).val($(this).val().substring(0, 160));
					$("#char_counter").text(160);
				}
			}
		);
		
		$(document).keydown(
			function(e){
				if (e.ctrlKey){
					var link = null;
					var href = null;
					switch (e.keyCode ? e.keyCode : e.which ? e.which : null){
						case 0x25:
						link = document.getElementById ('NavPrev');
						break;
						case 0x27:
						link = document.getElementById ('NavNext');
						break;
						case 0x26:
						link = document.getElementById ('NavUp');
						break;
						case 0x28:
						link = document.getElementById ('NavDown');
						break;
						case 0x24:
						href = '/';
						break;
					}
				}
				if (link && link.href) { document.location = link.href; if (!jQuery.browser.msie) $("body").fadeOut("fast"); }
				if (href) { document.location = href; if (!jQuery.browser.msie) $("body").fadeOut("fast"); }
			}
		);
		
		// $("body").fadeIn("fast");
		var checkTimer;
		$("#issa_login_form #phone_number").val("8 ").keydown(
			function(e){
				if(e.keyCode == 8){
					return;
				}
				checkTimer = setTimeout("checkISSANumber()", 10);
			}
		).keyup(
			function(){
				clearInterval(checkTimer);
			}
		);
		
		$("#issa_login_form").submit(
			function(){
				var toRealValue = $("#phone_number").val();
				var toRealValue = toRealValue.replace(/[^\d]/g, "").replace(/^8/,"");
				
				if (toRealValue){
					// window.console.log("Value: " + toRealValue);
					$(this).append('<input type="hidden" name="phone_number_real" value="' + toRealValue + '"/>');
				}
			}
		);
		
		$("#issa_login_form").validate({
				rules: {
					phone_number: {
						required: true
					},
					password: {
						required: true
					}
				},
				messages: {
					phone_number: {
						required: "Укажите, пожалуйста, ваш номер"
					},
					password: "Введите пароль"
				}
		});
		
		$("#feedback").validate({
				rules: {
					name: {
						required: true,
						minlength: 2
					},
					email: {
						required: true,
						email: true
					},
					text: {
						required:true
					}
				},
				messages: {
					name: {
						required: "Укажите, пожалуйста, ваше имя",
						minlength: "Введите хотя бы пару символов"
					},
					email: "Введите верный адрес электронной почты",
					text: "Сообщите нам что-нибудь"
				}
		});
		
		$("#sms_send").validate({
				rules: {
					phone_number: {
						required: true,
						minlength: 7
					},
					communication: {
						required:true
					},
					code: {
						required:true
					}
				},
				messages: {
					phone_number: "Укажите, пожалуйста, номер телефона",
					communication: "Введите текст сообщения",
					code: "Введите тогда уже и кодrequired:true"
				}
		});
	}
);

function showPollResults(data){
	$(".poll .variant").remove();
	$(".poll .poll_submit").remove();
	$(".poll").append(data);
}

function sendPoll(polling_id, variant_id){
	$.get("/loader/",
		{
			polling_vote: 1,
			polling_id: polling_id,
			variant_id: variant_id
		},
		function(data) {
			showPollResults(data);
		}
	);
}

function checkISSANumber(){
	var currentInput = $("#issa_login_form #phone_number");
	currentInput.get(0).disabled = true;
	var currentValue = currentInput.val();
	var outputValue = "8 ";

	// window.console.log("Current: "+ currentValue);

	if(currentValue.length > 13){
		outputValue = currentValue.substring(0,15);
		currentInput.val(outputValue);
		currentInput.get(0).disabled = false;
		return;
	}

	var matcher = currentValue.match(/(\d)\s(\d+)?\s?(\d+)?-?(\d+)?-?(\d)?/);

	if (matcher){
		if(matcher[2]){
			outputValue += matcher[2].substring(0,3);
			if(matcher[2].length >= 3){ outputValue += " "; }
		}

		if(matcher[3]){
			outputValue += matcher[3].substring(0,3);
			if(matcher[3].length >= 3){ outputValue += "-"; }
		}

		if(matcher[4]){
			outputValue += matcher[4].substring(0,2);
			if(matcher[4].length >= 2){ outputValue += "-"; }
		}

		// if(matcher[5]){
		// 	outputValue += matcher[5];
		// 	if(matcher[5].length >= 2){ outputValue += "-"; }
		// }
	}
	// window.console.log("Matcher: ", matcher);
	currentInput.get(0).disabled = false;
	currentInput.val(outputValue);
}