/*  FUNCTION SCRIPTS */ 
/*
				 AJAX от zeq'a 
 	 			   пыщъ пыщъ
*/

//##############################################################################################
// function to create object, in object pool

ajaxpool=new Array;

function GetNewAJAX(onreceive, onerror, oninprocess){
var i=0;
for (i in ajaxpool) {
     if (ajaxpool[i].ReadyState) {
	ajaxpool[i].onrsv = onreceive;
	ajaxpool[i].onerr = onerror;
	ajaxpool[i].oninproc = oninprocess;
	ajaxpool[i].ReadyState = false;
	return ajaxpool[i];
     };
}; 
 var ax = GetNewAJAX_inner(onreceive, onerror, oninprocess);
 ajaxpool.push(ax); 
 return ax;
};

function GetNewAJAX_inner(onreceive, onerror, oninprocess)
{	
	// пыщь!
	var ax = new Object();
	ax.name = "ajxmstr";
	//Так же нам понадобятся два масива для хранения GET и POST параметров
	ax.GET  = new Array();
	ax.POST = new Array();
	ax.ReadyState = false;
	ax.onrsv = onreceive;
	ax.onerr = onerror;
	ax.oninproc = oninprocess;
        // пыщь!пыщь!пыщь!
	    if (window.XMLHttpRequest) {
        	try {
	            ax.HTTP = new XMLHttpRequest();
	        } catch (e){}
	    } else if (window.ActiveXObject) {
	        try {
	            ax.HTTP = new ActiveXObject('Msxml2.XMLHTTP');
	        } catch (e){
	            try {
	                ax.HTTP = new ActiveXObject('Microsoft.XMLHTTP');
	            } catch (e){}
	        }
	   };

	//  функция добавления GET, 
	  ax.addGET = function(vname, value) {
	  ax.GET.push(vname + "=" +  ajaxspecencode(value)); // пыщъ!
	  }
	//  функция добавления POST
	  ax.addPOST = function(vname, value) {
	  ax.POST.push(vname + "=" +  ajaxspecencode(value));
	  }
	  
	//Функция для отправки запроса серверу, в параметре передается путь и имя файла
/*|asyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasyncasync|*/
	ax.request = function(file) {
	  var v;
	  var post;
	  this.HTTP.abort(); //Закрываем предыдущие соеденение
	  var url = file;
	  if(this.GET.length !== 0) {
	    url += "?";
	    for(v in this.GET) {
	      url += this.GET[v] + "&";
	    }
	  }
	  if(this.POST.length === 0) {
	     this.HTTP.open("GET", url, true);
	     post = null;
	  } else {
	     this.HTTP.open("POST", url, true);
	     post = "";
	    for(v in this.POST) {
	      post += this.POST[v] + "&";
	    }
	    this.HTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    this.HTTP.setRequestHeader("Content-Length", post.length);
	  }
   
	  this.HTTP.send(post);

	this.HTTP.onreadystatechange = function() {
	if(ax.HTTP.readyState == 2) { if(typeof(ax.oninproc) == "function") {ax.oninproc();} };
        if(ax.HTTP.readyState == 4) {
	    if(ax.HTTP.status == 200) {
	// качло!
	       var rText = ax.HTTP.responseText;
	       var rXml =  ax.HTTP.responseXML;
  	       if(typeof(ax.onrsv) == "function") ax.onrsv(rText, rXml);
 	   } else {
        //Ошибка!!! Если событие onerror отслеживается, то сгенерируем его
  	       var rErr = ax.HTTP.statusText;
      	      if(typeof(ax.onerr) == "function") ax.onerr(rErr);
    	  }; ax.ReadyState = true;
	  }}; // конец функции обработки смены статуса объекта
	 // ПЫЩЬ! ПЫШЬ!

	  this.GET  = new Array();
	  this.POST = new Array();
	  return true;
	  }; // request!

/*|syncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsyncsync|*/
	ax.syncrequest = function(file) {
	  var v;
	  var post;
	  this.HTTP.abort(); //Закрываем предыдущие соеденение
	  var url = file;
	  if(this.GET.length !== 0) {
	    url += "?";
	    for(v in this.GET) {
	      url += this.GET[v] + "&";
	    }
	  }
	  if(this.POST.length === 0) {
	     this.HTTP.open("GET", url, false);
	     post = null;
	  } else {
	     this.HTTP.open("POST", url, false);
	     post = "";
	    for(v in this.POST) {
	      post += this.POST[v] + "&";
	    }
	    this.HTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    this.HTTP.setRequestHeader("Content-Length", post.length);
	  }
   
	  this.HTTP.send(post);
	  ax.ReadyState = true;
	  this.GET  = new Array();
	  this.POST = new Array();
	  return this.HTTP.responseText;
	  }; // syncrequest!

    return ax;
} 

