var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  try {
    xmlhttp = new XMLHttpRequest();
  } catch (e) {
    xmlhttp=false
  }
}

function myXMLHttpRequest() {
  var xmlhttplocal;
  try {
    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
  } catch (e) {
    try {
      xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
    } catch (E) {
      xmlhttplocal=false;
    }
  }
  if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
    try {
      var xmlhttplocal = new XMLHttpRequest();
    } catch (e) {
      var xmlhttplocal=false;
      alert('couldn\'t create xmlhttp object');
    }
  }
  return(xmlhttplocal);
}

function checkusername(form) {
  var name = escape(form.buLogin.value);
  var checkitvalue = document.getElementById('checkitvalue');
  url = 'xmlhttprequest?buLogin='+name;
  checkitxmlhttp = new myXMLHttpRequest();
  checkitxmlhttp.open("GET",url,true);
  checkitxmlhttp.onreadystatechange=function() {
    if (checkitxmlhttp.readyState==4) {
      responsestring = checkitxmlhttp.responseText;
      //      checkitvalue.innerHTML = "length="+responsestring.length+";";
      if (responsestring == '1') {
        checkitvalue.innerHTML = '<br><strong style="padding-left: 14px; color: #CC0000;">Имя "'+name+'" не соответствует критериям.</strong>';
        form.Submit.disabled = 'disabled';
      } else if (responsestring == '2') {
        checkitvalue.innerHTML = '<br><strong style="padding-left: 14px; color: #CC0000;">Имя "'+name+'" уже зарегистрировано.</strong>';
        form.Submit.disabled = 'disabled';
      } else if (responsestring == '3') {
        checkitvalue.innerHTML = '<br><strong style="padding-left: 14px; color: #009900;">Имя "'+name+'" свободно.</strong>';
        form.Submit.disabled = '';
      }else{
        checkitvalue.innerHTML += responsestring;
      }
    }
  }
  checkitxmlhttp.send(null);
  return false;
}

function enablebutton(button, button2, target) {
  var string = target.value;
  button2.disabled = false;
  if (string.length > 0) {
    button.disabled = false;
  } else {
    button.disabled = true;
  }
}

function voteit(newsid,userid,username,votesnum) {
  var checkitvalue = document.getElementById('numvotes'+newsid);
  var votelink = document.getElementById('votelink'+newsid);
  if(userid==0 || userid=='0'){
    userid=getCookie("buLogin2");
  }
  if(!(userid==0 || userid=='0')){
    votelink.innerHTML = "<blink>голосую</blink>";
    url = '/news/xmlhttprequest?voteid='+newsid+"&userid="+userid+"&username="+username+"&votesnum="+votesnum;
    checkitxmlhttp = new myXMLHttpRequest();
    checkitxmlhttp.open("GET",url,true);
    checkitxmlhttp.onreadystatechange=function() {
      if (checkitxmlhttp.readyState==4) {
        checkitvalue.innerHTML = checkitxmlhttp.responseText;
      }
    }
    checkitxmlhttp.send(null);
    votelink.innerHTML = "";
  }
  return false;
}

/* ----------------------------------------------- */

function unpopp(){
  var poppDiv = document.getElementById('poppDiv');
  if(poppDiv){
    poppDiv.parentNode.removeChild(poppDiv);
    poppDiv=false;
  }
}

function popp(id,text){
  var txtarea = document.getElementById('enclosure'+id);
  unpopp();
  txtarea.innerHTML='<div id="poppDiv" class="inline-warning"><div><table border=0><tr><td style="font-size: 14px;">Для того, чтобы '+text+',<br> необходимо <a href="/news/login" style="font-size: 14px;">войти</a> или <a href="/news/registration" style="font-size: 14px;">зарегистрироваться</a>.</td><td><a href="javascript:unpopp()"><img src="/close.gif" alt="Закрыть" title="Закрыть" border=0/></a></td></tr></table></div></div>'+txtarea.innerHTML;return(false);
}

function poppd(id){
  return(popp(id,'проголосовать за статью'));
}

