function makeTabs(contId, start_pos){
    if (!start_pos)
        start_pos='first';
	var tabContainers = $('#'+contId+'_container > div');
	tabContainers.hide().filter(':'+start_pos).show();
	$('#'+contId+' span').click(function(){
		tabContainers.hide().filter('#'+contId+'_container #'+contId+'_'+this.id).show();
 	$('#'+contId+' span').removeClass('blue').filter('#'+this.id).addClass('blue');
 	return false;
	}).filter(':'+start_pos).click();
}


// banners init code
var bbn,cid,d,nv,na,j,z='',bv,c,fr,bv,n,sl,s,px;
bbn=0;cid=1;d=document;nv=navigator;
na=nv.appName;j="N";d.cookie="b=b";
bv=Math.round(parseFloat(nv.appVersion)*100);
if (d.cookie) c=1;n=(na.substring(0,2)=="Mi")?0:1;if (self!=top) {fr=1;} else {fr=0;}
sl="1.0";

function get_exec_data(absnum,div_rating,style_rating) {
	if(window.ActiveXObject) {
		hv = new ActiveXObject("Microsoft.XMLHTTP");
		hv.open('GET','/exec/views.php?art='+absnum+'&killcache='+vdate.getTime(),false);
		hv.send();
		if(hv.responseXML)
		{
			art_views = hv.responseXML.getElementsByTagName("views")[0].firstChild.nodeValue;
			art_comms = hv.responseXML.getElementsByTagName("totalcomments")[0].firstChild.nodeValue;
			imgcomms = new Array();
            ratingvalue=hv.responseXML.getElementsByTagName("ratingvalue")[0].firstChild.nodeValue;
            ratingcount=hv.responseXML.getElementsByTagName("ratingcount")[0].firstChild.nodeValue;
		}
	} else {
		hv = new XMLHttpRequest();
		hv.open('GET','/exec/views.php?art='+absnum+'&killcache='+vdate.getTime(),false);
		hv.send(null);
		if(hv.responseXML != '')
		{
			art_views = hv.responseXML.getElementsByTagName("views")[0].firstChild.nodeValue;
			art_comms = hv.responseXML.getElementsByTagName("totalcomments")[0].firstChild.nodeValue;
			imgcomms = new Array();
            ratingvalue=hv.responseXML.getElementsByTagName("ratingvalue")[0].firstChild.nodeValue;
            ratingcount=hv.responseXML.getElementsByTagName("ratingcount")[0].firstChild.nodeValue;
		      
        }
	}
    if (ratingcount>0 && ratingvalue>0)
        var rating =(ratingvalue/ratingcount).toFixed(2);
    else
        var rating=0;
    //Рейтинг статьи
    get_rating_data(absnum,div_rating,style_rating,ratingvalue,ratingcount);
    //$(document).ready(function(){$("#rating_description").html('<span class="grey">'+phrase_rating+': '+rating+' ('+phrase_votes+': '+ratingcount+')</span>')});
    $(document).ready(function(){
        $("#rating_description").html('<span class="grey">&nbsp;</span>')
        $("#rating_value").text(rating);
        $("#rating_votes").text(ratingcount);
        $("#total_comments").text(art_comms);
        if (art_comms==0)
            $("#total_comments").parent().hide();
        if (rating>0)
            $(".article_image_in_rating").show();    
            
        
    });
}

function swon(c,v)
{
	//
}

function  embedFlash(fileName, lib, tm, w, h)
{

/*
(c) Flash ActiveX IE fix by Ivan Turuk. http://www.newagelab.com
Put this function in external js file

fileName - path to flash file
lib - flash variables
tm - flash timestamp for anticaching
w - width
h - height
*/

var flob='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'" id="picture" align="middle">';
flob+='<param name="allowScriptAccess" value="sameDomain" />';
flob+='<param name="movie" value="'+fileName+'?' + tm + '" />';
flob+='<param name="quality" value="high" />';
flob+='<PARAM NAME=FlashVars VALUE="'+lib+'">';
flob+='<PARAM NAME=allowFullScreen VALUE="true" />';

flob+='<PARAM NAME=wmode VALUE="transparent">';
flob+='<param name="bgcolor" value="#eaeff4" />';
flob+='<embed src="'+fileName+'?' + tm + '" quality="high" wmode="transparent" allowFullScreen="true"  FlashVars="'+lib+'" bgcolor="#eaeff4" width="'+w+'" height="'+h+'" name="picture" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
flob+='</object>';
document.write(flob);
}

function submit_form (id){
	  document.getElementById(id).submit();
}


