// usage: 
// ajax.queue({url: 'target.cfm', targetId: 'target_id', })
//-------------------------------
// url - (required) Url of the request
// target|targetId - (optional) Target container 
//      which will receive contents as innerHTML
// formVarsString - (optional) 
//                  Encoded form vars string
// formVarsObj - (optional) 
//               Object that will encode parameters as key1=value1&key2=value2
//               Mutually exclusive with formVarsString
// onload   - function to be launched on load
//                  first argument will contain these variables
//                  args - This object
//                  request - XMLHttpRequest object.
//                            Use request.responseText to retreive contents
// params - put all variables that 


ajax ={
    readyStateEnum  : {
        UNINITIALIZED : 0 ,
        LOADING : 1, 
        LOADED : 2,
        INTERACTIVE : 3,
        COMPLETE : 4
    },
  
    URLEncode: function (decoded) {
        return encodeURIComponent(decoded);
    },
    encodeForm : function () {
        var cRet="";
        for(var i=0; i < arguments.length; i=i+2) {
            if(i>0) {
                cRet+="&";
            }
            if(arguments[i+1]===null) {
                arguments[i+1]="";
            }
            cRet+=encodeURIComponent(arguments[i])+"="+encodeURIComponent(arguments[i+1]);
        }
        return cRet;
    },
    encodeFormStruct : function (obj) {
        var cRet="";
        var i=0;
        for(var cProp in obj) {
            if(i>0) {
                cRet+="&";
            }
            cRet+=encodeURIComponent(cProp)+"="+encodeURIComponent(obj[cProp]);
            i++;
        }
        return cRet;
    },
    setStatusMessage : function(message) {    
         /*
		if(!this.infoBox) {
                this.infoBox = document.createElement('div');
                this.infoBox.style.position='absolute';
                this.infoBox.style.top='0px';
                this.infoBox.style.right='10px';
                this.infoBox.style.height='15px';
                this.infoBox.style.width='100px';
                this.infoBox.style.fontFamily='Verdana';
                this.infoBox.style.fontSize='11px';
                this.infoBox.id='StatusDiv';
                
				document.body.appendChild(this.infoBox);
        }
        var y;
        if (self.pageYOffset) { // all except Explorer
            y = self.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
            y = document.documentElement.scrollTop;
        }    
        else if (document.body) { // all other Explorers
            y = document.body.scrollTop;
        }
        this.infoBox.style.top = y + 'px';
        this.infoBox.style.display='block';*/
		
    },
     
    getForm : function (frm) {
        var cSubmitStr="";
        for(var i=0;i<frm.elements.length;i++) {
            var cElem=frm.elements[i];
            if(((cElem.type.toLowerCase() == 'checkbox' || cElem.type.toLowerCase() == 'radio') && cElem.checked===false ) || cElem.disabled===true || cElem.type.toLowerCase() == 'button') {
            }
            else if(cElem.tagName.toLowerCase()=='input') {
                cSubmitStr+=cElem.name+"="+encodeURIComponent(cElem.value)+"&";
            }
            else if(cElem.tagName.toLowerCase()=='select') {
                if(cElem.multiple) {
                    for(var j=0;j < cElem.length;j++) {
                        if(cElem[j].selected) {
                            cSubmitStr+=cElem.name+"="+encodeURIComponent(cElem[j].value)+"&";
                        }
                    }
                }
                else {
                    cSubmitStr+=cElem.name+"="+encodeURIComponent(cElem[cElem.selectedIndex].value)+"&";
                }
            }
            else if(cElem.tagName.toLowerCase()=='textarea') {
                cSubmitStr+=cElem.name+"="+encodeURIComponent(cElem.value)+"&";
            }


        }
        return cSubmitStr;
    },
    bustcachevar: 1, //bust potential caching of external pages after initial request? (1=yes, 0=no)
    loadedobjects: "",
    bustcacheparameter:"",
    serializeStack:new Array(),
    ajaxInProcess:0,

    queue: function (obj) {
        this.serializeStack.push(obj);
        this.processqueue();
    },

    processqueue: function () {
        if(this.ajaxInProcess===0&&this.serializeStack.length>0) {
            this.setStatusMessage('<img src="images/loading.gif" />');
            this.process(this.serializeStack.shift());
        }
    },
    
    getPageRequest:function (){
        var page_request=false;
        if (window.XMLHttpRequest) { // if Mozilla, Safari etc
            page_request = new XMLHttpRequest();
        }
		else if(typeof(ie6GetAjaxObject) != "undefined"){
			page_request=ie6GetAjaxObject();
		}
        return page_request;
    },
    insertScript: function (str){
      var re = /<script\b[\s\S]*?>([\s\S]*?)<\/script/ig;
      var match;
      /*/var oldScript=document.getElementById("script_"+targetContainerId);
      if(oldScript!==null) {
          document.body.removeChild(oldScript);
      }*/
      while ( ( match = re.exec(str) )) {
          var newScript = document.createElement('script');
          newScript.type = "text/javascript";
          newScript.text = match[1];
          document.body.appendChild (newScript);	
      }
    },
    process: function (obj) {
        //url, containerid,message,customload
        this.currentObj=obj;
        var message=null;
        if(this.currentObj.formVarsString)
            message=this.currentObj.formVarsString;
        else if(this.currentObj.formVarsObj)
            message=this.encodeFormStruct(this.currentObj.formVarsObj);
        this.page_request = this.getPageRequest();
        this.page_request.onreadystatechange=function(){ajax.loadpage()};
        if (this.bustcachevar) { //if bust caching of external page
            bustcacheparameter=(this.currentObj.url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
        }
        var operation="GET";
        if(message) {
            operation="POST";
        }
        this.page_request.open(operation, this.currentObj.url+bustcacheparameter, true);
        if(message) {
            this.page_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        }
    
        this.ajaxInProcess=1;
        this.page_request.send(message);
    },

    loadpage : function () {
        // this.page_request  and this.currentObj can be accessed

        if (this.page_request.readyState == this.readyStateEnum.COMPLETE) {
            
            //(|| window.location.href.indexOf("http")==-1)) {
        //this.page_request.status==200 
            var targetId=null;
            var args= this.currentObj;
            var target=null;
            if(typeof args.targetId  != "undefined" && args.targetId !== null) {
                targetId=args.targetId;

            }
            if(typeof args.target  != "undefined" && args.target !== null) {
                target= args.target;
                if(targetId==null&&typeof target.id  != "undefined")
                  targetId=target.id;
            }
            else if(targetId!==null)
                target=document.getElementById(targetId);
            if (target) {
                target.innerHTML=this.page_request.responseText;
                this.insertScript(this.page_request.responseText);
            }
			try {
	            if(typeof args.onload  != "undefined" && args.onload !== null){
					
	                args.onload({args:args,request:this.page_request});
	            }
			}
			finally {

	            this.ajaxInProcess=0;
	            if(this.serializeStack.length>0) {
	                //Defer to prevent recursion
	                window.setTimeout("ajax.processqueue()",0);
	            }
	            else {
					if(this.infoBox)
						this.infoBox.style.display = 'none';
						
	            }
			}
        }
    }
};
