/*
 * Ext Sajax Library
 * Copyright(c) 2007-2008
 * 
 * Sabayev, Malyshev
 * 
 * http://wday.ru
 */
sajax={};
sajax.DEBUG=0;
var ldr=null;
var ldr2=null;
var processNew;
var localDiv=null;
var localDiv2=null;
var parentDiv=null;
var divT=null;
var divT2=null;
var d_a=null;
var storeHTML;
var threadNum;
var ret=false;

//multi vars
var freeThread=1; //can we process current request
var threadArray = new Array; 
var threadCounter=0;
var ldrA= new Array(7); // array for store ajax request
var threadArray= new Array(100); //array pool for ajax requests
for (i=0; i <100; i++) threadArray[i]=new Array(7);
var divA= new Array(100); // maximum pool unical calls per page
for (i=0; i <100; i++) divA[i]=0;

var sT= new Array(100); // maximum pool unical calls per page
for (i=0; i <100; i++) sT[i]=null;


sajax.document = document;

sajax.selector=function()
{
  var A=null;
  try{A=new ActiveXObject("Msxml2.XMLHTTP")}
  catch(e){try{A=new ActiveXObject("Microsoft.XMLHTTP")}
  catch(oc){A=null}}
  if(!A&&typeof XMLHttpRequest!="undefined") {A=new XMLHttpRequest()}
  return A
}

/*
Parametrs:
  url - sajax script url
  data - action and data for script (object)
  doc - document js object for main page
  div - element id which hide, transform or replace
  div_action - how show sajax progress (add,hold,butt or nothing)
  div2 - for hold only, which element id transform
  
*/

sajax.XMLCmdIce= function (url,data,doc,div,div_action,div2,threadNum)
{
eval('if(sT['+threadNum+']){clearTimeout(sT['+threadNum+']);} sT['+threadNum+']=setTimeout( function(){sajax.XMLCmd(url,data,doc,div,div_action,div2,'+threadNum+')},1);'); //350
return false;
}

/*
Parametrs:
  url - sajax script url
  data - action and data for script (object)
  doc - document js object for main page
  div - element id which hide, transform or replace
  div_action - how show sajax progress (add,hold,butt or nothing)
  div2 - for hold only, which element id transform
*/
sajax.XMLCmd= function (url,data,doc,div,div_action,div2,uid)
{
 if(doc)sajax.document = doc;
 if(div_action){sajax.d_a = div_action;}else{sajax.d_a=null;}
 if(!uid || uid>100 || uid<0)uid=0;
 sajax.showLoader(sajax.d_a,uid,div,div2);
 pushThread(url,data,div,div_action,div2,uid);
 sajax.timeout2 = setInterval( function(){sajax.threadPool();}, 1); //1000
 return false;
}

/*
ldrA[0] loader
ldrA[1] url
ldrA[2] data
*/

sajax.threadPool= function()
 { 
if(freeThread==1)
 {

 ldrA=popThread();
 if (ldrA[1]) ldr=sajax.selector();
 if(ldr && ldrA[1])
 {
  freeThread=0;
  name.length = 0;
  var now = new Date();
  ldr.open("POST",ldrA[1]+"?t="+now.getSeconds(),true);
  ldr.setRequestHeader("Method", "POST " + ldrA[1] + " HTTP/1.1");
  ldr.setRequestHeader("Content-Type", "text/plain");
  ldr.onreadystatechange=function()
  {
   if(ldr.readyState==4 && ldr.responseXML)
   {
    freeThread=1;
    sajax.ProcessXmlIce(ldr,ldrA[3],ldrA[4],ldrA[5],ldrA[6]);
   }
  };

  ldr.send(ldrA[2]);

 }else{ clearInterval(sajax.timeout2);}
 }
 }

/*
push|pop threadSection
*/
pushThread = function (url,data,div,div_action,div2,uid)
 {
 var jsn = 1;
 if(threadCounter<100){
  if(data.toJSONString=== undefined)
//    if(data.tagName && "FORM" == data.tagName.toUpperCase())
      {
//      data=sajax.getFormValues(data);
      data = sajax.JSONform(data);
      jsn = 0;
      }

 threadArray[threadCounter][0]=null;
 threadArray[threadCounter][1]=url;
 threadArray[threadCounter][2]=(jsn==1)?data.toJSONString():data;
 threadArray[threadCounter][3]=div;
 threadArray[threadCounter][4]=div_action;
 threadArray[threadCounter][5]=div2;
 threadArray[threadCounter][6]=uid;
 threadCounter++;
 }
 }