function ajaxspecencode(tocode) {
 var out="";
 var codestring=""+tocode;
 for (var i = 0; i < (codestring.length); i++)
  {
    var n = codestring.charCodeAt(i);
    if ((n<=255)||(n>=0x410 && n <= 0x44F)||(n==0x401)||(n==0x451)) { out+=String.fromCharCode(n); } else
    { out+="&#"+n+";"; };  
  };
 return encodeURIComponent(out);
}; // ajaxspecencode  

function humanstringdecode(text) {
 var n = text.length;
 var out = "";
 for (var i = 0; i < (n); i++)
 { if ((text.substring(i,i+2)=="&#")) {
	//   	определяем ;
     var xi = i+2;
     while ((text.substring(xi,xi+1)!==";") && (xi<n)) xi+=1;
     if (xi>i) {
	// начинаем проверку что тока цифры до ;
     var cnum = text.substring(i+2,xi)
     if (is_numeric(cnum)) {
     out+=String.fromCharCode(cnum);
     i=xi;
     } else { out+="&" };
     } else { out+="&" };
  } else { out+=text.substring(i,i+1); };
 };
 return out;
}; //humanstringdecode

function getfromapi(objid, addr, afterloadfunc) {
 var newfunc1 = function (text1) {
  objid.innerHTML=text1;
  if(typeof(afterloadfunc) == "function") {afterloadfunc()};
  };
  var ax=GetNewAJAX(newfunc1);
  ax.addPOST("Test", "Test");
  ax.request("API/"+ addr);
};
//////////////  --------------------------------------------------------------------< AJAX

 

function ltrim(withSpaces) 
{
	if(withSpaces.substring(0,1)!==" "){ 
            return withSpaces;
        } else {
        return ltrim(withSpaces.substring(1));
	};
}; // ltrim

function rtrim(withSpaces) 
{
        if(withSpaces.substring(withSpaces.length-1, withSpaces.length)!==" "){ 
            return withSpaces;
        } else {
        return rtrim(withSpaces.substring(0, withSpaces.length-1));
	};
}; // rtrim

function trim(withSpaces)
{
 return ltrim(rtrim(withSpaces));
}; //  trim 

function loadHTML(sURL)
{
  var request=null;
  // ОШРЮЕЛЯЪ ЯНГДЮРЭ НАЗЕЙР ДКЪ MSXML 2 Х ЯРЮПЬЕ
  if(!request) try {
    request=new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e){}

  // МЕ БШЬКН... ОНОПНАСЕЛ ДКЪ MSXML 1
  if(!request) try {
    request=new ActiveXObject('Microsoft.XMLHTTP');
  } catch (e){}

  // МЕ БШЬКН... ОНОПНАСЕЛ ДКЪ Mozilla
  if(!request) try {
    request=new XMLHttpRequest();
  } catch (e){}

  if(!request)
    // МХВЕЦН МЕ ОНКСВХКНЯЭ...
    return false;
 
  // ДЕКЮЕЛ ГЮОПНЯ
  request.open('GET', sURL, false);
  request.send(null);

  // БНГБПЮЫЮЕЛ РЕЙЯР
  return request.responseText;
}

