function showmenu(elmnt)
{
document.getElementById(elmnt).style.visibility="visible";
document.getElementById(elmnt).style.zIndex="20000";
}
function hidemenu(elmnt)
{
document.getElementById(elmnt).style.visibility="hidden";
document.getElementById(elmnt).style.zIndex="0";
}


function markmenu(elmnt)
{
document.getElementById(elmnt).className='inner_spam_menu_selected';
}

function unmarkmenu(elmnt)
{
document.getElementById(elmnt).className='inner_spam_menu';
}

function change_znak(newsid)
{
var znak=document.getElementById('ch_weight_znak_'+newsid);
var pic =document.getElementById('ch_weight_pic_'+newsid);
if(znak.value=='+')
{
znak.value='-';
pic.src='http://smi2.ru/img/vote_minus.gif';
}
else
{
znak.value='+';
pic.src='http://smi2.ru/img/vote_plus.gif';
}
}

add2forum = function(newsId) {
  jQuery.ajax({
    type: "GET",
    cache: false,
    url: '/process/',
    data: {
        action: '2forum',
            news_id: newsId,
            bind_id: jQuery('#2forum_' + newsId).val()
    },
    timeout: 15000,
    beforeSend: function(XMLHttpRequest){},
    complete: function(data, status){}
  });
  window.location.reload();
}

move_forum_news = function(newsId, bindId, return_url) {
  var action = jQuery('#2forum_' + newsId).val() == "clean" ? 'del_from_forum' : 'move_forum_news';
  jQuery.ajax({
    type: "GET",
    cache: false,
    url: '/process/',
    data: {
        action: action,
            news_id: newsId,
            bind_id: jQuery('#2forum_' + newsId).val(),
            old_bind_id: bindId,
            return_url: return_url
    },
    timeout: 15000,
    beforeSend: function(XMLHttpRequest){},
    complete: function(data, status){}
  });
  window.location.reload();
}


function spam(news_id, type){
  var digit = document.getElementById('lay_spam_digit_'+news_id);
  var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
              if ( !isNaN(parseInt(resp)) ) {
                digit.innerHTML = drown+'! ('+resp+')';
                document.getElementById('Strany_'+news_id).style.visibility='hidden';
//						changevisible(twiggleoff, twiggleon);
//        	    		alert('Ваш сигнал учтен. Спасибо!'+resp);
              } else {
                    alert('Error: ' + resp);
              }
            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };

  var request = '/process/?action=spam&news_id='+news_id+'&type='+type;
    //alert(request);
    req.open('GET', request, true);
    req.send(null);
    return false;
}

/**
 *
 * @access public
 * @return void
 **/
function vote(news_id, digit_id, twiggleoff, twiggleon, attitude){
  var old_positive, old_negative, old_votes, obobs;
  var digit = $('#'+digit_id);
  old_positive=$('#lay_pdigit_'+news_id).text();
  old_negative=$('#lay_ndigit_'+news_id).text();
  old_votes=$(digit).text();
  odobs=Array();

  /*раньше это была аякса
  var odobs = resp.split('|'); // odob | odob_positive | odob_negative
  odobs[0] = parseInt(odobs[0]);
  odobs[1] = parseInt(odobs[1]);
  odobs[2] = parseInt(odobs[2]);*/

  odobs[0] = parseInt(old_votes)+1;
  if(attitude=='p'){
      odobs[1] = parseInt(old_positive)+1;
  }else{
      odobs[1] = parseInt(old_positive);
  }
  if(attitude=='n'){
      odobs[2] = parseInt(old_negative)+1;
  }else{
      odobs[2] = parseInt(old_negative);
  }

  $(digit).text(odobs[0]);
  changevisible(twiggleoff, twiggleon);
  var divs = document.getElementById(twiggleon[0]).getElementsByTagName('div');

  if (!odobs[1] && !odobs[2]) {
    var pw = 34;
    var nw = 34;
  } else if (!odobs[1]) {
    var pw = 0;
    var nw = 70;
  } else if (!odobs[2]) {
    var pw = 70;
    var nw = 0;
  } else {
    var pw = Math.round(odobs[1]/(odobs[1]+odobs[2])*70)-2;
    var nw = 68-pw;
  }

  if (!pw) {
    divs[0].style.display = 'none';
  } else {
    divs[0].style.display = 'block';
    divs[0].style.width = pw+'px';
  }

  if (!nw) {
    divs[1].style.display = 'none';
  } else {
    divs[1].style.display = 'block';
    divs[1].style.width = nw+'px';
  }

  $.get('/process/?action=vote&news_id='+news_id+'&attitude='+attitude);
  return true;
}

function vote_mosaic(news_id, digit_id, twiggleoff, twiggleon){
  var digit = document.getElementById(digit_id);
     var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
              if ( !isNaN(parseInt(resp)) ) {
                digit.innerHTML = resp;
                changevisible(twiggleoff, twiggleon);
              } else {
                    alert('Error: ' + resp);
              }
            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };
     /*пкоазывать голоса*/
  var request = '/process/?action=vote&news_id='+news_id+'&golosov=1';
    req.open('GET', request, true);
    req.send(null);
}


function vote_simple(news_id, digit_id, golosovat_id){
  var digit = document.getElementById(digit_id);
  var gol = document.getElementById(golosovat_id);
     var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
              if ( !isNaN(parseInt(resp)) ) {
                digit.innerHTML = resp;
                gol.innerHTML = '';
              } else {
                    alert('Error: ' + resp);
              }
            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };
  var request = '/process/?action=vote&news_id='+news_id;
    req.open('GET', request, true);
    req.send(null);
}

function setclick ( news_id, partner_id ){
     var req = newHttpRequest();

  var request = '/process/?action=click&news_id='+news_id+'&partner_id='+partner_id;
  var url = window.location.href;
  var re = /\/\?seid\=(\w+)/;
  if (re.test(url)) {
      var val = re.exec(url);
      request = request + "&seid="+val[1];
    }
    req.open('GET', request, true);
    req.send(null);
}

function click ( news_id, partner_id ){
     var req = newHttpRequest();

  var request = '/process/?action=click&news_id='+news_id+'&partner_id='+partner_id;
    req.open('GET', request, true);
    req.send(null);
}

function click_site ( news_id, partner_id ){
     var req = newHttpRequest();

  var request = '/process/?action=click_site&news_id='+news_id+'&partner_id='+partner_id;
    req.open('GET', request, true);
    req.send(null);
}

function news_delete(news_id/*, elem_off*/){
  if (!confirm('Удалить новость?')) {
    return 0;
  }
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
           if (req.status == 200) {
              if ( resp=='OK' ) {
                window.location.href=window.location.href;
                //changevisible(new Array (elem_off), new Array());
              } else {
                    alert('Error: ' + resp);
              }
            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
      };
  var request = '/process/?action=delete&news_id='+news_id;
      req.open('GET', request, true);
      req.send(null);
}


function topic_delete(topic_id){
    if (!confirm(delete_topic+'?')) {
        return 0;
    }
    var url='/process/?action=deleteTopic&topic_id='+topic_id;
    $.get(url,function(){
        document.location.href="/topics/";
    });
}