popThread = function ()
 {
 if(threadCounter==0) return [null,null,null];
 threadCounter--;
 return [threadArray[threadCounter][0], threadArray[threadCounter][1], threadArray[threadCounter][2],threadArray[threadCounter][3], threadArray[threadCounter][4], threadArray[threadCounter][5],threadArray[threadCounter][6]];
 }

/*
process section
*/

sajax.ProcessXmlIce= function (request,div,div_action,div2,uid)
{
 var responseXML = request.responseXML;
 if (responseXML.documentElement && responseXML.documentElement.localName!="parsererror") 
 {
  var child = responseXML.documentElement.firstChild;
  while (child) 
  {
   if(sajax.command[child.nodeName]) sajax.command[child.nodeName](child);
   child = child.nextSibling;
  }

 if(div){sajax.localDiv = sajax.document.getElementById(div);divT=div;}else{sajax.localDiv=null;divT=null;}
 if(div2){sajax.localDiv2 = sajax.document.getElementById(div2);divT2=div2;}else{sajax.localDiv2=null;divT2=null;}
 if(div_action){sajax.d_a = div_action;}else{sajax.d_a=null;}
 }
 else
 {
  if(sajax.DEBUG) sajax.Error('no valid xml',request.responseText);
 }
 // delete loaded loader-pic
 sajax.hideLoader(div_action,uid,div,div2);

}


sajax.command = [];

sajax.command['replace']= function(child) {
     var dest=$$(child,"id")[0].firstChild.data;
     $(dest).innerHTML=$$(child,"data")[0].firstChild.data;
}
sajax.command['addpre']= function(child) {
     var dest=$$(child,"id")[0].firstChild.data;
     $(dest).innerHTML=$$(child,"data")[0].firstChild.data+$(dest).innerHTML;
}

sajax.command['add']= function(child) {
     var dest=$$(child,"id")[0].firstChild.data;
     $(dest).innerHTML=$(dest).innerHTML+$$(child,"data")[0].firstChild.data;
}

sajax.command['insert']= function(child) {
     var xDV = sajax.document.createElement('div');
     xDV.innerHTML=$$(child,"data")[0].firstChild.data;
     var dest=$$(child,"id")[0].firstChild.data;
     $(dest).parentNode.insertBefore(xDV,$(dest));
}

sajax.command['remove']= function(child) {
  sajax.dom.remove($$(child,"id")[0].firstChild.data);
}

sajax.command['hide']= function(child) {
     var id=$$(child,"id")[0].firstChild.data;
     $(id).style.display='none';
}

sajax.command['show']= function(child) {
     var id=$$(child,"id")[0].firstChild.data;
     $(id).style.display='block';
}

sajax.command['javascript']= function(child) {
     eval(child.firstChild.data);
}

sajax.Error=function (name,txt)
{
 var obj =sajax.document.createElement('div');
 obj.setAttribute('id', 'sajax_error');
 obj.style.position='absolute';
 obj.style.top='10px';
 obj.style.left='10px';
 obj.style.border='1px solid red';
 obj.style.backgroundColor='#ffffff';
 obj.style.padding='10px';
 obj.style.width='700px';
 sajax.document.body.appendChild(obj);
 obj.innerHTML='<b>ERROR:'+name+'</b><textarea style="width:100%;height:400px">'+txt+'</textarea>';
}

sajax.dom={};

sajax.dom.remove = function(element) {
  if ('string' == typeof (element))
    element = $(element);
  
  if (element && element.parentNode && element.parentNode.removeChild)
    element.parentNode.removeChild(element);

  return true;
}

function $(sId)
{
  if (!sId) {
    return null;
  }
  var returnObj = sajax.document.getElementById(sId);
  if (!returnObj && sajax.document.all) {
    returnObj = sajax.document.all[sId];
  }
  if (sajax.DEBUG & !returnObj) {
      sajax.Error('$()',"Element with the id \"" + sId + "\" not found.");
  }
  return returnObj;
}

function $$(obj,tagname)
{
  if (!tagname) {
    return null;
  }
  var returnObj = obj.getElementsByTagName(tagname);
  if (sajax.DEBUG & (!returnObj || returnObj.length==0)) {
      sajax.Error('$$()',"Element with the tagname\"" + tagname + "\" not found.");
  }
  return returnObj;
}

