$(document).ready(function() {

	
	$('#header a').attr('rel', 'header');
	$('#content a').attr('rel', 'center');
	$('.same-theme-block a').attr('rel', 'same-theme');
	$('#left-side a').attr('rel', 'left-side');
	$('#right-side a').attr('rel', 'right-side');
	$('#footer a').attr('rel', 'footer');
	$('#fresh-news a').attr('rel', 'fresh-news');
	$('#social-buttons a').attr('rel', 'social');
	
	
	$('a').live('mousedown', function(){
		
		if($(this).attr('href')==undefined)
			return; // mb logo clicked
		
		var req = new JsHttpRequest();
		req.open('post', '/ajax/clicker/', true);
		req.send({
			'page': location.href,
			'href': $(this).attr('href'),
			'text': $(this).text(),
			'useragent': navigator.userAgent,
			'block': ($(this).attr('rel') ? $(this).attr('rel') : 'other')
		});
		
	});
	
	
	$('#comment-login').bind('click', function(){
		$('#comment-anonymouse-form').toggle();
		$('#comment-login-form').toggle();
		
		$('#post-mode').val($('#post-mode').val()=='login' ? 'anonymouse' : 'login');
		
		return false;
	});
	
	
///////////////////////////////////////////////////////////////////////

	$('#form-comment-main #comment').bind('keydown', function(e) {
		var x = this;
		if(e.ctrlKey && e.keyCode==13 && $(x).val()!='' && $(x).val().length>1) {
			$('#form-comment-main').submit();
			return false;
		}
	});
	
	$('#form-comment-main').bind('submit', function(e) {
    	$('#form-comment-main #submit-button').attr('disabled', 'disabled');
    	$('#form-comment-main input, #form-comment-main textarea').attr('readonly', 'readonly');
    	
    	$('#form-comment-main #comment').unbind('keydown');
    	$('#my-opinion').unbind('click');    	
	});
	
///////////////////////////////////////////////////////////////////////	
	
	var tracking_news = new Array();
	var walk_obj = lid==1 ? latest_news_ru : latest_news_ua;
	$.each(walk_obj, function(k, e){
		tracking_news.push('<a href="'+e.link+'?top-rotation" title="'+e.header+'">'+e.header+'</a>');
	});
	
	$('#header-fresh-news-fade > div.mega-link:gt(2)').remove();
	var offset = 3;	
	var content='';
	setInterval(function(){
		var i=0;
		content='';
		for (i=0;i<=2;i++) {
			var link = tracking_news[i+offset];
			if(link!=undefined) {
				content=content+'<div class="mega-link hidden">'+link+'</div>';
			}
		}
		offset=offset+3;
		if(tracking_news.length<=offset)
			offset=0;
			
		$('#header-fresh-news-fade > div.mega-link').fadeOut(750, function(){
			$('#header-fresh-news-fade > div.mega-link').remove();
			$('#header-fresh-news-fade').append(content);
			$('#header-fresh-news-fade > div.mega-link').fadeIn(500);
		});

	},20*1000); // ротация 30 сек
	
	
	
	// тугл блока "О сайте"
	$('#short-site-info-details').bind('click', function(){
		$('#short-site-info .hidden').toggle();
		return false;
	});
	
	
	
	
	$(document).pngFix(); // PNG fix			

	
	var fresh_news_tab_id = 1;
	// свежие новости, стрелочки tab++/-- (layout)
	$('#tab-arrow-inc').bind('click', function() { // ++
	
		if($('#today-news li.tab'+(fresh_news_tab_id+1)).length==0) {
			return false;
		}
		
		$('#tab-arrow-dec').show();
		fresh_news_tab_id++;
				
		$('#today-news li:visible').hide();
		$('#today-news li.tab'+fresh_news_tab_id).show();
		
		
		if(fresh_news_tab_id==1) {
			$('#tab-arrow-dec').hide();
		}
		
		if($('#today-news li.tab'+(fresh_news_tab_id+1)).length==0) {
			$('#tab-arrow-inc').hide();
		}
		
		return false;
	});
	
	$('#tab-arrow-dec').bind('click', function() { // --
		
		if($('#today-news li.tab'+(fresh_news_tab_id-1)).length==0) {
			return false;
		}
		
		$('#tab-arrow-inc').show();
		fresh_news_tab_id--;
				
		$('#today-news li:visible').hide();
		$('#today-news li.tab'+fresh_news_tab_id).show();
		
		
		if(fresh_news_tab_id==1) {
			$('#tab-arrow-dec').hide();
		}
		
		if($('#today-news li.tab'+(fresh_news_tab_id+1)).length==0) {
			$('#tab-arrow-inc').hide();
		}
		
		return false;
		
	});
	
	
	$('#category-top-news > li > h1').bind('mouseenter', function () {
			
		var i = $(this).parent().children('img');
		var l = $(this).children('a').attr('href');
		
		$('#category-top-news-link').attr('href', l);
		$('#category-top-news-image').attr('src', $(i).attr('src'));
		$('#category-top-news-image').attr('alt', $(i).attr('alt'));

		//t=true;
	});
	
	// зум шрифта
	$('#text-size span').bind('click', function(){
		
		$('#news-content p').css('font-size', $(this).css('font-size'));
		$('#text-size span').removeClass('current');
		$.cookie("news_font_size", $(this).attr('class'), { path: '/', expires: 360 });
		$(this).addClass('current');
	});
	
	//  "Мой город"
	$('.this-is-my-city a').bind('click', function(){
		var city_en = $(this).attr('title').replace(/(.*)\(([a-z\-]+)\)(.*)$/gi, '$2');
		$.cookie("weather_user_city", city_en, { path: '/', expires: 360 });
		$('.this-is-my-city .saved').show();
		$(this).hide();
		$('.this-is-my-city .my-city').show();
		setTimeout(function(){
			$('.this-is-my-city .saved').fadeOut(500);
		}, 5000);

		return false;
	});
	
	
	//  свитчер картинок на глагне
	$('#actual-2nd-news h1').bind('mouseenter', function() {
		$('#second-actual-news-image').css('background', 'url(' + $(this).children('img').attr('src') + ')');
		$('#actual-2nd-news h1').removeClass('active-actual-news');
		$('#second-actuality-timer').text($(this).children('span').text());
		$(this).addClass('active-actual-news');
	});


	// для редиректов, формирует нормальные ссылки
	jQuery.each($('.gsom'), function() {
		
		var new_lnk = $(this).attr('href');

		if(new_lnk==undefined)
			return;
		
		var new_len = $(this).attr('href').length;
		var cut_pos = strpos($(this).attr('href'), '/yarrr/');
		
		new_lnk = new_lnk.substr(cut_pos, new_len);
		



		$(this).attr('href', new_lnk.replace('/yarrr/', 'http://').replace('!', '?').replace('*', '&'));
	});

	// для редиректов, формирует нормальные ссылки
	$('.gsom').bind('click', function() {
		return yarrr($(this).attr('href').replace('?', '!', '.').replace('&', '*', '|'));
	});


	// search-input toolip label
	$('#search-query').bind("focus click", function(e){
		$('#search-form label').hide();
	});

	$('#search-query').bind("blur", function(e){
		if($('#search-query').val()=='')
			$('#search-form label').show();
	});
	
	
	// anonymus  comment  toolip label
	$('#comment-anonymouse-form input').bind("focus click", function(){
		$(this).parent().find('label').hide();
	});

	$('#comment-anonymouse-form input').bind("blur", function(e){
		if($(this).val()=='')
			$(this).parent().find('label').show();
	});


	if($('#search-query').val()=='')
		$('#search-form label').show();



	// маусовер по списку актуальных новостей, меняем имагу

	// t=false;
	
//	$('#actual-news-list li').bind('mouseenter', function() {
//		
//		obj = this;
//		$('#second-news-link').attr('href', $(obj).children('a').attr('href'));
//		$('.second-image').css('background', 'url(' + $(obj).children('img').attr('src') + ') no-repeat');
//		
//		$('#actual-news-list li').removeClass('active-actual-news');
//		$(this).addClass('active-actual-news');
//		
//		return;
//	});



	// свитчер погоды/валют
	$('.widget-switcher').bind('click', function() {
		if ($(this).attr('id') == 'widget-weather') {
			$('.container-widget-currency').hide();
			$('#widget-weather').hide();
			$('#widget-currency-on').hide();

			$('.container-widget-weather').show();
			$('#widget-weather-on').show();
			$('#widget-currency').show();
			
			$.cookie("widget", 'widget-currency', { path: '/', expires: 360 });
		}
		else
		{
			$('.container-widget-weather').hide();
			$('#widget-currency').hide();
			$('#widget-weather-on').hide();

			
			$('#widget-currency-on').show();
			$('#widget-weather').show();
			$('.container-widget-currency').show();

			$.cookie("widget", 'widget-weather', { path: '/', expires: 360 });
		}

		return false;
	});


	// дропдаун городов
	$('#weather-choose-city').bind('click', function() {
		$('#city-container ul').toggle();
		return false;
	});

	// клик по городу
	$('#city-container ul li.g a').bind('click', function() {
		var city_id = $(this).attr('class').replace('city_', '');
		$('#city-container ul').hide();
			
		var city_en = $(this).attr('href').replace(/(.*)\/([a-z\-]+)\/$/gi, '$2');
		$.cookie("weather_user_city", city_en, { path: '/', expires: 360 });

		//// ------------------------------------------------------------------------
		
		$('#detailed-forecast-link').attr('href', $(this).attr('href'));
		
		var city = w[city_id].t;

		var today_temperature = w[city_id].c.t;

		if (today_temperature > 0)
			today_temperature = '+' + today_temperature;

		var _percip_id = w[city_id].c.c;
		var today_clouds = weather_percip[_percip_id];

		var _image_id = w[city_id].c.i;
		var today_image = weather_images['dir'] + weather_images[_image_id];

		//// ------------------------------------------------------------------------

		var next_t_max = w[city_id].n.t_max;
		var next_t_min = w[city_id].n.t_min;

		if (next_t_max > 0)
			next_t_max = '+' + next_t_max;
		if (next_t_min > 0)
			next_t_min = '+' + next_t_min;

		var _percip_id = w[city_id].n.c;
		var next_clouds = weather_percip[_percip_id];

		var _image_id = w[city_id].n.i;
		var next_image = weather_images['dir'] + weather_images[_image_id];

		//// ------------------------------------------------------------------------

		$('#weather-choose-city').text(city);
		$('#widget-weather').html(weather_translates['weather_in'] + city);
		$('.detailed-forecast a').attr('title', weather_translates['weather_detailed_in'] + city);
		$('.detailed-forecast a').html(weather_translates['forecast_in'] + city);

		var next_period = $('._p').text();

		$('.periods div').attr('title', next_period + weather_translates['in'] + city);
		$('.what-is-the-weather-today').attr('title', next_period + weather_translates['in'] + city);

		$('.what-is-the-weather-today .t').text(today_temperature);

		$('.periods ._tp').html(next_t_min + ' .. ' + next_t_max);

		$('.clouds').html(today_clouds);

		$('.precip-atm').attr('src', today_image);
		$('.periods img').attr('src', next_image);

		return false;
	});




	//  хайд списка городов по таймеру, если мышь вне списка Х мс.
	var timer;
	$("#city-container").bind("mouseleave", function(e) {
		timer = setTimeout(function() {
			$("#city-container ul").fadeOut('fast');
		}, 1000);
	});

	$("#city-container").bind("mouseenter", function(e) {
		clearTimeout(timer);
	});


	$('#b-2').attr('src', '/i/_banners/2.jpg');
	$('#b-2').css('border-color', '#fff');

	$('#b-3').attr('src', '/i/_banners/ld.gif');
	$('#b-3').css('border-color', '#fff');


	document.onkeydown = NavigateThrough;
});



/////////////////////////////////////////////////


		
function NavigateThrough (event) {
	
	if(event==undefined)        
		 return;
		 
	switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
	{
		case 0x25:
			link = $('#prev-page a').attr('href');
			if(link)
				document.location = link;
			break;
		case 0x27:
			link = $('#next-page a').attr('href');
			if(link)
				document.location = link;
			break;
	}
			
}