function forum_delete(news_id, elem_off){
  if (!confirm(delete_forum_posting+'?')) {
    return 0;
  }
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
              if ( resp=='OK' ) {
                window.location.href=window.location.href;
              } else {
                    alert('Error: ' + resp);
              }
            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
      };
  var request = '/process/?action=delete&news_id='+news_id;
      req.open('GET', request, true);
      req.send(null);
}


function forum_subscribe(user_id, news_id,topic)
{
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200)
            {
              if(req.responseText=='-1'){
                alert('Чтобы подписаться на тему: \n' + topic+'\n необходимо быть зарегистрированным пользователем');
              } else {
                  if(req.responseText=='1')
                  {
                    document.getElementById('forum_subscribe').innerHTML = 'Отписаться';
                    alert('Вы подписаны на рассылку по этой теме: \n' + topic);
                  }
                  else
                  {
                    document.getElementById('forum_subscribe').innerHTML = 'Подписаться';
                    alert('Вы удалены из списка рассылки по теме: \n' + topic);
                  }
              }
             }
            else
            {
              alert('There was a problem with the request.');
            }
          } else {
          }
      };
    var request = '/process/?action=forum_subscribe&user_id='+user_id+'&news_id='+news_id;
      req.open('GET', request, true);
      req.send(null);
}


function is_addcomments(news_id, status)
{
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200)
            {
              if(status==1)
              {
              document.getElementById('is_addcomments_'+news_id).innerHTML = '<a class="middle21" onclick="is_addcomments('+news_id+', 0)" href="javascript:{}">Откл. вопросы</a>';
              }
              else
              {
              document.getElementById('is_addcomments_'+news_id).innerHTML = '<a class="middle21" onclick="is_addcomments('+news_id+', 1)" href="javascript:{}">Вкл. вопросы</a>';
              }
             }
            else
            {
                  alert('There was a problem with the request.');
            }
          } else {
          }
      };
  var request = '/process/?action=is_addcomments&news_id='+news_id+'&status='+status;
      //alert(request);
      req.open('GET', request, true);
      req.send(null);
}

function setanswer(news_id)
{
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
              if (req.status == 200)
            {
                if(resp=='ok') alert('Запрос успешно выполнен.');
                else if(resp=='no user') alert('Пользователь с таким ником не найден.');
                else alert(resp);
            };
                      }
                        }
    var answer_nick=document.getElementById('answer_nick').value;
    if(answer_nick=='') alert('Укажите ник пользователя');
  var request = '/process/?action=setanswer&news_id='+news_id+'&answer_nick='+answer_nick;
      req.open('GET', request, true);
      req.send(null);
}

function client_ban(client_id){
  if (!confirm('Забанить юзера?')) {
    return 0;
  }
      var req = newHttpRequest();
      req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) alert('Пользователь отключен');
            }

        };
  var request = '/process/?action=ban&client_id='+client_id;
      req.open('GET', request, true);
      req.send(null);
}


function client_penalty(client_id){

  if (!confirm('Поставить штраф?'))
  {
    return 0;
  }
  var value=document.getElementById('client_penalty_'+client_id).value;
    if (isNaN(value)==true || value<=0)
    {
    alert ('Введите число большее 0.');
    return 0;
    }

   //alert(value);
   var req = newHttpRequest();

   req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) alert('Штраф начислен');
            }

        };
  var request = '/process/?action=penalty&client_id='+client_id+'&value='+value;
        req.open('GET', request, true);
      req.send(null);
}


function changeweight(newsid){

  var value=document.getElementById('ch_weight_value_'+newsid).value;
  var znak=document.getElementById('ch_weight_znak_'+newsid).value;

  if (!confirm('Изменить рейтинг?'))
  {
    return false;
  }
    if (isNaN(value)==true || value<=0)
    {
    alert ('Введите число большее 0.');
    return false;
    }

   //alert(value);
   var req = newHttpRequest();

   req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) alert('Рейтинг изменен. Вес новости изменится через некоторое время.');
            }

        };
  var request = '/process/?action=changenewsweight&news_id='+newsid+'&value='+znak+value;
        req.open('GET', request, true);
      req.send(null);
}


function exportrss(news_id, to_status, type, elem){
    var url='/process/?action=exportrss&news_id='+news_id+'&to_status='+to_status+'&type='+type;
    $.get(url, function(data){
          var html=$(elem).html();
          if(data=='1'){
              alert('Новость добавлена в ленту');
              $(elem).html(html.replace('2', 'Из'));
              $(elem).attr("onClick", "exportrss("+news_id+", '0', '"+type+"', this)");
         }else if(data=='0'){
              alert('Новость удалена из ленты');
              $(elem).html(html.replace('Из', '2'));
              $(elem).attr("onClick", "exportrss("+news_id+", '1', '"+type+"', this)");
          }else{
              alert('Ошибка запроса. Обратитесь в службу поддержки.');
          }
     });
}

//не ждать ответа от аяксы
function comment_rating(act, comm_id){
    var golosov, ar_golosov, num_golosov, t1, t2, re, pref, pref1;
    golosov=$('#comment_rating_'+comm_id+' .current-rating').text();
    ar_golosov=golosov.toString().split(' ');
    num_golosov=parseInt(ar_golosov[0]);
    act=parseInt(act);
    num_golosov=eval(num_golosov.toString()+'+'+act.toString());
    num_golosov=parseInt(num_golosov);
	re = /[^-]{0,2}$/i;
	t1 = num_golosov.toString().match(re);
	t1=parseInt(t1);
	re = /[^-]{0,1}$/i;
	t2 = num_golosov.toString().match(re);
	t2=parseInt(t2);
    if (t1 > 5 && t1 <= 20){
        pref = tr_golosov;
    }else if(t2 == 1){
        pref = tr_golos;
    }else if(t2 >= 2 && t2 <= 4){
        pref = tr_golosa;
    }else{
        pref = tr_golosov;
    }

    if(num_golosov>0){
        pref1='+';
    }else{
        pref1='';
    }

    $('#comment_rating_'+comm_id+' .current-rating').text(pref1+num_golosov.toString()+' '+ pref);

    $('#comment_rating_'+comm_id+' img').each(function (i) {
        var src=$(this).attr('src');
        $(this).attr('src', src.replace('.gif', '_grey.gif'));
        $(this).css('cursor', 'default');
        $(this).bind("click", function(){
          return false;
        });
        $(this).parent().bind("click", function(){
          return false;
        });
    });
    $.getJSON('/process/?action=vote_comment&comm_id='+comm_id+'&act1='+act, function(data){
       if(data.status!='ok'){
          alert(data.errors);
       }
    });
    return true;
}

function refreshPage() {
    var url = document.location.href;
    var i = url.indexOf('#');
    if (i) {
    	url = url.substr(0,i);
    }
    document.location.href = url;
}

function comment_delete(comm_id)
{
if (!confirm('Удалить комментарий?'))
  {
    return 0;
  }

  $.get('/process/?action=delete_comment',{comm_id:comm_id},function(){
        alert('Комментарий удален');
        refreshPage();
  });

}