/* ----------------------------------------------- */

function madr(a,d) {
  return a+String.fromCharCode(64)+d.replace(/#/g,'\056');
}

function mto(a,d) {
  var m = madr(a,d);
  document.write(String.fromCharCode(60,97,32,104)+'ref=\"mai'+String.fromCharCode(108,116,111,58)+m+'\" style="font-size:10px">'+m+'\074/a\076');
}

/*
function emoticon(text) {
  var txtarea = document.getElementById('messText');
  text = ' ' + text + ' ';
  if (txtarea.createTextRange && txtarea.caretPos) {
    var caretPos = txtarea.caretPos;
    caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
    txtarea.focus();
  } else {
    txtarea.value  += text;
    txtarea.focus();
  }
}
 */
function emoticon(text) {
  var txtarea = document.getElementById('messText');
  text = ' ' + text + ' ';
  if (txtarea.createTextRange && txtarea.caretPos) {
    var caretPos = txtarea.caretPos;
    caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
    txtarea.focus();
  } else {
    txtarea.value  += text;
    txtarea.focus();
  }
}


function GetCaretPosition(element) {
  var CaretPos = 0;
  if ( element.contentWindow.document.selection )
    alert(document.selection.createRange().text);
  else
    alert(element.getSelection().toString());

  return (CaretPos);
}


function showhide(id){
  var div=document.getElementById(id);
  if (div) {
    if (div.style.display != "block") {
      div.style.display = "block";
    }
    else {
      div.style.display = "none";
    }
  }
}

// request img counter

var reqImg=new Array();
function requestImg(u) {
  var i=new Image();
  i.src=u;
  return reqImg.push(i);
}

function setCookie(name, value) {
  var expire = new Date();
  var path="/";
  expire.setTime(expire.getTime() + 2*365*24*3600*1000); // +2 years
  document.cookie = name + "=" + escape(value)
  + "; expires=" + expire.toGMTString()
  + "; path="+path;
  return document.cookie;
}

function getCookie(cName) {
  var aCookie = document.cookie.split(/\s*;\s*/);
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (cName == aCrumb[0])
      return unescape(aCrumb[1]);
  }
  return null;
}

function initCookie(buLogin2){
  var aCookie = getCookie("buLogin");
  var aCookie2 = getCookie("buLogin2");
  if(aCookie==null && aCookie2==null){
    setCookie("buLogin2",buLogin2);
  }
  setCookie("catfilters","all");
  setCookie("useFilters",0);
  aCookie = getCookie("peoplefirst");
  if(aCookie==null){
    setCookie("peoplefirst",0);
  }
  aCookie = getCookie("showpeople");
  if(aCookie==null){
    setCookie("showpeople",1);
  }
  aCookie = getCookie("showrss");
  if(aCookie==null){
    setCookie("showrss",1);
  }
}

function reInitCookie(){
  setCookie("showpeople",1);
  setCookie("showrss",1);
}

function saveFilters(){
  var buff="";
  for(var i=10;i<100;i++){
    var element = document.getElementById("catid"+i);
    if(element!=null && element.checked){
      buff+=i+"-";
    }
  }
  //  buff=buff.substring(0,10);
  //  window.alert(buff);
  setCookie("catfilters",buff);
}

function catGlobalChange(catCounter,idList){
  var element = document.getElementById("catid"+catCounter);
  if(element!=null){
    var ids = idList.split("-");
    for (i in ids){
      var chkbox = document.getElementById("catid"+ids[i]);
      if(chkbox!=null){
        chkbox.checked=element.checked;
      }
    }
  }
}

function initCategories(catCounter,idList){
  var element = document.getElementById("catid"+catCounter);
  if(element!=null){
    element.checked=true;
    var ids = idList.split("-");
    for (i in ids){
      var chkbox = document.getElementById("catid"+ids[i]);
      if(chkbox!=null && !chkbox.checked){
        element.checked=false;
        break;
      }
    }
  }
}

