// -----------------------------------------------------------------------
// <!-- ajaxResponse -->        - start of correct data response from server to ajax script
// <!-- ajaxResponseNoData -->  - start of correct respons for 'no data' case (sometimes we should process in in special way)
// any other response is treated as an error , it will be checked for the keywords until time out will pass, afterwards - you'll get error status
// Note: stupid IE do not see comments at the beginning of message, so server need to response something like :
//  " <span style='display:none'> For stupid IE </span><!-- ajaxResponse[NoData] --> "
// -----------------------------------------------------------------------
// ajaxQuery item object, mandatory features & methods example :
// ajaxQuery[i] = {
//									URL:'url to post ajax request',
//									Destination:'[hidden] span\div to put the response',
//									...
//									startItem:   function(){ alert('actions before posting ajax request'); },
//									finishItem:  function(){ alert('actions after the response is loaded into Destitation'); },
//									finishItems: function(){ alert('actions after all requests finished'); }
// 								};
// -----------------------------------------------------------------------
// first this script is included into your html page
// second ajaxQuery is been filled with objects to get by ajax
// third goAjaxQuery() call is done
//
// -----------------------------------------------------------------------
// pushToAjaxQuery(obj[,newQuery]) - adds obj to current ajaxQuery, 
// if defined newQuery - obj is added to new sub query ( finishItems() will be launched for previous sub query)
//

ajaxQuery = [];
ajaxQueryBussy = 0;
ajaxQueryProcessing = 0;
ajaxQueryTimeout = 250; // msec : 1000 = 1sec
ajaxQueryResultCheckIteration = 0;


function goAjaxQuery(){
	
		if(ajaxQueryBussy == 0 && ajaxQueryProcessing == 0){
			ajaxQueryBussy = 1;
			var ajaxQueryItem = ajaxQuery.shift();
			if(ajaxQueryItem == 'newSubQuery'){
				ajaxQueryItem = ajaxQuery.shift();
			}
			if(ajaxQueryItem){
				if(ajaxQuery.length == 0 || ajaxQuery[0] == 'newSubQuery'){
					ajaxQueryItem.ajaxQueryItemLast = 1;
					var devider = ajaxQuery.shift(); // just to remove it
				}
				ajaxQueryBussy = 1;
				ajaxQueryProcessing = ajaxQueryItem;
				if(typeof ajaxQueryProcessing.startItem == 'function'){
					ajaxQueryProcessing.startItem();
				}
				postAjaxRequest(ajaxQueryProcessing.URL,ajaxQueryProcessing.Destination,ajaxQueryProcessing.NoRewrite);
				//alert('posted '+ajaxQueryProcessing.URL);
				//ajaxQueryBussy = 0;
				window.setTimeout("goAjaxQuery()",ajaxQueryTimeout);
			}else{
				ajaxQueryBussy = 0;
				ajaxQueryProcessing = 0;
				ajaxQueryResultCheckIteration = 0;
				//return;
				window.setTimeout("goAjaxQuery()",ajaxQueryTimeout);
			}
		}else if(ajaxQueryBussy == 1 && ajaxQueryProcessing != 0){
			var check = ajaxQueryResultCheck();
			//alert("=Bussy:"+ajaxQueryBussy+'; Processing:'+ajaxQueryProcessing.tCode+"; CHECK="+check+'..'+ajaxQueryProcessing.Destination);
			if(check == 'notLoaded' && ajaxQueryResultCheckIteration <= 60){
				ajaxQueryResultCheckIteration++;
			}else{
				if(typeof ajaxQueryProcessing.finishItem == 'function'){
					ajaxQueryProcessing.finishItem(check);
				}
				if(ajaxQueryProcessing.ajaxQueryItemLast == 1){
					if(typeof ajaxQueryProcessing.finishItems == 'function'){
						ajaxQueryProcessing.finishItems();
					}
				}
				ajaxQueryBussy = 0;
				ajaxQueryProcessing = 0;
				ajaxQueryResultCheckIteration = 0;
			}
			window.setTimeout("goAjaxQuery()",ajaxQueryTimeout);
		}else if(ajaxQueryBussy != 0){
			window.setTimeout("goAjaxQuery()",ajaxQueryTimeout);
		}

}