function changevisible(twiggleoff, twiggleon){
  for(var i in twiggleoff) {
    var el = document.getElementById(twiggleoff[i]);
    if(el){
        el.style.display='none';
    }
  }
  for(var i in twiggleon) {
    var el = document.getElementById(twiggleon[i]);
    if(el){
        el.style.display='';
    }
  }

}



/*function $( element ){
  return document.getElementById(element);
  if(mem){
    return mem;
  }
  alert( element );
}*/

function unpopp(){poppDiv=document.getElementById('poppDiv');if(poppDiv){poppDiv.parentNode.removeChild(poppDiv);poppDiv=false;}}

function pop(id,text){
  unpopp();
  document.getElementById('place'+id).innerHTML+='<div id="poppDiv" class="inline-warning"><div><p><a href="/register/">Присоединяйтесь</a> к SMI2, чтобы '+text+'. Если у вас уже есть аккаунт, авторизуйтесь.</p><a href="javascript:unpopp()"><img src="http://smi2.ru/img/close.gif" class="close" border=0 width="22" height="22" alt="Close" /></a></div></div>';
  return(false);
}

function pop_comm(id,text){
  unpopp();
  document.getElementById('place_comm'+id).innerHTML+='<div id="poppDiv" class="inline-warning"><div><p><a href="/register/">Присоединяйтесь</a> к SMI2, чтобы '+text+'. Если у вас уже есть аккаунт, авторизуйтесь.</p><a href="javascript:unpopp()"><img src="http://smi2.ru/img/close.gif" class="close" border=0 width="22" height="22" alt="Close" /></a></div></div>';
  return(false);
}

function newHttpRequest(){
  var http_request;
  if (window.XMLHttpRequest) {
    http_request = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
  }
//  http_request.overrideMimeType('text/xml');
  return http_request;
}

function reply_to_comments(client_nick, reply_to, level, news_id, s1,s2,s3, otv,skr, home_domain)
{
/*document.getElementById('caption_comment').innerHTML='<b>Ответить на комментарий '+client_nick+':</b>(<a class="middle19" href="javascript:{}" onClick="reset_reply_to_comments(); return false;">Oтменить</a>)';
document.getElementById('reply_to').value=reply_to;
document.getElementById('level').value=level;*/
document.getElementById('response_form_'+reply_to).style.display = "block";
document.getElementById('response_form_'+reply_to).innerHTML= document.getElementById('response_form_'+reply_to).innerHTML +
'<span style="margin-right:222px;">'+s1+'</span> '+s2+' <a href="http://" + home_domain + "/rules/">'+s3+'</a>.<br>'+
'<input type=hidden name=action value=save_comment>'+
'<textarea name="comment" id="comment_reply_'+reply_to+'"'+
'class=input-text cols=64 rows=5></textarea>'+
'<br><div align="center" style="margin:7px 0 7px 0;"><input type=submit value= "'+otv+'" class="input-text">'+
'&nbsp;<input type=submit value="'+skr+'" class="input-text"'+
'onClick="reset_reply_to_comments('+reply_to+');return false;"></div>'+
'<input type="hidden" name="action" value="save_comment">'+
'<input id="reply_to" name="reply_to" type="hidden" value="'+reply_to+'">'+
'<input id="news_id" name="news_id" type="hidden" value="'+news_id+'">'+
'<input id="level" name="level" type="hidden" value="'+level+'">';
$('#comment_reply_'+reply_to).smi2editor()
//loadFCKEditor('comment_reply_'+reply_to, '', 'smi2_panel', '640', '250');
document.getElementById('response_link_'+reply_to).style.display='none';
return false;
}
function reply_to_comments_partner(client_nick, reply_to, level, news_id, s1,otv,skr, home_domain)
{
/*document.getElementById('caption_comment').innerHTML='<b>Ответить на комментарий '+client_nick+':</b>(<a class="middle19" href="javascript:{}" onClick="reset_reply_to_comments(); return false;">Oтменить</a>)';
document.getElementById('reply_to').value=reply_to;
document.getElementById('level').value=level;*/
document.getElementById('response_form_'+reply_to).innerHTML=
'<span style="margin-right:222px;">'+s1+'</span> '+'<br>'+
'<input type=hidden name=action value=save_comment>'+
'<textarea name="comment" id="comment_reply_'+reply_to+'"'+
'class=input-text cols=64 rows=5></textarea>'+
'<br><div align="center" style="margin:7px 0 7px 0;"><input type=submit value= "'+otv+'" class="input-text">'+
'&nbsp;<input type=submit value="'+skr+'" class="input-text"'+
'onClick="reset_reply_to_comments('+reply_to+');return false;"></div>'+
'<input type="hidden" name="action" value="save_comment">'+
'<input id="reply_to" name="reply_to" type="hidden" value="'+reply_to+'">'+
'<input id="news_id" name="news_id" type="hidden" value="'+news_id+'">'+
'<input id="level" name="level" type="hidden" value="'+level+'">';
$('#comment_reply_'+reply_to).smi2editor()
//loadFCKEditor('comment_reply_'+reply_to, '', 'smi2_panel', '640', '250');
document.getElementById('response_link_'+reply_to).style.display='none';
return false;
}

function reset_reply_to_comments(reply_to)
{
/*document.getElementById('caption_comment').innerHTML='<b>Ваш комментарий:</b>';
document.getElementById('reply_to').value='0';
document.getElementById('level').value='0';*/
document.getElementById('response_form_'+reply_to).innerHTML='';
document.getElementById('response_link_'+reply_to).style.display='block';
return false;
}

function fsearchform()
{
if(document.getElementById("search").style.display=='none')
{
document.getElementById("search").style.display='';
document.getElementById("search1").style.display='';
document.getElementById("login1").style.display='none';
document.getElementById("login2").style.display='none';
document.getElementById("rasp_670").style.display='none';
}
else
{
document.getElementById("search").style.display='none';
document.getElementById("search1").style.display='none';
document.getElementById("login1").style.display='';
document.getElementById("login2").style.display='';
document.getElementById("rasp_670").style.display='';
}
return false;
}

function changeColor(num, hexcolor)
{
document.getElementById('hexcolor'+num).value=hexcolor;
var colors_example=document.getElementById('colors_example');
if(Number(num)==1)
{
colors_example.style.borderColor=hexcolor;
}
if(Number(num)==2)
{
colors_example.style.backgroundColor=hexcolor;
}
}

function setChecks(flag, block_name)
{
var form_checks=document.getElementById(block_name);

  for(var i=0; i<form_checks.elements.length; i++)
  {
    if (form_checks.elements[i].id.search('friendid')!=-1)
    {
      if (flag==1)
      {
          form_checks.elements[i].checked=true;
      }
      else
      {
          form_checks.elements[i].checked=false;
      }
    }
  }
}

function unsend_comments(user_id, news_id){
  var block = document.getElementById('unsend_comments');
     var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {

            if(resp=='ok')
            {
                    alert('Извещение по email о новых комментариях успешно отключено.');
                block.innerHTML = '';
            }
            else
            {
            alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
            }

            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };
  var request = '/process/?action=unsend_comments&news_id='+news_id+'&user_id='+user_id;
    //alert(request);
    req.open('GET', request, true);
    req.send(null);
}