function loadfulltext(id){
  $("#"+id).html("<img src=\"/i/loader.gif\" height=\"8\" border=0>");
  $("#"+id).load("/news/ty_ajax?mode=getfulltext&id="+id+"&link="+$("#"+id).parent().find(".name > a").attr("href"));
}
function loadshorttext(id){
  $("#"+id).load("/news/ty_ajax?mode=getshorttext&id="+id+"&link="+$("#"+id).parent().find(".name > a").attr("href"));
}
function loadphototext(id){
  $("#"+id).load("/news/ty_ajax?mode=getphototext&id="+id+"&link="+$("#"+id).parent().find(".name > a").attr("href"));
}

function myload(id,command){
  var link=$("#"+id).parent().find(".name > a").attr("href");
  var el = $("#"+id);
  reqJSON("/news/ty_ajax?mode="+command+"&link="+link+"&id="+id+"&anstype=json",
    function(json){
      json=eval(json);
      if(json.answer.text=="no such entry"){
        el.css("display","none");
      }else{
        el.html(json.answer.text);
      }
    },null);
}


function reload(id){
  var link=$("#"+id).find(".name > a").attr("href");
  var el = $("#"+id);
  //el.find(".text").html("Загружается ...");
  var data = el.html();
  var inText="";
  $("#"+id.substring(5)).html("<img src=\"/i/loader.gif\" height=\"8\" border=0>");
  $("#"+id.substring(5)).css("display","block");
  reqJSON("/news/ty_ajax?mode=reload"+"&link="+link+"&id="+id.substring(5),
    function(json){
      json=eval(json);
      if(json.answer.text=="no such entry"){
        el.css("display","none");
      }else{
        if(json.answer.img!=''){
          inText = "<div style=\"float:left;border=0;width: 50px;text-align:right;margin:0 5px 5px 0;\"><img src=\""+json.answer.img+"\" border=0 style=\"width: 50px;\"></div>";
        }
        inText+=data.replace("none","block");
        if(data.lastIndexOf("</DIV>")>=0){
          inText = inText.substring(0,inText.lastIndexOf("</DIV>"))+json.answer.text+"</div>";
        }else{
          inText = inText.substring(0,inText.lastIndexOf("</div>"))+json.answer.text+"</div>";
        }
        el.html(inText);
      }
    },null);
}

function fetchText(){
  $(".text").each(function() {
    //var tt = $(this).html();
    if($(this).html()==''||$(this).html()==" <br>"){
      reload("entry"+$(this).attr("id"));
    }
  });

}

function reqJSON(url, success, error) {
  var CallParams = {};
  CallParams.type = "GET";//params.Method || "POST";
  CallParams.url = url;
  CallParams.processData = true;
  CallParams.dataType = "json";
  if (success) {
    CallParams.success = success;
  }
  if (error) {
    CallParams.error = error;
  }
  $.ajax(CallParams);
}

function postJSON(url, params, success, error) {
  var CallParams = {};
  CallParams.type = "POST";//params.Method || "POST";
  CallParams.url = url;
  CallParams.processData = true;
  CallParams.data = params;
  CallParams.dataType = "json";
  CallParams.success = success;
  if (error) {
    CallParams.error = error;
  }
  $.ajax(CallParams);
}

function restrictBloger(name){
  $(".data").each(function() {
    if($(this).text().indexOf(name)>=0){
      $(this).parent().css("display","none");
    }
  });
  //$("#entry"+uid).css("display","none");
  var text = $("#noblogers").text();
  if(name.length>1){
    if(text!=''){
      text+=',';
    }
    text+=name;
    $("#noblogers").text(text);
    var post = '"mode":"saveblogers","list":"'+text+'"';
    postJSON("/news/ty_ajax",eval('({'+post+'})'),null,null);
  }
}

function FormClick (formID,divID) {
  var str = $("#"+formID).serialize();
  $("#"+divID).html('Загрузка:');
  $.post("/news/ty_ajax", str, function(data) {
    $("#"+divID).html(data);
  });
  return false;
}