function testMailAndPopup(email, msg){
	var splitted = email.match("^(.+)@(.+)$");
	if(splitted == null) {
		alert(msg);
		return false;
	}
	if(splitted[1] != null) {
		var regexp_user=/^\"?[\w-_\.]*\"?$/;
		if(splitted[1].match(regexp_user) == null) {
			alert(msg);
			return false;
		}
	}
	if(splitted[2] != null) {
		var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
		if(splitted[2].match(regexp_domain) == null) {
			var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
			if(splitted[2].match(regexp_ip) == null) {
				alert(msg);
				return false;
			}
		}
		var w = 260;
		var h = 180;
		var winl = (screen.width - w) / 2;
		var wint = (screen.height - h) / 2;
		if (navigator.appName=="Netscape") {
			winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,' +
			'location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes';
		} else {
			winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,' +
			'location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no';
		}
		win = window.open( 'about:blank', 'popup', winprops);
		document.forms['sendform'].target = 'popup';
		return true;
	}
	alert(msg);
	return false;
}

// JavaScript Document
function timeSource(){
   x=new Date(timeNow().getUTCFullYear(),timeNow().getUTCMonth(),timeNow().getUTCDate(),timeNow().getUTCHours(),timeNow().getUTCMinutes(),timeNow().getUTCSeconds());
   x.setTime(x.getTime()+7200000);
   return x;
}
function timeNow(){
   return new Date();
}
function leadingZero(x){
   return (x>9)?x:'0'+x;
}
function displayTime(){
   document.getElementById('disp').innerHTML=eval(outputTime);
   setTimeout('displayTime()',1000);
}
var outputTime="leadingZero(timeSource().getHours()+1)+':'+leadingZero(timeSource().getMinutes())+':'+leadingZero(timeSource().getSeconds())";

function strt()
{
	displayTime();
}


function OpenPopup(popupurl,windowwidth,windowheight)
{
	var popWidth = 0;
	var popHeight= 0;
	popWidth = 870;

	if(windowwidth  == "") windowwidth = 670;
	if(windowheight == "") windowheight = 502;

	// add 0.01 to windowwidth as X40 ASP rounding slightly differs from Javascript rounding
	popHeight=Math.round((popWidth*windowheight)/(parseFloat(windowwidth)+0.01));

	if(windowwidth > popWidth || windowheight > popHeight){
		windowwidth  = popWidth;
		windowheight = popHeight;
	}	

	if(popEnlarge!=null && !popEnlarge.closed){ 
	popEnlarge.close(); 
	}
	var URL = popupurl;				
  var windowName = "EnlargedImage";
	
	{if(windowheight != "0") windowheight = parseInt(windowheight) + 80;}
  var features = "top=10,left=10,width=" + windowwidth + ",height=" + windowheight + ",menubar=no,location=no,resizable=no,scrollbars=no,toolbar=no,status=yes";

  popEnlarge = window.open (URL, windowName, features);
  popEnlarge.focus();
}