function ajaxQueryResultCheck(){

	var destination = document.getElementById(ajaxQueryProcessing.Destination);
	if(destination && destination.innerHTML){
		if(destination.innerHTML.search(/ajaxResponseNoData/im) != -1 ){
			return 'empty';
		}else if(destination.innerHTML.search(/ajaxResponse /im) != -1 ){
			return 'loaded';
		}
	}
	return 'notLoaded';
}

function pushToAjaxQuery(obj,newQuery){

	if(newQuery){
		ajaxQuery.push('newSubQuery');
		ajaxQuery.push(obj);
	}else{
		ajaxQuery.push(obj);
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function fillBlockWithContent(destination,content){
	if(document.getElementById(destination)){
		document.getElementById(destination).innerHTML = content;
	}
	// check for javascript
	if(content.match('<script')){
		content = content.replace(/[\r\n]/gm,' ');
		//content = content.substr(0,1000);
		var l = content.length;
		content = content.replace(/<\/script>.*<script[^>]*?>/,'');
		content = content.replace(/^.*<script[^>]*?>/,''); // <script[^>]*?>.*?</script>
		//content = content.replace(/<\/script>.*<script[^>]*?>/,'');
		content = content.replace(/<\/script>.*$/,'');
		//content = content + ' // Iam '+l;
		document.getElementById(destination).innerHTML = document.getElementById(destination).innerHTML+'<!-- Iam '+ l +' -->';
		//alert('javascript included: '+content);
		//eval(content);
		var scr;// = document.createElement("script"); 
		    try{
			      scr = document.createElement("<script type='text/javascript'>");
		    }catch(ex){
			      scr = document.createElement("script");
		    }
		scr.setAttribute('type','text/javascript'); 
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
						scr.text = content; // FOR IE
		} else {
						scr.innerHTML = content;
		}

/*		scr.text = content; // FOR IE
		scr.innerHTML = content;*/
		document.getElementsByTagName("head")[0].appendChild(scr);
		//alert('added');
	}
}

function loadingProcess(destination){
	if(document.getElementById(destination)){
		document.getElementById(destination).innerHTML = "<img src='http://prf.icecat.biz/imgs/ajax_loader.gif'>";
	}
}

function postAjaxRequest(url,destination,noLoadingProcess){
   
    if(!this.http){
      this.http = getHttp();
      this.working = false;
    }
    if (!this.working && this.http) {
      var http = this.http;
			url = url + '&;rand='+Math.random();
//			alert(url+"\nTo\n"+destination);
      this.http.open("GET", url, true);
			if(!noLoadingProcess){
	      loadingProcess(destination);
			}
      this.http.onreadystatechange = function() {
                                                  if (http.readyState == 4) {
                                                    fillBlockWithContent(destination,http.responseText);
                                                    this.working = false;
                                                  }else{
                                                    //loading_process(destination);
                                                  }
                                                }
			if(!noLoadingProcess){
	      loadingProcess(destination);
			}
      this.http.send(null);
    }
    if(!this.http){
      alert('error  XMLHTTP request !')
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////

//function pause (mSec) {
//  clock = new Date();
//  justMinute = clock.getTime();
//  while (true) {
//    just = new Date();
//    if (just.getTime() - justMinute > mSec) break;
//  }
//}


function getHttp(){
    var xmlhttp;
    /*@cc_on
      @if (@_jscript_version >= 5)
        try {
             xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
                      try {
                            xmlhttp = new
                            ActiveXObject("Microsoft.XMLHTTP");
                          } catch (E) {
                                       xmlhttp = false;
                          }
        }
      @else
      xmlhttp = false;
   @end @*/
   if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}





