// Taqua Ajax
_d = (typeof _d=="undefined")?document:_d;
_UND = (typeof _UND == 'undefined')?'undefined':_UND;
//function to replace string
var _Replace = function(strSearch,strReplace,str){
	var newstr = "";
	if(str.Trim() != ""){
		var strarr = str.split(strSearch);
		newstr = strarr.join(strReplace);
	}
	return newstr;
}

String.prototype.Replace = function(strSearch,strReplace){return _Replace(strSearch,strReplace,this.toString());}
function _(selector){
	//by id (baseobj if set, not allowed, only document)
        var qsel = document.getElementById(selector);
        if(qsel != null)return qsel;

        //by classname
        var qsel = document.getElementsByClassName(selector);
        if(qsel.length > 0){
            var arrRtn = Array.prototype.slice.call(qsel); 
            return arrRtn.length == 1?arrRtn[0]:arrRtn;
          }

        //by name (baseobj if set, not allowed, only document)
        var qsel = document.getElementsByName(selector);
        if(qsel.length > 0){
            var arrRtn = Array.prototype.slice.call(qsel); 
            return arrRtn.length == 1?arrRtn[0]:arrRtn;
          }

        //if not found
        return null;
}

//trim leading and trailing space
var _Trim = function(val){
	//alert(val);
	if(typeof val == 'string'){
	 //return val.replace(/^\s+|\s+$/g,'');
	 if (typeof String.prototype.trim != 'function')return val.replace(/^\s+/, '').replace(/\s+$/, '');
     return val.trim();
	}else if(IsObject(val)){
	val = val.GetText();
	return _Trim(val);	
	}else if(IsArray(val)){
		var newarr = new Array();
		for(var s=0,lens=val.length; s < lens ; s++){
			var rtn = _Trim(val[s]);
			if(IsArray(rtn)){
				newarr.concat(rtn);
			}else if(typeof rtn == 'string'){
				newarr.push(rtn);
			}
		}
		return newarr;
	}else{
	  return val;	
	}
}
String.prototype.Trim = function(n){return _Trim(this.toString())}
Array.prototype.Trim = function(n){return _Trim(this)}
//Object.prototype.Trim = function(n){return _Trim(this)}

var _DataStrToArray = function(str,order){
	 order = typeof order == _UND?false:order;
	 var rtArr = {};
	 var orderarr = new Array();
	 var strarr = str.split("&");
	 if(strarr.length > 0){
		 for(var s=0,lens=strarr.length; s<lens; s++){
			 var atrrVal = strarr[s].split("=");
			 if(atrrVal.length == 2){
				 //atrrVal[1]=atrrVal[1].Replace("%2A","*").Replace("%2B","+").Replace("%2F","/").Replace("%40","@");
				 rtArr[atrrVal[0]] = rawunescape(atrrVal[1]);
				 if(order)orderarr[s] = atrrVal[0];
			 }
			 
		 }
		 
	 }
	 if(order){
		return {NewArray:rtArr,OrderArray:orderarr} 
	 }else{
	 return rtArr;
	 }
	 
 }
 
 var rawescape = function(str){
	 var esstr = escape(str);
	 esstr = esstr.Replace("*","%2A").Replace("+","%2B").Replace("/","%2F").Replace("@","%40");
	 return esstr;
 }
 
 var rawunescape = function(str){
	 str = str.Replace("%2A","*").Replace("%2B","+").Replace("%2F","/").Replace("%40","@").Replace("%C2%A0"," ");//%C2%A0
	 return unescape(str);
 }