function setNewsCommentsNotification(user_id, news_id, val){
    if(val){
        val=1;
    }else{
        val=0;
    }
    jQuery.get("/process/?action=setNewsCommentsNotification&news_id="+news_id+"&user_id="+user_id+"&val="+val);
}

function mess_spam(mess_id){
     var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
                //alert(resp);
            if(resp=='ok')
            {
                    alert('Ваш сигнал учтен. Спасибо!');
        window.location.href=window.location.href;
            }
            else
            {
            alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
            }

            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };
  var request = '/process/?action=mess_spam&mess_id='+mess_id;
    //alert(request);
    req.open('GET', request, true);
    req.send(null);
}


function comm_spam(comm_id)
{
     var req = newHttpRequest();
     req.onreadystatechange = function(){
        if (req.readyState == 4) {
         var resp = req.responseText;
            if (req.status == 200) {
                //alert(resp);
            if(resp=='ok')
            {
                    alert('Ваш сигнал учтен. Спасибо!');
            //window.location.href=window.location.href;
            }
            else
            {
            alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
            }

            } else {
                  alert('There was a problem with the request.');
            }
          } else {
          }
     };
  var request = '/process/?action=comm_spam&comm_id='+comm_id;
    //alert(request);
    req.open('GET', request, true);
    req.send(null);
}

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

// связи пользователя (4 функции)

function addToFriends(st, generator_id, user_name)
{
    var url = '/process/?action=setUserRelation&st=' + st + '&user_id=' + generator_id;
    var a = $('[class^=tofriends-][data-generator-id=' + generator_id + ']');

    if (a.length && st == 'default_user' && !confirm(sure_delete_friend1 + ' ' + user_name + ' ' + sure_delete_friend2 + '?')) {
        return false;
    }

    $.get(url, function(data) {
        if (!a.length) {
            return;
        }
        var c;
        if (st == 'default_user') {
            //a.data('st', 'friend').attr('data-st', 'friend').html(read_him);
            var t = $('.tofriends-'+generator_id).closest('div[id^="notification-"]'); 
            if (t.length>0) {
               t.slideUp(500);
            } else {             
                $(".is_friend-"+generator_id+", .remove_friend-"+generator_id).hide();
                $(".is_not_friend-"+generator_id).show();
                if ($(".count_is_read_by_" + generator_id).length>0) {
                    c = parseInt($(".count_is_read_by_" + generator_id).html().replace(/[^\d]/g, ''))-1;
                    $(".count_is_read_by_" + generator_id).html(number_format(c, 0, ',', ' '));
                }
            }
        } else if (st == 'friend') {
            //a.data('st', 'default_user').attr('data-st', 'default_user').html(not_read_him);
            $(".is_not_friend-"+generator_id).hide();
            $(".is_friend-"+generator_id).show();
            if ($(".count_is_read_by_" + generator_id).length>0) {
                c = parseInt($(".count_is_read_by_" + generator_id).html().replace(/[^\d]/g, ''))+1;
                $(".count_is_read_by_" + generator_id).html(number_format(c, 0, ',', ' '));       
            }
        }
      
    });        
    return false;
}

function addToNotOffer(st, user_id)
{
    var url = '/process/?action=setUserRelation&st='+st+'&user_id='+user_id;
    $.get(url, function(data){
        //alert('Пользователь исключен из списка предложений');
    });
    return false;
}

function addToBlack(st, user_id)
{
    var url = '/process/?action=setUserRelation&user_id='+user_id+'&st='+ st;
    var bl=$("#blacklist_"+user_id);
    $.get(url, function(data){
        if(data=='ok' && bl){
            if (st=='blacklist'){
                bl.html('<a href="javascript:{}" onClick="return addToBlack(\'default_user\', \''+user_id+'\');" title="'+activate_user+'.">'+activate_user+'</a>');
            }else if(st=='default_user'){
                bl.html('<a href="javascript:{}" onClick="return addToBlack(\'blacklist\', \''+user_id+'\');" title="'+deny_communicate+'.">'+ignore_user+'</a>');
            }
        }

    });
    return false;
}

function watchUserNews(st, user_id, li){
    var url='/process/?action=setUserRelation&user_id='+user_id+'&st='+st;
    $.get(url,function(data){
        if(data=='ok'){
            //если бы был только один на странице то можно было бы через this. А так через класс.
            if(li){
                var cl=$(li).attr('class');
                $('.watchnews-select-'+user_id+' li').css('background', 'none');
                $('.watchnews-select-'+user_id+' li.'+cl).css('background', 'url(\'/img/check_blue_12x12.png\') no-repeat left center');
            }else{
                alert('Статус пользователя изменен.');
            }
        }
    });
    return;
}

function setpartnerinsmi2(partner_id, to_status){
var req = newHttpRequest();
req.onreadystatechange = function()
{
    if (req.readyState == 4)
    {
        var resp = req.responseText;
        if (req.status == 200)
        {
            if(resp=='ok')
            {
                alert('Статус успешно изменен.')
            } else {
                alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
            }

        } else {
           alert('There was a problem with the request.');
        }
    }
};
  var request = '/process/?action=setpartnerinsmi2&partner_id='+partner_id+'&status='+to_status;
    req.open('GET', request, true);
    req.send(null);
}

function settemplateeditorinsmi2(partner_id){
var req = newHttpRequest();
  elem=document.getElementById('edit_selector_'+partner_id).value;
  to_status = elem;
//, this.options[this.selectedIndex].value

req.onreadystatechange = function()
{
    if (req.readyState == 4)
    {
      var resp = req.responseText;
         if (req.status == 200)
         {
          if(resp=='ok')
          {
        //var cb = document.getElementById('edit_template_'+partner_id);
        /*if (status==1){
          cb.value=1;
        }else if(status==0){
          cb.value=0;
        }*/
        elem=to_status;
        alert('Статус успешно изменен.')
            }
          else
          {
          alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
          }

         }
         else
         {
              alert('There was a problem with the request.');
         }
      }
};
  var request = '/process/?action=settemplateeditorinsmi2&partner_id='+partner_id+'&status='+to_status;
    req.open('GET', request, true);
    req.send(null);
}

function ed2main(partner_id, news_id){
var req = newHttpRequest();
var to_value=document.getElementById('editor_odob_'+news_id).value;
req.onreadystatechange = function()
{
    if (req.readyState == 4)
    {
      var resp = req.responseText;
         if (req.status == 200)
         {
              if(resp=='ok')
              {
                  alert('Статус успешно изменен.')
                  window.location.href=window.location.href;
                }
              else
              {
                  alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
              }
        }
         else
         {
              alert('There was a problem with the request.');
         }
      }
};
var request = '/process/?action=ed2main&partner_id='+partner_id+'&news_id='+news_id+'&to_value='+to_value;
req.open('GET', request, true);
req.send(null);
}


function floginform()
{
    if(document.getElementById("loginform").style.display=='none')
    {
        document.getElementById("loginform").style.display='block';
    }
    else
    {
        document.getElementById("loginform").style.display='none';
    }
    return false;
}

