// JavaScript Document
/*
    © icw82 (functions)
*/

/* определдение версии IE */

function getIEVersion()
{
	var ua=navigator.userAgent;	
	var set=ua.indexOf("MSIE ");
	if(set!=-1) return parseFloat(ua.substring(set+5,ua.indexOf(";", set)));
}
	var IEVersion=getIEVersion();

function hasBrowser(name)
{
	var ua=navigator.userAgent;
	var result=ua.indexOf(name);
	if(result!=-1) return true;
}

function getFlashPlayerVersion(){
	var i;var ver;if(navigator.appVersion.indexOf("MSIE")!=-1){try{for(i=7;i<=15;i++)
	{if(eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')) ver=i;}}
	catch(e){};if(ver>7) return ver; else return false}else{for(i=0;
	i<navigator.plugins.length;i++){if(navigator.plugins[i].name.indexOf('Flash')>-1)
	{var t=true;var p=/Flash\s(.+)\s/;var out=p.exec(navigator.plugins[i].description);
	return parseInt(out[1])}}if(t!=true)return false;}
}

function placeholder(id, value, action)
{
	var e=document.getElementById(id);
	
	if ((action=='hide')&&(e.value==value))
	{
		e.value='';
		q.className='search-text';
	}
	
	if ((action=='show')&&((e.value=='')||(e.value==' ')))
	{
		e.value=value;
		q.className='search-placeholder';
	}
}

/* Навигация стрелками. С разрешения Татьяныча. */
document.onkeydown=NavigateThrough;

function NavigateThrough (event){
	if (!document.getElementById) return;
	if (window.event) event=window.event;
	if (event.ctrlKey)
	{
		var link=null;
		var href=null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which:null)
		{
			case 0x27:
				link=document.getElementById('NextLink'); break;
			case 0x25:
				link=document.getElementById('PrevLink'); break;
			case 0x24: href='/'; break;
		}

		if (link && link.href) document.location=link.href;
		if (href) document.location=href;
	}			
}

// jQuery
$(document).ready(function(){
	if($('div').hasClass('pn-live')){
		if ($('#player').length==0){
			var rTime=20; // в секундах
			var rUrl=window.location.href; // URL перезагрузки

			rIv=setInterval(function(){$('.timeout em').html(--rTime); if(rTime==0) clearInterval(rIv)},1000);		
			rTo=setTimeout(function(){window.location.href=rUrl},1000*rTime);

			$('.timeout a').click(function(){
				clearTimeout(rTo);
				clearInterval(rIv);
				$('.timeout').html('Автоматическая перезагрузка отменена');
			})
		} else {
			$('.timeout').html('Автоматическая перезагрузка отменена');
		}
	}
	
	// Форма поиска
	if(hasBrowser('Safari'))
		$('.search-form span').html('<input maxlength="80" size="20" type="search" placeholder="Поиск" results="" name="query" />')
	else{
		$('.search-form span').html('<input maxlength="80" size="20" type="text" value="поиск" class="placeholder" name="query" />');
		$('.search-form .placeholder').focus(function(){if($(this).attr('value')=='поиск') $(this).removeClass('placeholder').attr('value','');});
		$('.search-form .placeholder').blur(function(){if($(this).attr('value')=='') $(this).addClass('placeholder').attr('value','поиск');});
	}


	$('.switch').click(function(){
		$(this).toggleClass('expanded');
		$(this).parents('.issue-list').find('.list').slideToggle(500);
	});

	$('.archive-months .inner').hide();
	$('.archive-months .inner div').find('.active').parents('.inner').slideDown(600);
	
	$('.archive-days .inner').hide();
	$('.archive-days .inner div').find('.active').parents('.inner').slideDown(600);


	$('.archive-switches em').click(function(){
		$(this).addClass('active');
		$(this).siblings('em').removeClass('active');
		
		var arcYear=$(this).text();

		$('.archive-months .inner div').find('p:contains('+arcYear+')').parents('.inner').slideDown(600);
		$('.archive-months .inner div').find('p:not(:contains('+arcYear+'))').parents('.inner').slideUp(300);

		$('.archive-days .inner').slideUp(300);
	})


	$('.archive-months .inner div em').click(function(){
		$(this).addClass('active');
		$(this).siblings('em').removeClass('active');
		
		var arcYear=$(this).siblings('p').text();
		
		var arcMonth=$(this).text();

		$('.archive-days .inner div').find('p:contains("'+arcYear+arcMonth+'")').parents('.inner').slideDown(600);		
		$('.archive-days .inner div').find('p:not(:contains('+arcYear+arcMonth+'))').parents('.inner').slideUp(300);
	})

	function imgComp(e,x){
		if(e.attr('width')<e.attr('height')) e.css('width',e.attr('width')/e.attr('height')*x+'%');		
		e.load(function(){if(e.attr('width')<e.attr('height')) e.css('width',e.attr('width')/e.attr('height')*x+'%');});
	};
	
	// фикс высоких изображений
	$('div.ct-main img:not(.notfix)').each(function(i){imgComp($(this),75);});
	$('div.ct-main-2 img:not(.notfix)').each(function(i){imgComp($(this),75);});
	$('.pn-mainpage .main-news .first img:not(.notfix)').each(function(i){imgComp($(this),33.75);});
	
	// фикс Тюба
	if(getFlashPlayerVersion()){
		$('.video-code object').attr('width','100%');
		$('.video-code embed').attr('width','100%');
	}else{
		$('.video-code').html('У вас отключен JavaScript либо установлена устаревшая версия проигрывателя Adobe Flash. <a href="http://www.adobe.com/go/getflashplayer/">Загрузите новый проигрыватель Flash</a>').addClass('alert')
	}
	
	// Опрос (скрипт, далёкий от совершенства)
	var pollMax=0;
	$('div.panel-polling .results div').each(function(i)
	{
		pollN=$(this).attr('title');
		pollN=pollN+1-1;
		if (pollN>pollMax) pollMax=pollN;
	})

	$('div.panel-polling .results div').each(function(i)
	{
		pollN=$(this).attr('title');
		pollW=(pollN+1-1)/pollMax*100;
		$(this).css('width',pollW+'%')
		$(this).siblings('p').find('span').text('('+pollN+')')
	})

	
	// LI.RU
	$('.hide-it .counters').html('<a class="invisible" href="http://www.liveinternet.ru/stat/asnta.ru/"><img alt="" src="http://counter.yadro.ru/hit?t14.1;r'+escape(document.referrer)+((typeof(screen)=='undefined')?'':';s'+screen.width+'*'+screen.height+'*'+(screen.colorDepth?screen.colorDepth:screen.pixelDepth))+';u'+escape(document.URL)+';'+Math.random()+'" /></a><a href="http://top.mail.ru/jump?from=786057"><img alt="" src="http://top.list.ru/counter?id=786057;t=53;js=13;r='+escape(document.referrer)+';j='+navigator.javaEnabled()+';s='+screen.width+'*'+screen.height+';d='+(screen.colorDepth?screen.colorDepth:screen.pixelDepth)+';rand='+Math.random()+'"/></a>');
	
	// Mail.ru
	/*$('.mail-ru-counter').html('');*/
	
	// презент
	$('#yoz').click(function(){	$('.show-it').show(); $('.hide-it').hide(); })
	
	
	// achtung
	if((IEVersion)&&(IEVersion<8))
	{
		$('a img').parents('a').attr('style','border:0 none');

		if(IEVersion<8)
		{
			$('.browser-warning').html('<div><p>Уважаемый пользователь <strong>Internet Explorer '+IEVersion+'</strong>!<br />Рекомендуем <a href="http://www.microsoft.com/windows/Internet-explorer/">обновить</a> или сменить ваш браузер на более быстрый, удобный и качественный.<br />Например на <a href="http://www.mozilla-europe.org/ru/firefox/">Mozilla Firefox</a>, <a href="http://www.google.com/chrome/">Google Chrome</a>, <a href="http://ru.opera.com/">Opera</a>, <a href="http://www.apple.com/safari/">Apple Safari</a>.</p><p>Обращаем ваше внимание на то, что ваш браузер лишь частично поддерживает<br />основные веб-стандарты, что не позволяет вам получать адекватное отображение страниц.</p></div>');
		};
	}	

	$('.drop-down-list').each(function(i){
		var headers=$(this).find("ul").parent()
		headers.each(function(i){
			var subul=$(this).find('ul:eq(0)');
			$(this).hover(
				function(e){
					subul.css({top:$(this).offset().top+this.offsetHeight+'px'})
					subul.css({left:$(this).offset().left+'px'})
					subul.slideDown(250);
				},
				function(e){
					subul.hide(150);
				}
			)
		})
	})
});

