var limit_up = 4;
var limit_down = -4;
var limit_cur = 0;

function r_name() {
    var name = _utf8_decode(Get_Cookie('username'));
    var email = _utf8_decode(Get_Cookie('useremail'));
    if (name)
	$('#name').val(name);
    if (email)
	$('#email').val(email);

}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function Get_Cookie( check_name )
{
// first we'll split this cookie up into name/value pairs
// note: document.cookie only returns name=value, not the other components
var a_all_cookies = document.cookie.split( ';' );
var a_temp_cookie = '';
var cookie_name = '';
var cookie_value = '';
var b_cookie_found = false; // set boolean t/f default f

for ( i = 0; i < a_all_cookies.length; i++ )
{
// now we'll split apart each name=value pair
a_temp_cookie = a_all_cookies[i].split( '=' );

// and trim left/right whitespace while we're at it
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

// if the extracted name matches passed check_name
if ( cookie_name == check_name )
{
b_cookie_found = true;
// we need to handle case where cookie has no value but exists (no = sign, that is):
if ( a_temp_cookie.length > 1 )
{
cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
}
// note that in cases where cookie is initialized but no value, null is returned
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if ( !b_cookie_found )
{
return null;
}
}



$(document).ready(function(){

	$("#search_image").hover(function() {
		$(this).animate({opacity: "0.7"}, "slow");
	}, function() {
		$(this).animate({opacity: "1.0"}, "slow");
	});
	
	//закладки для популярных статей
	$('.b-pop .switcher li a').click(function() {
		if($(this).hasClass('active')) {}
		else{
			bem = $(this).attr('href');
			bem = bem.substr(1,bem.length);
			
			$('.switcher li a').removeClass('active');
			$(this).addClass('active');
			
			$('div.n-block:visible').slideUp(300, function() {$('#'+bem).slideDown()});
		}
		return false;
	});
	// закладки для информеров
	$('.b-informer .switcher li a').click(function() {
		if($(this).hasClass('active')) {}
		else{
			bem = $(this).attr('href');
			bem = bem.substr(1,bem.length);
			
			$('.switcher li a').removeClass('active');
			$(this).addClass('active');
			$('div.n-blockalt:visible').slideUp(300, function() {$('#'+bem).slideDown()});
		}
		return false;
	});

	//Клик на закладки в страничке раздела, вверху на черном фоне
	$('.sw li a').click(function() {
		if($(this).hasClass('here')) {}
		else{
			bem = $(this).attr('href');
			bem = bem.substr(1,bem.length);
			
			$('.sw li a').removeClass('here');
			$(this).addClass('here');
			$('div.wraphot:visible').hide();
			
			$('.'+bem).show()
		}
		return false;
	});
	//Форма комментирования
	var state = true;
	$('.addcomment').click(function() {
		if(state){
			state = false;
			$('.addcommentform').stop().slideToggle(500, function(){state=true;});
		}
		return false;
	});		

	$('#show_comments_bar').click(function() {
		if(state){
			state = false;
			$('.addcommentform').stop().show(500, function(){state=true;});
		}
		return false;
	});		

	// карусель в разделе мультмедиа
	$(".caro").jCarouselLite({
	    btnNext: ".rightcar",
	    btnPrev: ".leftcar",
			visible: 2
	});
	// карусель для блогов
	$(".blogentries").jCarouselLite({
	    btnNext: ".rightcar1",
	    btnPrev: ".leftcar1",
			visible: 3
	});
	//наведение курсора в разделе мультимедиа
	$('.multi li .bl').hover(function() {
			$(this).parent().addClass('active');
			$('.caro').addClass('carohovered');
		},function(){
			$(this).parent().removeClass('active');
			$('.caro').removeClass('carohovered');
	});

	//__>и+и'_ _аз__ __и"'а
  $("#largerfont").click(function(){
  	var currentFontSize = $('.post').css('font-size');
 		var currentFontSizeNum = parseFloat(currentFontSize, 10);
    if (limit_cur<limit_up) {
            limit_cur = limit_cur +1;
  	var newFontSize = currentFontSizeNum+1;
		$('.post').css('font-size', newFontSize);
    }
		return false;
  });
  // _____и'_
  $("#smallerfont").click(function(){
  	var currentFontSize = $('.post').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
	if (limit_cur>limit_down) {
    	    limit_cur = limit_cur -1;
        	var newFontSize = currentFontSizeNum-1;
		$('.post').css('font-size', newFontSize);
	}
		return false;
  });
	
	//подсказки внутри инпутов, берутся из тайтла, сам плагин "after all"
	$('input[title!=""],textarea[title!=""]').hint();
	
	//статьи по теме, кликалка туда-сюда по кругу
	$('.rel-next').click(function(){
		$('#relatedpostlist li:visible').
		        hide().
		        next('li').
	          css({display:'inline'});
		      if ($('#relatedpostlist li:visible').length < 1) {
		        $('#relatedpostlist li:first').css({display:'inline'});
		      }
		return false;
	});
	$('.rel-prev').click(function(){
		$('#relatedpostlist li:visible').
		        hide().
		        prev('li').
	          css({display:'inline'});
		      if ($('#relatedpostlist li:visible').length < 1) {
		        $('#relatedpostlist li:last').css({display:'inline'});
		      }
		return false;
	});
	
	//popup for blog
	$('.b-popup .js').click(function(){
		$('.b-popup .popup').hide();
		$(this).parent().children('.popup').fadeIn('fast');
	});
	// add by goshi for blogger
	$('.b-popup .blogger').click(function(){
		$('.b-popup .popup').hide();
		$(this).parent().children('.popup').fadeIn('fast');
	});
	$('.b-popup .h3wrap').click(function(){
		$(this).parent().fadeOut('fast');
	});
	$('.printmeplease').click(function(){$('#screenstyles').attr({href:'/css/print.css'});});
	$('.backtonormal').click(function(){$('#screenstyles').attr({href:'/css/master.css'});});
	//popup for issues archives
	//$('.month:nth-child(3n)').addClass('monthlastinrow');
	$('.mdata tr:first-child').addClass("firstrow");
	//$('.mdata td a').wrap('<div class="b-popup"></div>');
	// POPUP WITH DATE ARCHIVE
/*
	$('.mdata td .b-popup').hoverIntent(function(){
		popupc = $(this).children('.popup');
		if(popupc.length>0){//if popup already created
			// have a little whiskey
		}
		else{//creating popup
			thisdate = $(this).children('a').text();
			var d = new Date();
			thisid = d.getTime();
			adate = $('a',this);

			adate.after('<div class="popup" style="display:none">'+
				'<div class="h3wrap"><h4>'+ thisdate+ '</h4></div>'+
				'<div class="popup-top"></div>'+
				'<div class="popup-str"><div class="popup-str-in" id="id'+thisid+'">'+
					'<img src="img/loader.gif" alt="Идет загрузка..." />		'+
				'</div></div>'+
				'<div class="popup-bot"></div>'+
			'</div>');
			popupc =  $(this).children('.popup');
			// THIS SHOULD BE DONE WITH AJAX !!!!!!!!!!!!!!!!!!!!!! Not its just static
			$('#id'+thisid).html('<div class="vnomersmall"><a href="#"><img src="img/smnomer.png" alt="" /></a><h5>№ 49 (802)</h5><ul><li><a href="#">Финансовый кризис: робкий оптимизм</a></li><li><a href="#">Депутаты ставят под угрозу кредит МВФ</a></li><li><a href="#">Рейтинг надежных банков: ТОП-20</a></li><li><a href="#">Фондовые индексы упали из-за проблем </a></li><li><a href="#">автопроизводителей и банков</a></li></ul></div>');
		}
		popupc.fadeIn('fast');
		$(this).addClass('hoveredtd');
	}, function(){
		$('.popup',this).fadeOut('fast');
		$(this).removeClass('hoveredtd');
	});
	
	//hiding popup on "blur" (click elsewhere)
	$(document).click(function(e){
		tar = $(e.target);
		if(!(tar.parents('.b-popup').length > 0) && !(tar.hasClass(".b-popup"))){$('.popup').fadeOut('fast');}
//		if(tar.hasClass("add")){tar.next().toggle();}
	});
*/	
	//hiding popup on "blur" (click elsewhere)
	$(document).click(function(e){
		tar = $(e.target);
		if(!(tar.parents('.b-popup').length > 0) && !(tar.hasClass(".b-popup"))){$('.popup').fadeOut('fast');}
//		if(tar.hasClass("add")){tar.next().toggle();}
	});
	Cufon.replace('.page h1 span,.aftepage h2');
	});
	/**
	* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
	* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
	* 
	* @param  f  onMouseOver function || An object with configuration options
	* @param  g  onMouseOut function  || Nothing (use configuration options object)
	* @author    Brian Cherne <brian@cherne.net>
	*/
	(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
	
	
	
	/*after all*/
	jQuery.fn.hint = function () {
	  return this.each(function (){
	    var t = jQuery(this);
	    var title = t.attr('title');
	    if (title) {
	      t.blur(function (){
	        if (t.val() == '') {
	          t.val(title);
	          t.addClass('blur');
	        }
	      });
	      t.focus(function (){
	        if (t.val() == title) {
	          t.val('');
	          t.removeClass('blur');
	        }
	      });
	      t.blur();
	    }
	  });
	}

	
	
	function _utf8_encode(string) {
		if (typeof string != "undefined"){
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		} else return "";
	}
 
	function _utf8_decode(utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		// fixed buy goshi
 		if (utftext){
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
 		}
		return string;
	}

	