function toggle_block(block_id)
{
    if(document.getElementById(block_id).style.display=='none')
    {
        document.getElementById(block_id).style.display='block';
    }
    else
    {
        document.getElementById(block_id).style.display='none';
    }
    return false;
}

var markitupSettings = {
        onShiftEnter:   {keepDefault:false, replaceWith:'<br />\n'},
        onCtrlEnter:    {keepDefault:false, openWith:'\n<p>', closeWith:'</p>'},
        onTab:                  {keepDefault:false, replaceWith:'    '},
        resizeHandle: false,
        previewInWindow: 'width=600, height=400, resizable=yes, scrollbars=yes',
        markupSet:  [
                {name:'Bold', key:'B', openWith:'(!(<strong>|!|<b>)!)', closeWith:'(!(</strong>|!|</b>)!)' },
                {name:'Italic', key:'I', openWith:'(!(<em>|!|<i>)!)', closeWith:'(!(</em>|!|</i>)!)'  },
                {name:'Stroke through', key:'S', openWith:'<del>', closeWith:'</del>' },
                {name:'Picture', key:'P', replaceWith:'<img src="[![Source:!:http://]!]" alt="[![Alternative text]!]" />' },
                {name:'Link', key:'L', openWith:'<a href="[![Link:!:http://]!]"(!( title="[![Title]!]")!)>', closeWith:'</a>', placeHolder:'Your text to link...' },
                {name:'Clean', className:'clean', replaceWith:function(markitup) { return markitup.selection.replace(/<(.*?)>/g, "") } },
                {name:'Preview', className:'preview',  call:'preview'}
        ]
}

function toggleComment(id,link_id) {
    var l = link_id;
    jQuery.get("/process/?action=comm_toggle_vis&id="+id,null,function(){toggleLink(l)});
}

function enlistBattleComment(id) {

  var comment_id = id;
  var c = $('#'+comment_id);
  var level = parseInt(c.attr('level'));
  var tr = c.parent().parent();
  var descendants = new Array();

  do {
    descendants.push(tr);
    tr = tr.next();
  } while (tr.size() > 0 && parseInt(tr.attr('level')) > level);

  jQuery.get(
    "/process/?action=comm_enlist_battle&id="+id,
    null,
    function(){
      $.each(descendants, function(){
        var old = this;
        old.children().hide('slow')
      });
      //$('#'+comment_id).hide();
    }
  );
}

/*делает коммент на главной странице и добавляет к экспертам не убирая из общего потока*/
function setMainComment(id) {
  jQuery.get(
    "/process/?action=setMainComment&id="+id,
    null,
    function(){
      alert('Теперь мнение показывается на главной странице под анонсом новости и в комментариях экспертов');
      $('#set-maincomment-'+id).hide();
      $('#del-maincomment-'+id).show();
    }
  );
}


function banPreCommentBan(comm_id){
    $('#etalon_bancomment').attr('href', '/bancomment/?width=550&height=450&comm_id='+comm_id);
    $("#etalon_bancomment").trigger('click');
}

function delMainComment(id) {
  jQuery.get(
    "/process/?action=delMainComment&id="+id,
    null,
    function(){
      alert('Мнение больше не показывается в комментариях экспертов');
      $('#del-maincomment-'+id).hide();
      $('#set-maincomment-'+id).show();
    }
  );
}

function delExpertComment(id) {
  jQuery.get(
    "/process/?action=delExpertComment&id="+id,
    null,
    function(){
      alert('Мнение больше не показывается в комментариях экспертов');
    }
  );
}

function makeSpecialComment(id) {
  jQuery.get(
    "/process/?action=comm_make_special&id="+id,
    null,
    function(){
      alert('Теперь мнение показывается на главной странице под анонсом новости');
      $('#special-comment-trigger-make-'+id).hide();
      $('#special-comment-trigger-unmake-'+id).show();
    }
  );
}

function unmakeSpecialComment(id) {
  jQuery.get(
    "/process/?action=comm_unmake_special&id="+id,
    null,
    function(){
      alert('Мнение больше не показывается на главной странице под анонсом новости');
      $('#special-comment-trigger-unmake-'+id).hide();
      $('#special-comment-trigger-make-'+id).show();
    }
  );
}

function toggleLink(link_id) {
    var l1 = jQuery('#'+link_id+"_0");
    var l2 = jQuery('#'+link_id+"_1");
    if (l1.hasClass('hidden')) {
  l1.removeClass('hidden');
  l2.addClass('hidden');
    } else {
  l2.removeClass('hidden');
  l1.addClass('hidden');
    }
}

function binds_isonlyeditors(partner_id, bind_id, to_status){
  var req = newHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
          var resp = req.responseText;
             if (req.status == 200)
             {
                  if(resp=='ok')
                  {
                      alert('Статус успешно изменен.')
                    }
                  else
                  {
                      alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
                  }
            }
             else
             {
                  alert('There was a problem with the request.');
             }
          }
    };
    var request = '/process/?action=binds_isonlyeditors&partner_id='+partner_id+'&bind_id='+bind_id+'&to_status='+to_status;
    req.open('GET', request, true);
    req.send(null);
}

function isUrl(s) {
var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}

/**
 *
 * @access public
 * @return void
 * поставить редакторское одобрение для новости. действует пока только в партнерах
 * уникально для каждого партнера
 **/
function partner_edweight(newsid){
  var req = newHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
          var resp = req.responseText;
             if (req.status == 200)
             {
                  if(resp=='ok')
                  {
                      window.location.href=window.location.href;
                    }
                  else
                  {
                      alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
                  }
            }
             else
             {
                  alert('There was a problem with the request.');
             }
          }
    };

     var value=document.getElementById('partner_edweight_'+newsid).value;

    if (isNaN(value)==true || value<0)
    {
    alert ('Введите число большее 0.');
    return false;
    }


    var request = '/process/?action=partner_edweight&news_id='+newsid+'&value='+value;

    //alert(request);

    req.open('GET', request, true);
    req.send(null);
}


function add_partners_link(news_id){
var req = newHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            var resp = req.responseText;
            if (req.status == 200)
            {
                if(resp=='ok')
                {
                    alert('Новость добавлена в партнерки.');
                } else {
                    alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
                }

            } else {
                 alert('There was a problem with the request.');
            }
        }
    };

	var objSel = document.getElementById('newspartnersrel_sel_'+news_id);
    //document.getElementById('newspartnersrel_'+news_id).style.display='none';
    hidemenu('newspartnersrel_'+news_id);

	if(objSel.options[0].selected)
		partners = '0'
	else{
		partners = '';
		for (var i=0; i < objSel.options.length; i++)
			if (objSel.options[i].selected) partners+=objSel.options[i].value+',';
	}
	var request = '/process/?action=setpartnernewslink&news='+news_id+'&partners='+partners;
    req.open('GET', request, true);
    req.send(null);
}

/**
 *
 * @access public
 * @return void
 **/