// Function to set a cookie.
//---------------------------------------------------------------------
function SetCookie( name, value )
{
    var argv    = SetCookie.arguments;
    var argc    = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path    = (argc > 3) ? argv[3] : null;
    var domain  = (argc > 4) ? argv[4] : null;
    var secure  = (argc > 5) ? argv[5] : false;

    document.cookie =
        name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
}
//---------------------------------------------------------------------
// Function to get a cookie.
//---------------------------------------------------------------------
function GetCookie (name)
{
    var arg  = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i    = 0;

    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
          return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
//---------------------------------------------------------------------
// Function to get a cookie.
//---------------------------------------------------------------------
function getCookieVal( offset )
{
    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

//
// ajax function
//
function svn_ajax(url,svn_handler,params) {
	if(window.ActiveXObject) {
		var handler = new ActiveXObject("Microsoft.XMLHTTP");
		handler.onreadystatechange = function() { if(handler.readyState == 4) svn_handler(handler,params); }
		handler.open('GET',url,true);
		handler.send();
	} else {
		var handler = new XMLHttpRequest();
		handler.onreadystatechange = function() { if(handler.readyState == 4) svn_handler(handler,params); }
		handler.open('GET',url,true);
		handler.send(null);
	}
}

function svn_sajax(url,svn_handler,params) {
	if(window.ActiveXObject) {
		var handler = new ActiveXObject("Microsoft.XMLHTTP");
		handler.open('GET',url,false);
		handler.send();
		svn_handler(handler,params);
	} else {
		var handler = new XMLHttpRequest();
		handler.open('GET',url,false);
		handler.send(null);
		svn_handler(handler,params);
	}
}

// синхронизация времени с сервером (как аякс, но получаем сразу значение js переменных)
function getatime()
{ 
	var vdate = new Date();
    var newurl = '/exec/ajax/time.php?nocache='+vdate.getTime();
	if (navigator.userAgent.toLowerCase().indexOf('safari/') != -1){
		$.ajax({
			async:false,
			url:newurl,
			cache:false,
			dataType:'script'
		});
		
	} else {
		var span = null;
		var span = document.createElement('SPAN');
		document.getElementById('jsdiv').appendChild(span);
		span.style.display = 'none';
		span.innerHTML = 'text <s'+'cript></' + 'script>';
		var s = span.getElementsByTagName("script")[0];
		s.language = "JavaScript";
		if (s.setAttribute) s.setAttribute('src', newurl); else s.src = newurl;
	}
}

function do_tabs(number)
{
	$('#tabs'+number+'  a').click(function(id){ 
		$('#tabs'+number+' > div').removeClass('selected');
		$(id.target).blur().parent().addClass('selected');  
		$('#tabs'+number+'_body > div').addClass('hidden');
		$('#tabs'+number+'_body > #'+$(id.target).parent().attr('id')+'_body').removeClass('hidden');
	});
}
$(document).ready(function(){
	  fanat=function(absnum, category){
  if (userid=='' || !userid)
    login_api.load();
  else
    fun_fanat(absnum, category);
  };
  
 fun_fanat = function(absnum, category){
            if (!category)
                category='empty';
            var t=new Date();
			$.get('/exec/ajax/addfunclub.php',{person:absnum, category:category, killcache:t.getTime()},function(xml){
                var num_article='#change_fanat'+absnum;
                if ($('res',xml).text()=='0')
				{
					if ($(num_article).val())
                        $(num_article).val("Больше не фанат");
                    if ($(num_article).text())
                        $(num_article).text("Больше не фанат");
                    alert(add_fanat_alert);
                }
                if ($('res',xml).text()=='1')
				{
				    if ($(num_article).val())
					   $(num_article).val("Стать фанатом");
                    if ($(num_article).text())
                        $(num_article).text("Стать фанатом");
                    alert(del_fanat_alert);
                }
			});
		};

});

//Функции для рейтинга статьи
	var stars = 5;
	var timer = null;
	var voted = false;
    var phrase = new Array();
	phrase['voted_str'] = 'Ваш голос учтен.';
    phrase['stars_1'] = 'Ужасно';
    phrase['stars_2'] = 'Плохо';
    phrase['stars_3'] = 'Нормально';
    phrase['stars_4'] = 'Хорошо';
    phrase['stars_5'] = 'Отлично';
    phrase['estimate'] = 'Оценить';
    var messages = new Array(phrase['stars_1'],phrase['stars_2'],phrase['stars_3'],phrase['stars_4'],phrase['stars_5']);

    function get_rating_data(absnum, block_id, style,ratingvalue,ratingcount)
    {   
        var vdate = new Date();
        var rate,html_string;
        if (parseInt(style)==1)
            style_str='';
        else
            style_str='_white';

        var is_voted = GetCookie('av_contest'+absnum);
       	$(document).ready(function(){
               if (ratingvalue>0 && ratingcount>0)
                    rate=ratingvalue/ratingcount;
                else
                    rate=0;
                html_string='<table class=\"audio_rate_big\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >';
                html_string+='<tr><td style=\"padding-top:0px\" valign=\"top\" id=\"first_cell\">';
                //html_string+='<div id=\"rating_vote\" ><strong>'+phrase['estimate']+':</strong>&nbsp;</div>';
                html_string+='</td></tr></table>';
                html_string+='<td align=\"left\" style=\"padding-top:3px\" width=\"140\" valign=\"top\">';
                for (i=0; i<stars; i++)
                {
 			        if (i==0)
                        html_string+='<div id=\'s_rating\' style=\"float:left;width:100px;\">';
         			var m = i+1;
                    if (rate>= m-0.5)
                        html_string+='<a href=\"javascript:void(0)\" onmouseover=\"starOn('+i+','+style+');\" onmouseout=\"starOff('+rate+','+style+');\" onclick=\"giveStar('+i+','+absnum+','+style+');return false;\"><img id=\"star_'+i+'\" src=\"/user/img/rating/pixel.gif\" alt=\"\" class=\"rating star_full'+style_str+'\" /></a>';
                    else 
                        html_string+='<a href=\"javascript:void(0)\" onmouseover=\"starOn('+i+','+style+');\" onmouseout=\"starOff('+rate+','+style+');\" onclick=\"giveStar('+i+','+absnum+','+style+');return false;\"><img id=\"star_'+i+'\" src=\"/user/img/rating/pixel.gif\" alt=\"\"  class=\"rating star_empty'+style_str+'\" /></a>';
                    
                    if (i==stars-1)
                         html_string+='</div><div align=\"left\" style=\"margin:4px 0 0 0px;\"><span id=\"mark_comment\" style=\"padding-right:20px;\"></span></div></td>';
                } 
                $('#'+block_id).html(html_string);
                if (is_voted)
                    is_voted_func(rate);
        });  
    }
	function is_voted_func(rate)
    {
		disableStar();
		document.getElementById('first_cell').width = '1';
	//	document.getElementById('rating_vote').style.display = 'none';
        //if (rate!=0)
            //document.getElementById('mark_comment').innerHTML = messages[parseInt(rate-1)];
    }
    
	function starOn(ind,style)
	{
        if (parseInt(style)==1)
            style_str='';
        else
            style_str='_white';
		timer = null;
		for(var i=0; i<stars; i++)
		{
			document.getElementById('star_'+i).className = 'rating star_empty'+style_str;
		}
		for(i=0; i<=ind; i++)
		{
			document.getElementById('star_'+i).className = 'rating star_full'+style_str;
		}
		//document.getElementById('mark_comment').innerHTML = messages[parseInt(ind)];
	}
    
	function starOff(rate,style)
	{
		timer = setTimeout("resetStars("+rate+", "+style+")",300);
	}
    
	function resetStars(rate,style)
	{
        if (parseInt(style)==1)
            style_str='';
        else
            style_str='_white';
        if(timer == null || voted == true) return false;
		timer = null;
		for(var i=0; i<stars; i++)
		{
			var m = i+1;
			if (rate>= m-0.5)
			{
				document.getElementById('star_'+i).className = 'rating star_full'+style_str;
			}  else
			{
				document.getElementById('star_'+i).className = 'rating star_empty'+style_str;
			}
		}
	//	document.getElementById('mark_comment').innerHTML = '';
	}
    
	function giveStar(ind, art,style)
	{
         if (parseInt(style)==1)
            style_str='';
        else
            style_str='_white';

        //Голоосовать за статью может только авторизированый пользователь
        comm.errors='';
        comm.check_name()
        if (comm.errors!='')
        {
            alert(comm.errors);
            return;
        } 
        voted = true;
		avote(art, ind+1);
	//	document.getElementById('mark_comment').innerHTML = phrase['voted_str'];
		for(i=0; i<stars; i++)
		{
			if(i<=ind)
			{
				document.getElementById('star_'+i).className = 'rating star_full'+style_str;
			} else
			{
				document.getElementById('star_'+i).className = 'rating star_empty'+style_str;
			}
		}
		disableStar();
	}
	function disableStar()
	{
		var div = document.getElementById('s_rating');
		var list = div.childNodes;
		var html = '';
		for (var i = 0; i < list.length; i++)
		{
			if(list[i].nodeName == 'A') html += list[i].innerHTML;
		}
		div.innerHTML = html;
	}

function avote(art,rating) {
        var x = mkhttp('/xml/avote/' + art + '/' + rating,null,avote_handler);
}

function mkhttp(url, data, handler) {
        var x;
        if(window.ActiveXObject) {
                x = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
                x = new XMLHttpRequest();
        }
        x.open(data?'POST':'GET', url, (typeof(handler) != 'undefined' && handler)?true:false);
        x.send(typeof(data) != 'undefined'? data : null);
        if(handler) {
                if(typeof(x.onload) != 'undefined') {
                        x.onload = function () { handler(x); }
                } else {
                        x.onreadystatechange = function() { if(x.readyState == 4) handler(x); }
                }
        }
        return x;
}

function avote_handler(x) {
        if(x.responseXML && (d = x.responseXML.documentElement) && d.tagName == 'ok') {
                var newrat = d.getAttribute('cnt');
				var newratv = d.getAttribute('val');
                var c = document.getElementById('avote_current');
                if (c) while(c.firstChild) c.removeChild(c.firstChild);
				var b = document.createElement('b');
                b.appendChild(document.createTextNode(newratv));
                if (c){
                c.appendChild(b);
                c.appendChild(document.createTextNode(' ('+newrat+' голосов)'));
                }               
                return true;
        } else {
                return false;
        }
}
 
