//СОБЫТИЯ
$(function(){
	$.datepicker.setDefaults({
		firstDay: 1,
		dateFormat: 'yy-mm-dd',
		dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
		dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
		monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
		duration: 'fast',
		changeYear: true
		
	});
	
	$('.needClear')
	.focus(function(){
		if(this.value==this.title) this.value='';
	})
	.blur(function(){
		if(this.value=='') this.value=this.title;
	});
	
	// Рейтинг возле звезды
	$("#rating img").hover(
		function() { setRateStars($(this).attr("title")); },
		function() { setRateStars($("img.setrate").attr("title")); }
	);
	
	// Клик на звезду
	$("#rating img").click(function()
	{
		$.ajax({
			url: "/add_rating.php",
			data: "id="+$(this).parent().parent().attr("alt")+"&rate="+$(this).attr("title")+"&x=secure",
			type: "POST",
			dataType : "html",
			cache: false,

			beforeSend: function() 		{ $("#rating_sars").html("Загрузка..."); },
			success:  function(data) 	{ $("#rating_sars").html(data).fadeIn(); },
			error: function() 			{ $("#rating_sars").html("<span class=\"error\">Невозможно связаться с сервером!</span>"); }
		});
	});
});

// Установка звезд
function setRateStars(pos)
{
	var pos = parseInt(pos);
	for(i=1; i<=pos; i++)
	{
		$("#rating_"+i).attr("src", "/images/star.png");
	}
	for (i=pos+1; i<=5; i++)
	{
		$("#rating_"+i).attr("src", "/images/nostar.png");
	}
}