//alert('Ajax');
var TL_AllAjaxObj = [];
 var Ajax = function(){
	 var aname = Math.random().toString();
	 while(typeof TL_AllAjaxObj[aname] != _UND){
		aname = Math.random().toString(); 
	 }
	 var timeout = null;
	 var conStr = "";
	 if(arguments.length == 1){ //if one argument is sent
		 var arg = arguments[0];
		 if(IsNumber(arg)){ //if number set as timeout
		   timeout = arg;
		 }else if(IsString(arg)){ //if string set as connection string
			conStr =  arg;
		 }
	 }else if(arguments.length >= 2){ //if arg is greater than 1
		 timeout = arguments[1].ToNumber(); //the second is timeout
		 conStr = arguments[0];//the first is connection string
	 }
     
	 this.ConnectionString = conStr;
	 this.name = aname;
	 TL_AllAjaxObj[aname] = this;
	this.req = null;
	this.url = '';
	this.method = "GET";
	this.HandleResp = null;
	this.HandleError = null;
	this.GetStr = null;
	this.readyState = null;
	this.responseText = '';
	this.status = null;
	this.statusText = '';
	this.asyn = true;
	this.format = 'text';
	this.postData = null;
	this.mtype = null;
	this.timeout = timeout; //time out time to trip up ajax call if time reach
	this.timeoutTimmer = null; //the timmer
	this.Param = null; //use to keep data set by user, that can be reuse
	//server con properties
	/*this.ServerUser = (IsSet(User))?User:"root";
	this.ServerPassw = (IsSet(Passw))?Passw:"";
	this.ServerHost = (IsSet(Host))?Host:"localhost";
	this.CurrDB = (IsSet(Db))?Db:"";*/
	//data base conection parameters;
	
	/*this.Authenticate = function(paramarray,obj){
		for(val in paramarray){
			
		}
	}*/
	
	//initialize the XMLHTTPRequest Object
	this.init = function(){
		if(!this.req){ //if req is null create a new xmlhttprequest
			if (window.XMLHttpRequest){
			   this.req = new window.XMLHttpRequest	
			}else{
			   if(window.ActiveXObject){
				  try{
					 this.req = new ActiveXObject("Msxml2.XMLHTTP"); 
				  }catch(err1){
					  try{
						  this.req = new ActiveXObject("Microsoft.XMLHTTP");
					  }catch(err2){
						  return false;
					  }
				  }
			   }
				
			}
	  
		}
		this.req.Owner = this;
	return this.req;
	};
   this.UserHandleProgress = null;
   this.UserCompleteHandler = null;
   this.UserErrorHandler = null;
   this.UserAbortHandler = null;
   this.SendData = new Array();
   this.URL = "";
	//New ajax upload/post accepting Files / objects as parameter working in HTML5
	this.Post = function(param){
		if(typeof param == _UND){
            alert('No parameter Found');return;
		}
        if(typeof param.Action != _UND){param.serverScript = param.Action}
		if(typeof param.serverScript == _UND || param.serverScript == ""){
			
         alert("No Server Script Found");return;
		}
		if(!this.init()){
			//alert(this.init()); //create the xmlhttprequest object
			alert('Cannot perform operation, unable to create required object');
			return;
		}

		var formdataObj = new FormData();
		if(typeof param.PostData != _UND){param.formData = param.PostData}
		var real = new Array();
		if(typeof param.formData == _UND){
			//if(typeof param.PostData == _UND){
               param.formData = "";
			//}else{
				// param.formData = param.PostData;
			//}
          
		}else{
			//alert( param.formData);
			dataarr = _DataStrToArray(param.formData,true);
			
			 real = dataarr.NewArray;
			
			var ord = dataarr.OrderArray;
			//alert(ord);
			for(var s=0,lens=ord.length; s<lens; s++){
				
				var key = ord[s];
				if(typeof real[key] == _UND){
					continue;
				}
				var value = real[key].Trim();
              if(value == "?" || unescape(value) == "?"){ //if file
				  //alert(key);
                  var file = _(key).files[0];
				  
				  formdataObj.append(key, file);
			  }else{
				  formdataObj.append(key, value);
			  }
			} 
			
	// alert(file.name+" | "+file.size+" | "+file.type);
	     
	    
		}
		if(typeof param.progressHandler != _UND){this.UserHandleProgress = param.progressHandler;}
		if(typeof param.OnProgress != _UND){this.UserHandleProgress = param.OnProgress;}
		if(typeof param.completeHandler != _UND){this.UserCompleteHandler = param.completeHandler;}
		if(typeof param.OnComplete != _UND){this.UserCompleteHandler = param.OnComplete;}
       if(typeof param.errorHandler != _UND){this.UserErrorHandler = param.errorHandler;}
	   if(typeof param.OnError != _UND){this.UserErrorHandler = param.OnError;}
	   if(typeof param.abortHandler != _UND){this.UserAbortHandler = param.abortHandler;}
	   if(typeof param.OnAbort != _UND){this.UserAbortHandler = param.OnAbort;}
	  // var ss = this.UserHandleProgress;
	  if(this.UserHandleProgress != null){
	  this.UserHandleProgress(0,param.serverScript,real); //make sure it start loading
	  }
		this.req.upload.addEventListener("progress", this.HandleProgress, false);
		this.req.upload.Owner = this.req; //keep the owner inside it
		//alert(this.HandleProgress);
	this.req.addEventListener("load", this.HandleComplete, false);
	this.req.addEventListener("error", this.HandleError, false);
	this.req.addEventListener("abort", this.HandleAbort, false);
	
	//param.progressHandlers(0,param.serverScript,real);
	this.SendData = real;
	this.URL = param.serverScript;
	
	this.req.open("POST", param.serverScript);
	
	this.req.send(formdataObj);
	//this.UserHandleProgress(0,param.serverScript,real);
	//alert(this.req);
	}

	//function to handle progress
	this.HandleProgress = function(event){
		//alert(event.target.Owner.Owner);
		if(event.target.Owner.Owner.UserHandleProgress != null)event.target.Owner.Owner.UserHandleProgress(event.loaded/event.total,event.target.Owner.Owner.URL,event.target.Owner.Owner.SendData);
	}
	//handle complete operation
	this.HandleComplete = function(event){if(event.target.Owner.UserCompleteHandler != null)event.target.Owner.UserCompleteHandler(event.target.responseText,event.target.Owner.URL,event.target.Owner.SendData);
	 	//event.target.Owner.UserCompleteHandler = null;
	}
	this.HandleError = function(event){if(event.target.Owner.UserErrorHandler != null)event.target.Owner.UserErrorHandler(event.target.statusText);}
	this.HandleAbort = function(event){if(event.target.Owner.UserAbortHandler != null)event.target.Owner.UserAbortHandler(event.target.statusText,event.target.Owner.URL,event.target.Owner.SendData);}

	
	this.FileExists = function(filename,func,requestfolder){
		requestfolder = typeof requestfolder == "undefined"?"":requestfolder;
		//alert(document.location);
		var librBase = typeof TaquaLoader.lb=='undefined' || TaquaLoader.lb==''?'TaquaLB':TaquaLoader.lb;
		this.PostResponse("filename="+escape(filename)+"&rf="+escape(requestfolder),librBase+"/Ajax/CGI/PHP/fileCheck.php",func,"text",func);
	}
	
	//send request
	this.SendReq = function(){
	
		if(!this.init()){
			//alert(this.init()); //create the xmlhttprequest object
			alert('Cannot perform operation, unable to create required object');
			return;
		}
		if(this.timeout != null){
			//alert(this.timeout);
          this.req.timeout = this.timeout; //set the timeout
		}
		
			//alert('inside-' + this.req);
		//process url
		//var rand = parseInt(Math.random() * 9999999999999999);
		var st = new Date;
		st = st.getTime();
		var inte = (this.GetStr)?'&':'?'; //if getstring is supplied concatinate rand else use only rand
		this.url += inte + 'rand=' + st ;
		//alert(this.url);
		//alert(this.GetStr);
		this.req.open(this.method, this.url, this.asyn); //open a server connection
		
		//Set the content type to form if request method is post
		if(this.method == 'POST'){
			this.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
		
		//overide the mimetype if set
		if(this.mtype){
			try{
				this.req.overrideMimeType(this.mtype);
			}catch(er){
				//cannot overide the mimetype
			}
		}

		
		var main = this; //lost - focus - problem put the current class/ object in a variable so as to use it in the another function

		this.req.onreadystatechange = function(res){ //function to execute when request state change
			//alert(this);
			var responce = null; //variable to hold the returned responce
			/*clearTimeout(main.timeoutTimmer);
				  main.timeoutTimmer = null;*/
			 if(main.req.readyState == 4){ //if request operation complete
				 switch (main.format){ //check format expected and intialize responce as required
					 case 'text':
					 responce = main.req.responseText;
					 break;
					 case 'xml':
					
					 responce = main.req.responseXML
					// alert(responce);
					 break;
					 case 'object':
					 responce = main.req;
					 break;
				 }
				 //alert(responce);
				 var datastr = (main.GetStr)?main.GetStr:(main.postData)?main.postData:"";
				 var dataArray = (datastr == "")?new Array():_DataStrToArray(datastr);
		       if(main.req.status >= 200 && main.req.status <= 299){ //if no http error
			      
				   main.HandleResp(responce,main.url,dataArray,main.req.status); //call the responce handler sending the responce as parameter
		        }else{
					//alert(main.req.status);
					var rstxt = main.req.statusText.Trim() == ""?"INTERNAL INTERUPT <br /> Check your connection and Try Again <br /> If error continues contact the support team":main.req.statusText;
					if(main.HandleError){ //if there is user specified error Handler Use it
						main.HandleError(rstxt,main.url,dataArray);
					}else{
						main.HandleErr(rstxt,main.url,dataArray); //error handler(in built)
					}
			     
				 
		        }
				
	          }
		};
		this.req.ontimeout = this.PerformTimeout;
		this.req.send(this.postData);
	};
	
	//function to set the mtype/ header
	this.setmtype = function(mimetype){
		this.mtype = mimetype;
	}
	
	//Handle error
	this.HandleErr = function(responseT){
		var errorwin;
		try{
		/*errorwin = window.open('','errorWindow');
		errorwin.document.body.innerHTML = this.req.statusText;*/
		if(responseT != "#"){
			alert('Error - ' + responseT);
		}else{
			alert('Request Timeout, Check your Network Connection');
		}
		}catch(e){
			alert('Error occured, Details cannot be displayed');
		}
		//this.abort() //abort the entire request
	}
	
	//Abort the request
	this.abort = function(){
		if(this.req){
		  this.req.onreadystatechange = function() {};
		  this.req.abort();
		  this.req = null;
		}
		
	}

	this.Abort = this.abort;
	
	//Alow user to call the retuest
	this.GetResponse = function(GetStr,url,handler,format,ErrHandler){
		this.GetStr = GetStr;
		if(GetStr == null || GetStr == ''){
			this.GetStr = null;	
		}else{
			url += '?' + GetStr;
		}
		/*if(!Null(this.timeout)){
			this.timeoutTimmer = setTimeout("TL_AllAjaxObj['"+this.name+"'].PerformTimeout()",this.timeout);
		}*/
		this.HandleError = ErrHandler || null;
		this.url = url;
		this.HandleResp = handler;
		this.format = format || 'text';
		this.SendReq(); //send the request
	}
	
	//function to perform time out
	this.PerformTimeout = function(){
	//function to handle timeout
	}
	
	this.PostResponse = function(postData,url,handler,format,ErrHandler){
		
		this.url = url;
		this.HandleResp = handler;
		this.HandleError = ErrHandler || null;
		this.format = format || 'text';
		this.method = 'POST';
		this.postData = postData;
		
		this.SendReq();
		/*if(!Null(this.timeout)){
			this.timeoutTimmer = setTimeout("TL_AllAjaxObj['"+this.name+"'].PerformTimeout()",this.timeout);
		} */
	}
	

	
 }
 


//New Ajax Structure
/*
         Ajax.Post({
				Action:"",
				PostData:"",
				OnProgress:function(delta){
                   delta = Math.floor(delta*100);
					if(delta < 100){
						MessageBox.Progress.HintTo(delta,null,"Loading",'Ajax.abort()');
					}else{
						MessageBox.Progress.HintTo(-1,"Loading ...","Loading",'Ajax.abort()'); 
					}
				},
				OnComplete:function(res,url,param){
                  MessageBox.CloseHint();

				},
				OnAbort:function(){

				},
				OnError:function(res){
                  MessageBox.CloseHint();
				  
				}
			});
*/