function chngSrcWeight(src, weight){
    if(weight>1 || weight<=0 || isNaN(parseFloat(weight)))
    {
        alert('Введите число от 0.1 до 1');
        return;
    }
    var req = newHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            var resp = req.responseText;
            if (req.status == 200)
            {
                if(resp=='ok')
                {
                    alert('Вес источника успешно изменен.');
                } else {
                    alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
                }

            } else {
                 alert('There was a problem with the request.');
            }
        }
    };

	var request = '/process/?action=chngsrcweight&src='+src+'&weight='+weight;
    //alert(request);
    req.open('GET', request, true);
    req.send(null);
}

/**
 *
 * @access public
 * @return void
 **/
function loadFCKEditor(text_form, config_file, panel_name, width, height){
        if(config_file==''){
        config_file='fckconfig_07122009.js';
        }
        var sBasePath = '/lib/fckeditor262/';
        var oFCKeditor_comm = new FCKeditor(text_form) ;
        oFCKeditor_comm.BasePath	= sBasePath ;
        oFCKeditor_comm.Config['CustomConfigurationsPath'] = sBasePath + config_file;
        if(width!=''){
        oFCKeditor_comm.Width			= width;
        }
        if(height!=''){
        oFCKeditor_comm.Height			= height;
        }
        oFCKeditor_comm.ToolbarSet = panel_name;
        /*if(document.getElementById(text_form)){
            document.getElementById(text_form).style.display="none";
        }else if(document.getElementsByName(text_form)){
            var array_elem=document.getElementsByName(text_form);
            if(array_elem[0]){
                array_elem[0].style.display='none';
            }
        }
        oFCKeditor_comm.Create();*/
        oFCKeditor_comm.ReplaceTextarea() ;
}

function addFriendsForm(friendform, invite_count){
	var form = $('#'+friendform);
	form.append('E-mail друга:&nbsp;&nbsp;&nbsp;&nbsp;'+
	'<input name="email['+invite_count+']" type="text" class="input-text" value="" size="60"><br>');
}

function setPossiblePublicCreative(value, uid, is_refresh){
  var req = newHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
          var resp = req.responseText;
             if (req.status == 200)
             {
                  if(resp=='ok')
                  {
                      if(is_refresh==1){
                          window.location.href=window.location.href;
                      }else{
                      alert("Статус успешно изменен.");
                      }
                    }
                  else
                  {
                      alert('Ошибка базы данных. Попробуйте выполнить действие позже.')
                  }
            }
             else
             {
                  alert('There was a problem with the request.');
             }
          }
    };


    var request = '/process/?action=set_possible_public_creative&user_id='+uid+'&value='+value;

    //alert(request);

    req.open('GET', request, true);
    req.send(null);
}

function onOdobSuccess(data){
    $("#odob").html( data );
}
function onSpamSuccess(data){
    $("#spam").html( data );
}


function show_users( type, news_id) {
    $("#"+type).html(loading);
//    alert( type+news_id );
    $.get("/process/",
        {
            action: 'getUserList',
            type: type,
            news_id:  news_id
        },
        type=='odob'?onOdobSuccess:onSpamSuccess);

    return false;
}

function setBookmark(id, status) {
	$.get("/process/?action=setBookmark",{news_id:id,status:status},function(resp){
        if 	(resp=='OK') {
            if(status=='set'){
                $('#setBookmark'+id).hide();
                $('#delBookmark'+id).show();
            }else{
                $('#setBookmark'+id).show();
                $('#delBookmark'+id).hide();
            }
		} else {
			alert(resp);
		}
	})
}

/*вызывать по MouseDown иначе в IE глюк*/
var simpletips=new Array;
function popupUserMenu(uid, elem, styleclass, ip){
    //ip может не быть передан
    ip=ip || '';
    if(simpletips[elem]==undefined){
        jQuery(elem).simpletip({persistent: true,
            content: loading+'...',
            position: 'bottom',
            baseClass: styleclass,
            onBeforeShow: function(){
                 var data = jQuery.ajax({
                  url: "/process/?action=popupUserMenu&uid="+uid+"&ip="+ip,
                  async: false
                 }).responseText;

                 var api=jQuery(elem).simpletip();
                 api.update(data);

                 /*jQuery.get("/process/?action=popupUserMenu&uid="+uid, function(data){})*/

                 //this.load("/process/?action=popupUserMenu&uid="+uid);
            }
            });
        simpletips[elem]=1;
        //var api=jQuery(elem).simpletip();
        //api.show();
    }
}

function popupSourceMenu(source, elem, styleclass){
    if(simpletips[elem]==undefined){
        jQuery(elem).simpletip({persistent: true,
            content: loading+'...',
            position: 'bottom',
            baseClass: styleclass,
            onBeforeShow: function(){
                 var data = jQuery.ajax({
                  url: "/process/?action=popupSourceMenu&source="+source,
                  async: false
                 }).responseText;
                 var api=jQuery(elem).simpletip();
                 api.update(data);

            }
            });
        simpletips[elem]=1;
    }
}

function banSource(source, tostatus){
    var data = jQuery.ajax({
    url: "/process/?action=banSource&source="+source+"&tostatus="+tostatus,
    async: false
    }).responseText;
    if(data=='ok'){
        alert('Статус успешно изменен');
    }else{
        alert('Ошибка при выполнении запроса');
    }
}

function addNewsToAdsCmp(val){
    $.get('/traffic/?traff_action=traffic_add&news_id='+val, function(data){
       if(data=='ok'){
           alert('Новость добавлена в рекламные компании. Перейдите на страницу рекламных компаний для завершения настроек.');
       }else{
           alert(data);
       }
       //document.location.reload();
       return;
     });
}

//show arch links block
function salb(val){
    $('#arch_links_main').hide();
    $('.alns').hide();
    $('#aln'+val).show();
}

/*user wall*/
function sendWallMessage(){
    if(!$('#block_user_wall_send_mess_text').val()){
        alert('Введите текст сообщения');
        return;
    }
    $('#block_user_wall_send_mess').hide();
    $('#block_user_wall_send_mess_process').show();
    var form_data = $('#block_user_wall_send_mess_form').serialize();
    $.ajax({
        type: "POST",
        url: "/wall/",
        async: false,
        data: form_data,
        success: function(msg){
            if(msg){
                alert(msg);
            }else{
                $('#block_user_wall_send_mess_text').val('');
            }
            $('#block_user_wall_send_mess').show();
            $('#block_user_wall_send_mess_process').hide();
            return false;
        }
    });
    return false;

}

function sendCompactWallMessage(){
    if(!$('#compact_block_user_wall_send_mess_text').val()){
        alert('Введите текст сообщения');
        return;
    }
    $('#compact_block_user_wall_send_mess').hide();
    $('#compact_block_user_wall_send_mess_process').show();
    var form_data = $('#compact_block_user_wall_send_mess_form').serialize();
    $.ajax({
        type: "POST",
        url: "/wall/",
        async: false,
        data: form_data,
        success: function(msg){
            if(msg){
                alert(msg);
            }else{
                $('#block_user_wall_send_mess_text').val('');
            }
            $('#compact_block_user_wall_send_mess').show();
            $('#compact_block_user_wall_send_mess_process').hide();
            alert('Сообщение отправлено');
            return false;
        }
    });
    return false;
}

