function MyGetElementByID(e) {
   if(document.getElementById) { e=document.getElementById(e); }
   else if(document.all) { e=document.all[e]; }
   else { e=null; }
   return e;
}

function Encode(str) {
   var trans = [];
   for (var i = 0x410; i <= 0x44F; i++) {
      trans[i] = i - 0x350;
   }
   trans[0x401] = 0xA8;
   trans[0x451] = 0xB8;
   trans[0x2116] = 0xB9;
 
   var encoded_str = '';
   for (var i = 0; i < str.length; i++) {
      var n = str.charCodeAt(i);
      if (n > 255) { n = trans[n]; }
      if (!n) { n=63; }
      hexcode = n.toString(16);
      encoded_str += ('%' + hexcode);
   }
   return encoded_str.toUpperCase();
}

function EvalScript(AText) {
   var xBlocks=AText.split('%SCRIPT');
   var yBlocks=xBlocks[1].split('%ENDSCRIPT');
   var xLines=yBlocks[0].split('\n');
   for (var xi=0; xi<xLines.length; xi++) {
      if (xLines[xi]!='') { eval(xLines[xi]); }
   }
   return xBlocks[0] + yBlocks[1];
   //return AText;
}

function sndForm(AAction, AParams, ACtrlID, AFrm) {
   if (AFrm!=null) {
      for(var xi=0; xi<AFrm.elements.length; xi++) { 
         if ((AFrm.elements[xi].type=='hidden') && (AFrm.elements[xi].name.indexOf('from')<0)) {
            AParams=AParams + AFrm.elements[xi].name + '=' + AFrm.elements[xi].value + '&';
         }
      }
      sndReq(AAction, AParams, ACtrlID);
   } else {
      alert('Ошибка: форма не найдена');
   }
}

function createRequestObject() {
   var ro;
   var browser = navigator.appName;
   if(browser == 'Microsoft Internet Explorer'){
      ro = new ActiveXObject('Microsoft.XMLHTTP');
   } else {
      ro = new XMLHttpRequest();
   }
   return ro;
}
 
var http = createRequestObject();
var httpBusy=0;
var httpRq=0;
var httpChain=new Array();
var httpTimer=null;
var httpInterval=500;
var httpStopped=0;
var httpStartTime=0;
var httpEndTime=0;
var httpMidTime=1000;
var httpErrState=0;
var httpParamA="";
var httpParamB="";
var httpIsCritical=0;

function sndReq(action, params, ctrlid) {
   http.open('get', action+'.php?ctrlid='+ctrlid+'&'+params);
   http.onreadystatechange = handleResponse;
   http.send(null);
   return false;
}

function sndManage() {
   if (httpTimer!=null) { clearTimeout(httpTimer); httpTimer=null; }
   if (httpChain.length>0) {
      if (httpBusy!=0) {
         var xhttpEndTime=Date.parse(Date());
         if ((xhttpEndTime - httpStartTime)>=25000) {
            http.abort();
            httpBusy=0;
            httpChain.splice(0, httpChain.length);
            if (comm) { this.window.location.reload(); }
            if (httpErrState==0) {
               UpdateChat("0%LASTID!r_0!<span style=\"color: #E00000\">Превышен интервал ожидания ответа от сервера. Все команды отменены.</span><br />");
               httpErrState=1;
            }
         }
         httpTimer=setTimeout("sndManage()", httpInterval);
      } else {
         httpParamA=httpChain[0][0];
         httpParamB=httpChain[0][1];
         httpIsCritical=httpChain[0][2];
         httpChain.splice(0, 1);
         if (httpChain.length<5) { httpStopped=0; }
         if (httpIsCritical>2) {
            UpdateChat("0%LASTID!r_0!<span style=\"color: #E00000\">Запрос не может быть выполнен из-за сетевой ошибки. Команда отменена.</span><br />");
            httpErrState=1;
            return;
         }
         DosndPostReq(httpParamA, httpParamB);
         sndManage();
      }
   }
}

function sndPostReq(action, params, iscritical) {
   //if (heroID==3) { UpdateBattleLog("*** Lnt: " + httpChain.length + "; Mid: " + httpMidTime + "; Inter: " + httpInterval + "; Cri: " + iscritical + "<br />"); }
   if (httpChain.length>3) { if (httpMidTime<1500) { httpMidTime=1500; httpInterval=700; } }
   if (httpChain.length>5) { if (httpMidTime<2000) { httpMidTime=2000; httpInterval=800; } }
   if (httpChain.length>7) { if (httpMidTime<2500) { httpMidTime=2500; httpInterval=1000; } }
   if (httpChain.length>10) { if (httpMidTime<3000) { httpMidTime=3000; httpInterval=1500; } }
   if (httpChain.length>15) { if (httpMidTime<4000) { httpMidTime=4000; httpInterval=2000; } }
   if (httpChain.length>25) { if (httpMidTime<5000) { httpMidTime=5000; httpInterval=2500; } httpStopped=1; alert("Соединение с сервером потеряно. Нажмите клавишу F5 чтобы попытаться восстановиться соединение."); return; }
   httpStopped=0;
   httpChain[httpChain.length]=new Array(action, params, iscritical);
   sndManage();
}

function DosndPostReq(action, params) {
   httpBusy=1;
   httpStartTime=Date.parse(Date());
   httpRq=1;
   http.open('POST', action+'.php');
   http.onreadystatechange = handleResponse;
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.setRequestHeader("Content-length", params.length);
   http.setRequestHeader("Connection", "close");
   http.send(params);
   return false;
}
 
function handleResponse() {
   //UpdateBattleLog("state: " + http.readyState + "<br />");
   if (http.readyState == 4) {
      //UpdateBattleLog("state: " + http.readyState + "; busy: " + httpBusy + "; cri: " + httpIsCritical + "<br /><br />");

      var response = http.responseText;
      var update=null;

      if ((response!="") && (response.indexOf("|")!=-1)) {
         update = response.split("|");
         if ((update[0]=="chatmsgs") || (update[0]=="chatcmd")) {
            chatcomm(update[0], update[1]);
         } else {
            if (comm) { comm(update[0], update[1]); }
         }
         if (update[2]!=null) {
            if ((update[2]=="chatmsgs") || (update[2]=="chatonline") || (update[2]=="chatcmd")) { chatcomm(update[2], update[3]); }
            else if (comm) { comm(update[2], update[3]); }
         }
         update=null;
         httpErrState=0;
      } else {
         //if (httpErrState==0) {
         //   UpdateChat("0%LASTID!r_0!<span style=\"color: #E00000\">Потеряно соединение с сервером. Предпринимается попытка восстановить его.</span><br />");
         //   httpErrState=1;
         //}
         if (httpIsCritical>0) {
            httpChain.splice(0, 0, "");
            httpChain[0]=new Array(httpParamA, httpParamB, httpIsCritical+1);
         }
      }

      httpEndTime=Date.parse(Date());
      if ((httpEndTime - httpStartTime)>=1000) {
         httpMidTime=Math.round(((httpEndTime - httpStartTime) + httpMidTime) / 2);
      } else { httpMidTime=Math.round((1000 + httpMidTime) / 2); }
      httpInterval=Math.round(httpMidTime / 2);
      if (httpInterval>2000) { httpInterval=2000; }
      httpBusy=0;
   }
}