function htmlspecialchars(html) {
		// Сначала необходимо заменить &
		html = html.replace(/&/g, "&amp;");
		// А затем всё остальное в любой последовательности
		html = html.replace(/</g, "&lt;");
		html = html.replace(/>/g, "&gt;");
		html = html.replace(/"/g, "&quot;");
return html;
}

function tfrmt(value){  if (value<=0) { return 1; } else { return value;}; };

function escapeA(txt)
{
 return escape(txt).replace("+","%2B");
}


function htmlspecialcharsb(text)
{
  var replacements = Array("<", ">", "&", '"');
  var chars = Array("&lt;", "&gt;", "&amp;", "&quot;");
  for(var i=0; i<chars.length; i++)
  {
     var re = new RegExp(chars[i], "gi");
     if(re.test(text))
     {
        text = text.replace(chars[i], replacements[i]);
     }
  }
  return text;
}


function specialformat(txt)
{
 var find= '[b],[i],[u],\r\n, ,\t,[/b],[/i],[/u],[img],[/img],[center],[/center],[right],[/right]'.split(',');
 var repl= '<b>,<i>,<u>,<br>,&nbsp;,&nbsp;&nbsp;&nbsp;&nbsp;,</b>,</i>,</u>,<img src=",">,<div class=cntr>,</div>,<div class=rght>,</div>'.split(',');
// var find= new Array('[b]', '[i]', '[u]', '\r\n', ' ', '\t', '[/b]', '[/i]', '[/u]', '[img]', '[/img]', '[center]', '[/center]');
// var repl= new Array();
 return str_replace(find, repl, txt);
};


function str_replace2 (search, replace, subject )
{

    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
    
    var i=0;
    var c=0;
    var isrep=false;
    var cc=search.length;	
    var ln=subject.length;
    var outs="";

    while (i<ln){
	c=0;
	isrep=false;
	while (c<cc) {
	    if (xbitte(subject, i, search[c]))
	    {
	    i+=search[c].length;
	    outs+=replace[c];
	    isrep=true;
	    c=cc;};
	    c+=1;
	}
	if (! isrep){
	outs+=subject.substr(i,1);
	i+=1;
	}
	};
	return outs;

}; //



function xbitte(st, spos, elm)
{
  return st.substr(spos, elm.length)==elm;
}



function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
}


function wordwrap( str, int_width, str_break, cut ) {    // Wraps a string to a given number of characters
    // 
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Nick Callen
 
    var i, j, s, r = str.split("\n");
    if(int_width > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > int_width;
            j = cut ? int_width : (j = s.substr(0, int_width).match(/\S*$/)).input.length - j[0].length || int_width,
            r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? str_break : "")
        );
        r[i] += s;
    }
    return r.join("\n");
}

function dw(text) { document.write(text) };
function dwb(toObject, text) { toObject.innerHTML=text; };
function did(elId) { return document.getElementById(elId); };
 

function getyScroll()
 {
  yScroll = 0;

  if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX)
   {
    yScroll = window.innerHeight + window.scrollMaxY;
    xScroll = window.innerWidth + window.scrollMaxX;

    var deff = document.documentElement;
    var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
    var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;

    xScroll -= (window.innerWidth - wff);
    yScroll -= (window.innerHeight - hff);
   } 
  else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth)
   { // all but Explorer Mac
    yScroll = document.body.scrollHeight;
    xScroll = document.body.scrollWidth;
   } 
  else 
   { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    yScroll = document.body.offsetHeight;
    xScroll = document.body.offsetWidth;
   }

  return yScroll;
 };

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
};

function setCookieA(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}



function urlencode(text)
{
	text = escape(text.toString()).replace(/\+/g, "%2B");
	var matches = text.match(/(%([0-9A-F]{2}))/gi);
	if (matches)
	{
		for (var matchid = 0; matchid < matches.length; matchid++)
		{
			var code = matches[matchid].substring(1,3);
			if (parseInt(code, 16) >= 128)
			{
				text = text.replace(matches[matchid], '%u00' + code);
			}
		}
	}
	text = text.replace('%25', '%u0025');
	return text;
};

 
function utf8_encode ( str_data ) {    // Encodes an ISO-8859-1 string to UTF-8
    // 
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
 
    str_data = str_data.replace(/\r\n/g,"\n");
    var utftext = "";
 
    for (var n = 0; n < str_data.length; n++) {
        var c = str_data.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
 
    return utftext;
} 

function utf8_decode ( str_data ) {    // Converts a string with ISO-8859-1 characters encoded with UTF-8   to single-byte
    // ISO-8859-1
    // 
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
 
    var string = "", i = 0, c = c1 = c2 = 0;
 
    while ( i < str_data.length ) {
        c = str_data.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if((c > 191) && (c < 224)) {
            c2 = str_data.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return string;
}

function is_numeric( mixed_var ) {    // Finds whether a variable is a number or a numeric string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
 
    return !isNaN( mixed_var );
} 


function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}


function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function enumClasses(ClassName, func, node,tag) {
	var obj = getElementsByClass(ClassName,node, tag);
	var tih = '';
	for(i=0;i<obj.length;i++){
		func(obj[i]);
	}
};

function addEvent(el, evnt, func){
   if (el.addEventListener) {
      el.addEventListener(evnt.substr(2).toLowerCase(), func, false);
   } else if (el.attachEvent) {
      el.attachEvent(evnt.toLowerCase(), func);
   } else {
      el[evnt] = func;
   }
}