function editWallMessage(){
    var form_data = $('#edit_wall_mess_form').serialize();
    $.ajax({
        type: "POST",
        url: "/wall/",
        async: false,
        data: form_data,
        success: function(msg){
            if(msg){
                alert(msg);
            }else{
                tb_remove();
                refreshPage();
            }
        }
    });
    return false;
}

function delWallMessage(mess_id){
    if (!confirm('Удалить сообщение?')){return 0;}
    var url="/wall/?wall_action=delWallMessage&id="+mess_id;
    $.get(url, function(data){
        if(data){
            alert(data);
        }else{
            refreshPage();
        }
    });
    return false;
}

function delGalleryItem(image_id, redirect_url){
    if (!confirm('Удалить фотографию?')) {
        return 0;
    }

    var url='/galleries/?action=gallery_delete&image_id='+image_id;
    $.get(url,function(){
        if(redirect_url){
            window.location.href = redirect_url;
        }else{
            refreshPage();
        }
    });
}

if (typeof ajaxNewsLoader == 'undefined') {
    var ajaxNewsLoader = {};
}

if (typeof ajaxNewsPager == 'undefined') {
    var ajaxNewsPager = {};
}

ajaxNewsPager.init= function(selector, load_next, loading_next, no_more, items_in_page){
    ajaxNewsPager.selector = selector;
    ajaxNewsPager.load_next = load_next;
    ajaxNewsPager.loading_next = loading_next;
    ajaxNewsPager.no_more = no_more;
    ajaxNewsPager.items_in_page = items_in_page;
    return true;
}

ajaxNewsPager.showLoadingNext = function(){
    $(ajaxNewsPager.selector).html('<img src="http://smi2.ru/img/ad-campaigns/loading.gif" alt=""/ style="margin-right:7px;">' + ajaxNewsPager.loading_next + '...');
    return true;
}

ajaxNewsPager.showNoMore = function(){
    $(ajaxNewsPager.selector).text(ajaxNewsPager.no_more);
    return true;
}

ajaxNewsPager.showLoadNext = function(){
    $(ajaxNewsPager.selector).html('<a href="#load-more" onclick="ajaxNewsPager.loadNext(); return false;">' + ajaxNewsPager.load_next + '...</a>');
    return true;
}

ajaxNewsPager.loadNext = function(){
    ajaxNewsLoader.reqcount = parseInt(ajaxNewsLoader.reqcount) + parseInt(ajaxNewsPager.items_in_page);
    ajaxNewsLoader.loadReqursive();
    return true;
}

ajaxNewsLoader.init = function(newslist, reqcount, url){
    var ajaxnewsloader_id = 'ajaxNewsLoader'
    ajaxNewsLoader.period = 2;
    ajaxNewsLoader.reqcount = reqcount;
    ajaxNewsLoader.news_id = 0;
    ajaxNewsLoader.maxperiod = 5000;
    ajaxNewsLoader.newslist = newslist;
    ajaxNewsLoader.url = url?url:'';
    ajaxNewsLoader.load();
    return true;
}

ajaxNewsLoader.load = function(){
    ajaxNewsLoader.loadReqursive();
    return true;
}

ajaxNewsLoader.loadReqursive = function(){
    //id последней загруженной новости
    ajaxNewsLoader.news_id = ajaxNewsLoader.getLastNewsId(ajaxNewsLoader.newslist);
    //новостей на странице есть
    var news_count = $(ajaxNewsLoader.newslist).find('.nl-item').length;
    //сколько нужно догрузить
    var news_request = ajaxNewsLoader.reqcount - news_count;

    if(news_request<1){
        //все загружено и возможно есть еще
        ajaxNewsPager.showLoadNext();
        return true;
    }

    //больше ничего нет
    if(ajaxNewsLoader.period>ajaxNewsLoader.maxperiod){
        ajaxNewsPager.showNoMore();
        return true;
    }

    //показать процесс загурзки
    ajaxNewsPager.showLoadingNext();
    var url = '';
    if(ajaxNewsLoader.url){
        url = ajaxNewsLoader.url;
    }else{
        url = document.location.href;
    }
    url = url.split('#');
    url=url[0];
    if(url.indexOf('?')==-1){
        url=url+'?'
    }
    url = url+"&newsloader=1&ajaxnewsloader_period="+ajaxNewsLoader.period+"&ajaxnewsloader_news_id="+ajaxNewsLoader.news_id;
    $.ajax({
        type: "POST",
        dataType:"json",
        url: url,
        async: true,
        data: '',
        success: function(rdata){
            var html = rdata.html;
            var em_items = $(document.createElement('div')).html(html).find('.nl-item');
            $(em_items).each(function (i) {
                news_id = ajaxNewsLoader.getNewsId(this);
                if(news_request>0 && $(ajaxNewsLoader.newslist).find('#lay_show_'+news_id).length==0){
                    $(this).appendTo($(ajaxNewsLoader.newslist)).show('slow');
                    //нарисовать кружочек
                    voteobj.drawCircle($(this).find('.nlvb-num'), parseInt($(this).find('.num').html(), 10));
                    news_request--;
                }
            });
            ajaxNewsLoader.period=parseInt(ajaxNewsLoader.period)*2;
            ajaxNewsLoader.loadReqursive();
            return true;
        }
    });
}

ajaxNewsLoader.getLastNewsId = function(newslist){
    var news_item = $(newslist).find('.nl-item:last');
    var last_news_id = false;
    if($(news_item).length>0){
        var rs = $(news_item).attr('id').toString().match(/lay_show_([0-9]+)/i);
        last_news_id = parseInt(rs[1]);
    }
    return last_news_id;
}

ajaxNewsLoader.getNewsId = function(item){
    var rs = $(item).attr('id').toString().match(/lay_show_([0-9]+)/i);
    return parseInt(rs[1]);
}

initAjaxPager = function(selector, show_more, load_next, no_more) {
    $('#pager').addClass('ajax').html('<a href="#load-more" onclick="loadListPage(\'' + selector + '\', \'' + load_next + '\', \'' + no_more + '\', \'' + show_more + '\'); return false">' + show_more + '...</a>');
}

loadListPage = function(selector, load_next, no_more, show_more) {
  var lastPage = $('.list-page:last');
  var count = lastPage.find(selector).size();
  listPageOffset = parseInt(count) + parseInt(listPageOffset);
  lastPage.after('<div class="list-page"></div>');

  $('#pager').html('<i><img src="http://smi2.ru/img/ad-campaigns/loading.gif" width="16" /><span>' + load_next + '...</span></i>');
  var cd = false;
  var baseURL = '';
  if (cd = getQueryVariable('calendar_date')) {
    baseURL = './?calendar_date=' + cd + '&';
  } else if (cd = getQueryVariable('tag')) {
    baseURL = './?tag=' + cd + '&';
  } else if (cd = getQueryVariable('s_tag')) {
    baseURL = './?s_tag=' + cd + '&';
  } else if (cd = getQueryVariable('source')) {
    baseURL = './?source=' + cd + '&';
  } else if (cd = getQueryVariable('a')) {
        if(cd=='viewCommunity'){
            id= getQueryVariable('id')
            baseURL = './?a=viewCommunity&id=' + id + '&';
        }
  } else {
    baseURL = './?';
  }
  $('.list-page:last').load(baseURL + 'of=' + listPageOffset + '&naked=1', function() {
    if ($('.list-page:last').find(selector).length == 0) {
        $('#pager').html('<i>' + no_more + '.</i>');
    } else {
        $('.list-page:last').find('.nlvb-num').each(function() {
            var num = parseInt($(this).find('.num').html(), 10);
            voteobj.drawCircle(this, num);
        })
        $('#pager').html('<a href="#load-more" onclick="loadListPage(\'' + selector + '\', \'' + load_next + '\', \'' + no_more + '\', \'' + show_more +'\'); return false">' + show_more + '...</a>');
    }

  });
}