sajax.CenterLogo= function (){
var obj=$('iceLoader');
var scroll=getScrollXY();
var pageWidth=window.innerWidth != null? window.innerWidth: document.documentElement != null? document.documentElement.clientWidth:null;
var pageHeight=window.innerHeight != null? window.innerHeight: document.documentElement != null? document.documentElement.clientHeight:null;
obj.style.top=(scroll[1]+(pageHeight/2))+'px';
obj.style.left=(scroll[0]+(pageWidth/2))+'px';
}

function getScrollXY() { 
  var scrOfX = 0, scrOfY = 0; 
  if( typeof( window.pageYOffset ) == 'number' ) { 
    //Netscape compliant 
    scrOfY = window.pageYOffset; 
    scrOfX = window.pageXOffset; 
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { 
    //DOM compliant 
    scrOfY = document.body.scrollTop; 
    scrOfX = document.body.scrollLeft; 
  } else if( document.documentElement && 
      ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { 
    //IE6 standards compliant mode 
    scrOfY = document.documentElement.scrollTop; 
    scrOfX = document.documentElement.scrollLeft; 
  } 
  return [ scrOfX, scrOfY ]; 
} 

function getPageSize(){
  
  var xScroll, yScroll;
  
  if (window.innerHeight && window.scrollMaxY) {  
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  } 
  
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else { 
    pageHeight = yScroll;
  }

  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){  
    pageWidth = windowWidth;
  } else {
    pageWidth = xScroll;
  }


  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
  return arrayPageSize;
}

/*
Parametrs:
  act - how show sajax progress (add,hold,butt or nothing)
  uid - unical thread id for this page
  div - element id which hide, transform or replace
  div2 - for hold only, which element id transform
  
*/

sajax.hideLoader = function (act,uid,div,div2)
{
 hideNow=true;
 if(uid){divA[uid]=divA[uid]-1;if(divA[uid]>0)hideNow=false;}
 if(hideNow || uid==0){
   if(div){sajax.localDiv = sajax.document.getElementById(div);divT=div;}else{sajax.localDiv=null;divT=null;}
   if(div2){sajax.localDiv2 = sajax.document.getElementById(div2);divT2=div2;}else{sajax.localDiv2=null;divT2=null;}
        
        switch (act) {
        case 'hold':
    sajax.localDiv.style.display="block";
    if(sajax.document.getElementById('iceHold'+divT))sajax.document.getElementById('iceHold'+divT).style.display='none';
    if(sajax.localDiv2){
    sajax.localDiv2.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
    sajax.localDiv2.style.MozOpacity="1";
    sajax.localDiv2.style.opacity="1";}
          if(sajax.document.getElementById('iceLoader')){sajax.document.getElementById('iceLoader').style.display='none';}
    break;
        case 'butt':
                if (sajax.localDiv) sajax.localDiv.innerHTML = sajax.storeHTML;
          if(sajax.document.getElementById('iceLoader')){sajax.document.getElementById('iceLoader').style.display='none';}
    break;
  case 'add2':
  case 'nope':  break;
        case 'add':
    if(sajax.document.getElementById('iceLocal'+divT)){sajax.document.getElementById('iceLocal'+divT).style.display='none';}
    sajax.localDiv.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
    sajax.localDiv.style.MozOpacity="1";
    sajax.localDiv.style.opacity="1";
          if(sajax.document.getElementById('iceLoader')){sajax.document.getElementById('iceLoader').style.display='none';}
    break;    
        default:
          if(sajax.document.getElementById('iceLoader')){sajax.document.getElementById('iceLoader').style.display='none';}
        }
 }
}

sajax.showLoader = function (act,uid,div,div2)
{
 drawNew=true;
 if(uid){if(divA[uid]>0)drawNew=false;divA[uid]=divA[uid]+1;}
 if(drawNew || uid==0){
   if(div){sajax.localDiv = sajax.document.getElementById(div);divT=div;}else{sajax.localDiv=null;divT=null;}
   if(div2){sajax.localDiv2 = sajax.document.getElementById(div2);divT2=div2;}else{sajax.localDiv2=null;divT2=null;}
        
        switch (act) {
        case 'add2':
    if(sajax.localDiv){
    xDIV = sajax.document.createElement('div');
    xDIV.innerHTML = "&nbsp;";
    xDIV.setAttribute("id", "iceLocal"+div);
    xDIV.style.display='none';
    xDIV.className = "loading-balls";
    xDIV.style.width='16px';
    xDIV.style.height='16px';
    xDIV.style.position='relative';
    xDIV.style.top='0px';
    xDIV.style.left='0px';
    xDIV.style.backgroundImage='url(/i/infinity-ico-loading.gif)';
    sajax.localDiv.appendChild(xDIV);
    xDIV.style.display='block';
    }
    break;

        case 'popup':
    if(sajax.localDiv){
    if(!sajax.document.getElementById('iceLocal'+div)){
    xDIV = sajax.document.createElement('div');
    sajax.parentDiv = sajax.localDiv.parentNode;
    xDIV.innerHTML = "&nbsp;";
    xDIV.setAttribute("id", "iceLocal"+div);
    xDIV.style.display='none';
    xDIV.className = "loading-balls";
    xDIV.style.width='16px';
    xDIV.style.height='16px';
    xDIV.style.position='absolute';
    xDIV.style.backgroundImage='url(/i/infinity-ico-loading.gif)';
    sajax.parentDiv.appendChild(xDIV);
    sajax.localDiv.style.filter="alpha(opacity=20)";
    sajax.localDiv.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
    sajax.localDiv.style.KhtmlOpacity=".20";
    sajax.localDiv.style.MozOpacity=".20";
    sajax.localDiv.style.opacity="0.20";
    xDIV.style.display='block';
    }else{
    sajax.localDiv.style.filter="alpha(opacity=20)";
    sajax.localDiv.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
    sajax.localDiv.style.KhtmlOpacity=".20";
    sajax.localDiv.style.MozOpacity=".20";
    sajax.localDiv.style.opacity="0.20";
    sajax.document.getElementById('iceLocal'+div).style.display='block';}}
    break;

        case 'hold':
    if(sajax.localDiv){
    if(!sajax.document.getElementById('iceHold'+div)){
    xDIV = sajax.document.createElement('div');
    sajax.parentDiv = sajax.localDiv.parentNode;
    if(sajax.localDiv2){
      sajax.localDiv2.style.filter="alpha(opacity=20)";
      sajax.localDiv2.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
      sajax.localDiv2.style.MozOpacity=".20";
      sajax.localDiv2.style.KhtmlOpacity=".20";
      sajax.localDiv2.style.opacity="0.20";}
    xDIV.innerHTML = "&nbsp;";
    xDIV.setAttribute("id", "iceHold"+div);
    xDIV.className = "loading-balls";
    xDIV.style.top='0px';
    xDIV.style.left='420px';
    xDIV.style.position='absolute';
    xDIV.style.backgroundImage='url(/i/infinity-ico-loading.gif)';

    xDIV.style.display='none';
    sajax.parentDiv.appendChild(xDIV);
    sajax.localDiv.style.display="none";
    xDIV.style.display='block';
    }else{
    if(sajax.localDiv2){
      sajax.localDiv2.style.filter="alpha(opacity=20)";
      sajax.localDiv2.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
      sajax.localDiv2.style.MozOpacity=".20";
      sajax.localDiv2.style.KhtmlOpacity=".20";
      sajax.localDiv2.style.opacity="0.20";}
    sajax.localDiv.style.display="none";
    sajax.document.getElementById('iceHold'+div).style.display='block';}}
    break;
        case 'butt':
    if(sajax.localDiv){
    sajax.storeHTML = sajax.localDiv.innerHTML;
    sajax.localDiv.innerHTML = "<img src='/i/infinity-ico-loading.gif' style='padding:0px;margin:0px' width='32' height='32' title='Загрузка...' alt='Загрузка...'> Загрузка...";
    }
    break;
       /* case 'buttp':
    if(sajax.localDiv){
    sajax.storeHTML = sajax.localDiv.innerHTML;
    sajax.localDiv.innerHTML = "<img src='/i/infinity-ico-loading.gif' style='padding:0px;margin:0px' width='32' height='32' title='Загрузка...' alt='Загрузка...'> Загрузка...";
    }    */

    break;

  case 'nope': break;

        default:
    if(!sajax.document.getElementById('iceLoader')){
    xDIV = sajax.document.createElement('div');
    xDIV.innerHTML = "<img src='/i/infinity-ico-loading.gif' width='32' height='32' alt='Загрузка...' title='Загрузка...'>";
    xDIV.setAttribute("id", "iceLoader");
    xDIV.style.display='none';
    xDIV.style.top='0px';
    xDIV.style.left='0px';
    xDIV.style.position='absolute';
    xDIV.style.zIndex='1000';
    sajax.document.body.insertBefore(xDIV,sajax.document.body.childNodes[0]);
    sajax.CenterLogo();
    xDIV.style.display='block';
    }else{sajax.CenterLogo();sajax.document.getElementById('iceLoader').style.display='block';}
        }

 }
}


//-- json
Array.prototype.toJSONString = function () {
    var a = ['['], b, i, l = this.length, v;
    for (i = 0; i < l; i += 1) {
        v = this[i];
        switch (typeof v) {
        case 'undefined':
        case 'function':
        case 'unknown':
            break;
        default:
            if (b) {
                a.push(',');
            }
            a.push(v === null ? "null" : v.toJSONString());
            b = true;
        }
    }
    a.push(']');
    return a.join('');
};

Boolean.prototype.toJSONString = function () {
    return String(this);
};

Date.prototype.toJSONString = function () {

    function f(n) {
        return n < 10 ? '0' + n : n;
    }

    return '"' + this.getFullYear() + '-' +
            f(this.getMonth() + 1) + '-' +
            f(this.getDate()) + 'T' +
            f(this.getHours()) + ':' +
            f(this.getMinutes()) + ':' +
            f(this.getSeconds()) + '"';
};

Number.prototype.toJSONString = function () {
    return isFinite(this) ? String(this) : "null";
};
/*
Object.prototype.toJSONString = function () {
var obj=this;
if(obj.tagName && "FORM" == obj.tagName.toUpperCase())
    {
    obj=sajax.getFormValues(this);

    var a = ['{'], b, i, v;
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            v = obj[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            default:
                if (b) {
                    a.push(',');
                }
    if(v.toJSONString=== undefined)
    if(v.tagName && "FORM" == v.tagName.toUpperCase()) v=sajax.getFormValues(v);

                a.push(i.toJSONString(), ':',
                        v === null ? "null" : v.toJSONString());
                b = true;
            }
        }
    }
    a.push('}');
    return a.join('');
    }else return null;
};
*/
sajax.JSONform = function (obj) {
if(obj.tagName && "FORM" == obj.tagName.toUpperCase())   obj=sajax.getFormValues(obj);
    var a = ['{'], b, i, v;
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            v = obj[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            default:
                if (b) {
                    a.push(',');
                }
    if(v.toJSONString=== undefined)
      {
       v = sajax.JSONform(v);
       a.push(i.toJSONString(), ':',v === null ? "null" : v);
      }else a.push(i.toJSONString(), ':',v === null ? "null" : v.toJSONString());

                b = true;
            }
        }
    }
    a.push('}');
    return a.join('');
};