// Проверка E-MAIL
function EmailCheck(value)
{ 
  var re = /^\w+([\.-]?\w+)*@(((([a-z0-9]{2,})|([a-z0-9][-][a-z0-9]+))[\.][a-z0-9])|([a-z0-9]+[-]?))+[a-z0-9]+\.([a-z]{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/i; 
  if(re.test(value)) { return true; } else { return false; } 
}

// Голосования
function voteIt(btn, voting_id, answer_id,num){
    //alert('voteIterererer'+num);
    if(num==1){
        //alert('1');
	$.get(ajaxFile, {vote:voting_id, a_id:answer_id,v_num:num}, function(html){
	//	$('#voting-backup').html( $('#voting-answers').html() );
		$('#voting-answers').html( html );
		//if(answer_id==false) $('#back-to-vote').show();
	});	
    }
    else if(num==2) {
       //alert('2');
    $.get(ajaxFile, {vote:voting_id, a_id:answer_id,v_num:num}, function(html){
		//$('#voting-backup').html( $('#voting-answers2').html() );
		$('#voting-answers2').html( html );
		//if(answer_id==false) $('#back-to-vote').show();
	});	
    }							
	return false;
}							
//function showVoting(){
    //if(num==1){
//	$('#voting-screen').html( $('#voting-backup').html() );
//	$('#back-to-vote').hide();
    //}
    //else {
   	//$('#voting-screen2').html( $('#voting-backup').html() );
	//$('#back-to-vote').hide();
    //}
//	return false;
//}

// Загрузка случаейного анекдота
function LoadAnekdot()
{
	$.ajax({
		url: "/load_anekdot.php",
		data: "&x=secure",
		type: "POST",
		dataType : "html",
		cache: false,
		
		beforeSend: function() 		{ $("#anekdot_text").html(""); $("#anekdot_ajax").show(); },
		complete: function() 		{ $("#anekdot_ajax").hide(); }, 
		success:  function(data) 	{ $("#anekdot_text").html(data); },
		error: function() 			{ alert("Невозможно подключиться к серверу!"); }
	});
}

// Загрузка таблицы результатов
function LoadResultsTable(type, per)
{
	$.ajax({
		url: "/load_restable.php",
		data: "type="+type+"&per="+per+"&x=secure",
		type: "POST",
		dataType : "html",
		cache: false,
		
		beforeSend: function() 		{ $("#res_place").html(""); $("#res_ajax").show(); },
		complete: function() 		{ $("#res_ajax").hide(); }, 
		success:  function(data) 	{ $("#res_place").html(data); },
		error: function() 			{ alert("Невозможно подключиться к серверу!"); }
	});
}

// Загрузка комментариев
function LoadComments(id, page)
{
	$.ajax({
    		url: "/load_comments.php",
			data: "id="+id+"&pg="+page+"&x=secure",
			type: "POST",
			dataType : "html",
			cache: false,
	
			beforeSend: function() 		{ $("#comments_ajax").show(); $("#comments").html(""); },
			complete: function() 		{ $("#comments_ajax").hide();  }, 
			success:  function(data) 	{ $("#comments").html(data); },
			error: function() 			{ $("#comments").html('<p class="error">Невозможно подключиться к серверу, попробуйте позже!</p>'); }
    });    

}

// Загрузка календаря событий
function LoadCalendar(mounth, year)
{
	$.ajax({
    		url: "/load_calendar.php",
			data: "mounth="+mounth+"&year="+year+"&x=secure",
			type: "POST",
			dataType : "html",
			cache: false,
	
			beforeSend: function() 		{ $("#calendar_place").html('<div style="margin-top:25px;">Загрузка...</div>'); },
			success:  function(data) 	{ $("#calendar_place").html(data); },
			error: function() 			{ alert("Невозможно подключиться к серверу, попробуйте позже!"); }
    }); 

}

// DOM
$(document).ready(function()
{
	// Календарь событий
	$("#calendar_switcher").click(function()
	{
		if ($(this).attr("alt") == 0) {
		  $(this).attr("alt", "1");
		  $("#calendar_container").slideDown();
		  LoadCalendar($("#cal_m").val(), $("#cal_y").val());
		} else {
		  $(this).attr("alt", "0");
		  $("#calendar_container").slideUp();
		}
	});
	$("#calendar_selects select").change(function()
	{
		LoadCalendar($("#cal_m").val(), $("#cal_y").val());
	});
	
	
	// Мини поиск
	$("#mini_search_form").submit(function()
	{
		var err_msg = '';
		if (($("#mini_search_what").val() == '') || ($("#mini_search_what").val() == $("#mini_search_what").attr("title"))) { err_msg = 'Укажите что искать'; }
		if ($("#mini_search_what").val().length < 3) { err_msg = 'Фраза поиска должна быть не короче 3х символов'; }
		if (err_msg == '') {
		  return true;
		} else {
		  alert(err_msg);
		  $("#mini_search_what").focus();
		  return false;
		}		
	});	
	
	// МЕНЮ
	$("#top_menu a.catalog").hover(
		function()
		{
			// Сбрасываем выделения меню
			$("#top_menu li").css("color","#fff").find("a").css("color","#fff");
			
			// Открываем нужное подменю если есть
			var current_submenu = $("#top_submenu_"+$(this).css("color", "#fec300").parent().attr("alt")).attr("id");
			
			// Скрываем все подменю
			$(".top_submenu").hide();
			
			if (current_submenu != null)
			{	
				// Открываем меню
				$("#"+current_submenu).show();
			} else {
			     $("#empty_div").show();
			}
		}
	);
	
	// БЕГУЩАЯ СТРОКА
	$("#marquee1").marquee(
	{
		scrollSpeed: 20,
		pauseSpeed: 1000,
	});	
	// БЕГУЩАЯ СТРОКА - Пауза/Продолжить
	$("#marquee_pause").click(function()
	{
		if ($(this).attr("alt") == 0) {
		  $(this).attr("alt", "1").css("opacity", "0.5"); $("#marquee1").marquee("pause");
		} else {
		  $(this).attr("alt", "0").css("opacity", "1.0"); $("#marquee1").marquee("resume");
		}
	});
	
	// Бегущая строка следующий
	$("#marquee_next").click(function()
	{
		$("#marquee1").next();
	});

	// ТАБЛИЦА РЕЗУЛЬТАТОВ
	$("#sport_table_program_btn").click(function()
	{
		self.location = '/'+_LANG_+'/pages/477.html';
	});
	
	// ТАБЫ
	$(".left_tab_expander").click(function()
	{
		if ($(this).attr("alt") == 0) {
		  $(this).attr("alt", "1").css("background-image", "url(/images/unexpand.png)").parent().parent().find(".tab_tab").slideDown();
		} else {
		  $(this).attr("alt", "0").css("background-image", "url(/images/expand.png)").parent().parent().find(".tab_tab").slideUp();
		}	
	});
	$(".right_tab_expander").click(function()
	{
		if ($(this).attr("alt") == 0) {
		  $(this).attr("alt", "1").css("background-image", "url(/images/unexpand.png)").parent().parent().find(".tab_tab").slideDown();
		} else {
		  $(this).attr("alt", "0").css("background-image", "url(/images/expand.png)").parent().parent().find(".tab_tab").slideUp();
		}	
	});
	
	$("#send").fancybox({
		'scrolling'		: 'no',
		'titleShow'		: false,
	});
	
	$("#subscribe_form").submit(function()
	{
		if (($("#subs_email").val() == "") || (EmailCheck($("#subs_email").val()) == false))
		{
			alert("Укажите правильный E-Mail");
		} else {
			$.ajax({
				url: "/subscribe.php",
				data: "email="+$("#subs_email").val()+"&x=secure",
				type: "POST",
				dataType : "html",
				cache: false,

				success:  function(data) 	{ $("#subscribe_protocol").html(data); },
				error: function() 			{ alert("Невозможно подключиться к серверу!"); }
    		});		
		}
		
		return false;
	});
	
	
	// Еще анекдот
	$("#more_anekdot").click(function()
	{	
		LoadAnekdot();	
		return false;
	});
	
	// Нижний инфобокс
	$("#footer_infobox_swich").click(function()
	{
		if ($(this).attr("alt") == 0) {
		  $(this).attr("alt", "1").css("background-image", "url(/images/footer_slider_down.gif)");
		  $("#footer_infobox").slideDown();
		} else {
		  $(this).attr("alt", "0").css("background-image", "url(/images/footer_slider_up.gif)");
		  $("#footer_infobox").slideUp();
		}
	});
	
	// Дополнительная информация
	$("div.full_new_addon_head").click(function()
	{
		if ($(this).attr("alt") == 0) {
			$(this).attr("alt", "1").parent().find("div.full_new_addon_content").slideDown("fast");
		} else {
			$(this).attr("alt", "0").parent().find("div.full_new_addon_content").slideUp("fast");
		}
	});
});