getQueryVariable = function(v) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i=0; i<vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == v) {
      return pair[1];
    }
  }
  return false;
}

function sendCommentForm(em) {
    var data= $(em).closest('form').serialize();
    $.ajax({
        type: "POST",
        dataType:"json",
        url: "/process/",
        async: false,
        data: data,
        success: function(rdata){
            //refreshPage();
            if(rdata.result==1){
                //редактировал или новый добавил
                $('form[id^=comment-form]').hide();
                $('.comm-add').show();
                var comm_id = rdata.comm_id;
                var comm_text = rdata.text;
                //редактировал
                var em = $('.comments-ordinary ').find('#'+comm_id);
                var parser = new Parse.Simple.Creole({forIE: document.all})
                if($(em).length > 0){
                    var ca = $(em).find('.comment-text .comment-author');
                    $(em).find('.comment-text').html('').append(ca).append(comm_text);
                //ставил новый
                }else{
                    tpl_comm = tmpl('comment_body_v3');
                    var html = tpl_comm(rdata);
                    if(rdata.reply_to){
                        length = $('#'+rdata.reply_to).nextAll('.comment-item').length;
                        if(length==0){
                            //первый коммент далее
                            $('.comments-ordinary').append(html);
                        }else{
                            //нашел коммент уровня выше
                            var is_add=false;
                            $('#'+rdata.reply_to).nextAll('.comment-item').each(function (i) {
                                if(parseInt($(this).find('input[name=level]').val())<parseInt(rdata.comm_level) && !is_add){
                                    is_add=true;
                                    $(this).before(html);
                                }
                            });
                            //не нашел коммент уровня выше
                            if(!is_add){
                                $('.comments-ordinary').append(html);
                            }
                        }
                    }else{
                        if($('.comments-ordinary .comment-item').length>0){
                            $('.comments-ordinary .comment-item:last').after(html);
                        }else{
                            $('.comments-ordinary').append(html);
                        }

                    }
                    if(!rdata.is_reply){
                        $('.reply'+comm_id).parent().remove();
                    }
                    anchorScroller(rdata.comm_id, 20);
                }
                var counthtml = $('#comments_count').html();
                var temp = counthtml.match(/(\d{1,5})/);
                var count = parseInt(temp[0])+1;
                $('#comments_count').html(count);
                if (count>5 && $("#additional_block").css('display', 'none')) {
                    $("#additional_block").show();
                }
            }else{
                alert('Ошибка при сохранении комментария.');
            }
        }
    });
}

function showReplyForm(reply_to) {
    reply_to=parseInt(reply_to);
    var em = $('#comment-form1').detach();
    $(em).find('input[name=comm_id]').val(0);
    $(em).find('input[name=reply_to]').val(reply_to);
    $(em).find('input[name=level]').val(parseInt($(em).find('input[name=level]').val())+1);
    $(em).find('.smi2editortext').val('');
    $(em).insertAfter('#'+reply_to).show();
    $('#comments .comm-add').show();
}

function showEditForm(comm_id) {
    comm_id=parseInt(comm_id);
    var parser = new Parse.Simple.Creole({forIE: document.all})
    var comment_text = $('#'+comm_id).find('.comment-text').clone();
    $(comment_text).find('.comment-author').remove();
    var text= $(comment_text).html();
    var em = $('#comment-form1').detach();
    $(em).find('input[name=comm_id]').val(comm_id);
    $(em).find('input[name=reply_to]').val(0);
    $(em).find('input[name=level]').val(0);
    $(em).find('.smi2editortext').val(parser.importHTML(text));
    $(em).insertAfter('#'+comm_id).show();
    $('#comments .comm-add').show();
    $('.actions').hide();
}

function showCommentForm(num) {
    var em = $('#comment-form'+num).detach();
    $(em).find('input[name=comm_id]').val(0);
    $(em).find('input[name=reply_to]').val(0);
    $(em).find('input[name=level]').val(0);
    $(em).find('.smi2editortext').val('');
    $(em).appendTo('#comments div#comment-form-div'+num).show();
    $('#comments #comm-add'+num).hide();
}

function v3commvote(comm_id, attitude, em) {
    var parent=$(em).closest('.nl-vote_block');
    if ($(em).hasClass('vote_plus_icon_na') || $(em).hasClass('vote_minus_icon_na')) {
        return false;
    }
    if (attitude == 'p') {
        $(em).addClass('vote_plus_icon_na');
        $(parent).find('.vote_minus_icon').removeClass('vote_minus_icon_na');
    } else {
        $(em).addClass('vote_minus_icon_na');
        $(parent).find('.vote_plus_icon').removeClass('vote_plus_icon_na');
    }
    $.getJSON('/process/?action=vote_comment&id=' + comm_id + '&attitude=' + attitude, function(data) {
        if(data.status=='ok'){
            $(parent).find('.num_rating').text(data.rating);
        }
    });
    return true;
}

function anchorScroller(address, duration) {
if (this.criticalSection) {
return false;
}

for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name == address) {
el = document.anchors[i];
break;
}
}
if (el === 0)
return true;

this.stopX = 0;
this.stopY = 0;
do {
this.stopX += el.offsetLeft;
this.stopY += el.offsetTop;
} while (el = el.offsetParent);

this.startX = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
this.startY = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;

this. stopX = this.stopX - this.startX;
this.stopY = this.stopY - this.startY;

if ( (this.stopX == 0) && (this.stopY == 0) )
return false;

this.criticalSection = true;
if (typeof duration == 'undefined')
this.duration = 500;
else
this.duration = duration;

var date = new Date();
this.start = date.getTime();
this.timer = setInterval(function () {
var date = new Date();
var X = (date.getTime() - this.start) / this.duration;
if (X > 1)
X = 1;
var Y = ((-Math.cos(X*Math.PI)/2) + 0.5);

cX = Math.round(this.startX + this.stopX*Y);
cY = Math.round(this.startY + this.stopY*Y);

document.documentElement.scrollLeft = cX;
document.documentElement.scrollTop = cY;
document.body.scrollLeft = cX;
document.body.scrollTop = cY;

if (X == 1) {
clearInterval( this.timer);
this.criticalSection = false;
}
}, 10);
return false;
}

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name)
		{
			return unescape(y);
		}
	}
	return null;
}

function setCookie(c_name,value,exdays, path)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value + "; path=/";
}