String.prototype.parseJSON = function () {
    try {
        if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) {
            return eval('(' + this + ')');
        }
    } catch (e) {
    }
    throw new SyntaxError("parseJSON");
};

(function () {
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };

    String.prototype.toJSONString = function () {
        if (/["\\\x00-\x1f]/.test(this)) {
            return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if (c) {
                    return c;
                }
                c = b.charCodeAt();
                return '\\u00' +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + this + '"'; //escape()
    };

})();

// -- getForm
sajax.getFormValues = function(element) {
  var submitDisabledElements = false;
  if (arguments.length > 1 && arguments[1] == true)
    submitDisabledElements = true;
  
  var prefix="";
  if(arguments.length > 2)
    prefix = arguments[2];
  
  if ("string" == typeof(element))
    element = $(element);
  
//  var aXml = new Object;
  var aXml = new Array;
  if (element && element.tagName && "FORM" == element.tagName.toUpperCase()) {
    var formElements = element.elements;
    for (var i = 0; i < formElements.length; ++i) {
      var child = formElements[i];
      if (!child.name)
        continue;
      if (prefix != child.name.substring(0, prefix.length))
        continue;
      if (child.type && (child.type == 'radio' || child.type == 'checkbox') && child.checked == false)
        continue;
      if (child.disabled && true == child.disabled && false == submitDisabledElements)
        continue;
      var name = child.name;
      if (name) {
        if('select-multiple' == child.type) {
          if (name.substr(name.length-2, 2) != '[]') { name += '[]'; aXml[name]= new Array;}
          for (var j = 0; j < child.length; ++j) {
            var option = child.options[j];
            if (true == option.selected) {
              aXml[name].push(option.value);
            }
          }
        } 
        else if(name.substr(name.length-2, 2) == '[]') {
        if(!aXml[name]) aXml[name]= new Array;
        aXml[name].push(child.value);
        }
        else {

          aXml[name]=child.value;
        }
      } 
    }
  }

  return aXml; 
}
