// Taqua Ajax
_d = (typeof _d=="undefined")?document:_d;
//alert('Ajax');
var TL_AllAjaxObj = [];
/*  var Ajax = function(){
	 var aname = Math.random().toString();
	 while(IsSet(TL_AllAjaxObj[aname])){
		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
	
	
	//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){
			//for eduporta only
			
			param.serverScript = param.Action
			if(typeof configdata != "undefined"){
				//param.serverScript = 
			}
		}
		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{
			//For eduporta only
			if(typeof configdata != "undefined"){
				//param.formData += "&SubDir="+encodeURIComponent(configdata['SubDir'])
			}
			//alert( param.formData);
			dataarr = param.formData.ToDataArray(true);
			
			 real = dataarr.NewArray;
			
			var ord = dataarr.OrderArray;
			//alert(ord);
			for(var s=0; s<ord.length; 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
			
			 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():datastr.ToDataArray();
		       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{
	
		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 || empty(GetStr)){
			this.GetStr = null;	
		}else{
			url += '?' + GetStr;
		}
		
		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();
		
	}
	this.ServerTFunc = null;
	this.containers = null;
	this.format = ""
	this.DTTimmer = null;
	this.StartAutoDateTime = function(format,ids){
		//this.ServerTFunc = func;
		//this.ServerTFunc = func;
		this.containers = ids;
	   this.formatr = format;
	   this.DTTimmer = setInterval("TL_AllAjaxObj['"+this.name+"'].ServerDTStart()",1000);
	}
	
	
	
	this.ServerDTStart = function(){
		this.abort();
		var librBase = typeof TaquaLoader.lb=='undefined' || TaquaLoader.lb==''?'TaquaLB':TaquaLoader.lb;
		var ajaxpg = librBase+"/Ajax/CGI/PHP/st.php";
		var pstdata = "fmt="+escape(this.formatr);
		//alert(pstdata);
		this.PostResponse(pstdata,ajaxpg,this.HandlerDT,"text",function(){});
	}
	
	this.StopAutoDateTime = function(){
		clearInterval(this.DTTimmer);
	}
	
	//handler for the timmerobject ajax responces
	this.HandlerDT = function(res){
		if(IsNull(this.containers)){this.StopAutoDateTime(); return} //if no container set to display the date time, Stop the timmer and return
		if(IsFunction(this.containers)){
			this.containers(res);
		}else{
		this.containers.Text(res);
		}
		//this.DisplayDT(res,this.containers);
		
	}
	
	
	//load from db
	this.query = function (q,handler){
		var librBase = typeof TaquaLoader.lb=='undefined' || TaquaLoader.lb==''?'TaquaLB':TaquaLoader.lb;
		if(q.Trim() == ""){
			return;
		}else{
			//alert(this.ConnectionString);
			this.PostResponse("connStr="+escape(this.ConnectionString)+"&query="+escape(q),librBase+"/Ajax/CGI/PHP/query.php",handler,"xml",function(q){});
		}
	}
	
	
	
 } */
 
 //function to check if object(xml) has error
 var _GetError = function(xml){
	 var err = xml.getElementsByTagName("errorName"); //get the errorName tag
	 if(err.length > 0){ //if it exist
		 return err[0].childNodes[0].nodeValue //return the error message
	 }else{
		return null;  //if node or tag not found, i.e there is no error, return null
	 }
 }
 
 //perform an action on each row of the record
 var _EachRow = function(xml,func){
	 var rows = xml.getElementsByTagName("row"); //get all the rows
	 if(rows.length > 0){ //if rows are found
		 for(var r=0,lenr=rows.length; r<lenr; r++){ //move through individual rows and run supplied function, sending the key(index) and the row childNodes(columns)
			 func(r,rows[r].childNodes); //run the function, supplying the key and the row childNodes.
			 //Note: the function supplied during call must have the same signature, (key and row childNodes parameters)
		 //return [0].nodeValue
		 }
	 }else{
		return null;  //if no row found return null
		//document.getElementById().tagName
	 }
 }
 
 //get the column value based on the column index or tagName( Field Name)
 var _Column = function(row,field){
	 if(IsString(field)){ //if field name supplied
		 for(var s=0,lens=row.length; s < lens ; s++){ //loop through and get the value of column whose tagname is the field name supplied
			 if(row[s].tagName.toUpperCase() == field.toUpperCase()){
				 return (typeof row[s] != "undefined")?(typeof row[s].childNodes[0] != "undefined")?row[s].childNodes[0].nodeValue:"":null;
			 }
		 }
	 }else if(IsNumber(field)){ //if index supplied
		 return (typeof row[field] != "undefined")?(typeof row[field].childNodes[0] != "undefined")?row[field].childNodes[0].nodeValue:"":null; //get the value of the column base on the column index
	 }
	 return null; //if invalid field name sent return null;
 }
 
 //get the rows and return as an array of rows column columns
 var _Rows = function(xml){
	 rtd = []; //an empty array to hold the individual rows child nodes(columns)
	 var rows = xml.getElementsByTagName("row"); //get all rows
	 if(rows.length > 0){
		  var rtd = new Array(rows.length); //re-create the array to be the total row lenght
		 for(var s=0,lens=rows.length; s<lens ; s++){ //loop through all rows and add childnodes (columns) to the array
			 rtd[s] = rows[s].childNodes;
		 }
	 }
	 return rtd; //return the array
 }
 
 //return the total number of rows found
 var _NumRows = function(xml){
	 var nrows = xml.getElementsByTagName("_total")[0].childNodes[0].nodeValue;
	 return nrows;
 }
 

 
 //object to send sms
var SMS = new function(){

	this.url = "http://www.bulksmsnigeria.net/components/com_spc/smsapi.php";
	this.user = "";
	this.pw = "";
	this.sender = "";
	//GetResponse = function(GetStr,url,handler,format,ErrHandler)
	//send
	this.Send = function(phone,msg){
		//alert('sms')
		Login.Ajax.GetResponse("username="+escape(SMS.user)+"&password="+escape(SMS.pw)+"&sender=UNIUYO&recipient="+phone+"&message="+msg,SMS.url,function(res){},"text",function(res){});
		
	}
}
 
 CountDowns = new Array();
 var CountDown = function(){
	 this.endDate = null;
	 this.countFunc = null;
	 this.endFunc = null;
	 this.Ajax = new Ajax();
	 this.LoopTimmer = null;
	 this.name = "cd"+Math.random();
	CountDowns[this.name] = this;
	//start countdown
	this.Start = function(endDate, countFunc, endFunc){
		//endDate {H:?,I:?,S:?,M:?,D:?,Y:?}
		
		if(typeof endDate != "undefined"){
			this.endDate = endDate;
			this.countFunc = (typeof countFunc != "undefined")?countFunc:function(){};
			this.endFunc = (typeof endFunc != "undefined")?endFunc:function(){};
			
			//this.DTTimmer = setInterval("TL_AllAjaxObj['"+this.name+"'].ServerDTStart()",1000);
			this.LoopTimmer = setInterval("CountDowns['"+this.name+"'].CountDownFunc()",1000);
		}
		
	}
	
	//countdown loop function
	this.CountDownFunc = function(dir){
		//alert('enter');
		var librBase = typeof TaquaLoader.lb=='undefined' || TaquaLoader.lb==''?'TaquaLB':TaquaLoader.lb;
		var h = this.endDate.H || 0;
			var i = this.endDate.I || 0;
			var s = this.endDate.S || 0;
			var m = this.endDate.M || 0;
			var d = this.endDate.D || 0;
			var y = this.endDate.Y || 0;
			if(h > 24 || i > 60 || s > 60 || m > 12 || d > 31){
				return;
			}
		this.Ajax.abort();
		var ajaxpg = librBase+"/Ajax/CGI/PHP/countdown.php";
		var pstdata = "h="+h+"&i="+i+"&s="+s+"&m="+m+"&d="+d+"&y="+y+"&name="+this.name;
		//alert(pstdata);
		this.Ajax.PostResponse(pstdata,ajaxpg,this.Handler,"text",null);
	}
	
	//countdown handler 
	this.Handler = function(res,url,param){
		//alert(res);
		if(res.Trim() == "#"){
			CountDowns[param['name']].endFunc();
			CountDowns[param['name']].LoopTimmer = null;
			clearInterval(CountDowns[param['name']].LoopTimmer);
		}else{
			CountDowns[param['name']].countFunc(res);
		}
	}
	 
	 
 }
 
 
 Object.prototype.GetError = function(){return _GetError(this);}
 Object.prototype.EachRow = function(func){_EachRow(this,func);}
 Object.prototype.Column = function(field){return _Column(this,field);}
  Object.prototype.Rows = function(){return _Rows(this);}
  Object.prototype.NumRows = function(){return _NumRows(this)}
//yom = "aa";

//htmlLoader object
var htmlLoader = new function(){
	this.funcArray = new Array();
  this.LoadHTML = function(obj,url,Func,errorHandler,append){
	  append = typeof append==_UND?0:1; //help to indicate if the loaded response is to be added to existing or overide
	  if(typeof obj == _UND)return;
	  obj = _(obj); //get the object(s)
	  if(obj != null){
	  if(typeof url == _UND){
		  if(IsArray(obj)){
			  var aobj = htmlLoader.FormInnerHTMLs(obj);
			  return aobj;
		  }else{
		   return obj.innerHTML;
		  }
	  }
		  if(IsArray(obj)){
			  //loop through all the object of the array and perform the load operation on each
			  for(var s = 0,lens=obj.length; s < lens; s++){
				  var nobj = obj[s];
				  htmlLoader.LoadHTML(nobj,url,Func,errorHandler);
			  }
		  }else{
			  //alert(typeof obj.id);
			  //perform the loading operation
			  //generate obj id if not exist to be passed as parameter 
			  if(typeof obj.id == _UND || obj.id.Trim() == ""){//if not exist
			  var currdat = new Date();
				  var genid = "id"+currdat.getTime(); //generate
				  obj.id = genid; //set object id
			  }
			  
			  //form ajax post variables
			  //get the url data
			  var urlResolved = URLs.Resolve(url); //breakdown url
			  var urldata = (urlResolved.Data.Trim() == "")?"":"&"+urlResolved.Data;
			  var realurl = urlResolved.Url; //get url only
			  var data = "append="+append+"&obj_id="+obj.id+urldata; //form post data
			  //store the end function, so that it can be accessible later in the main handler
			  htmlLoader.funcArray[obj.id] = (typeof Func == _UND)?null:Func;
			  errorHandler = (typeof errorHandler == _UND)?htmlLoader.LoaderHandler:errorHandler;
			  //create a new ajax object
			  var Ajaxs = new Ajax(1*60*1000);
			  //call the post operation
			  Ajaxs.PostResponse(data,realurl,htmlLoader.LoaderHandler,"text",errorHandler);
			  return Ajaxs;
		  }
		  
	  }
	  
  }
  //main loading handler
  this.LoaderHandler = function(res,url,param){
	  //alert(res);
	  //get the reciving objects id from param array
	  if(typeof param["obj_id"] != _UND){
	    var id = param["obj_id"];
		//alert(_(id).innerHTML);
		var append = param["append"].ToNumber();
		if(append==1){_(id).insertAdjacentHTML('beforeend',res)}else{_(id).innerHTML = res}
		
		if(htmlLoader.funcArray[id] != null){
			htmlLoader.funcArray[id](_(id),url,param,res);
		}
	  }
	  
	  
  }
  
  //function to form arrays of innerHTML of array of objects
  this.FormInnerHTMLs = function(arrobj){
	  var arr = Array();
	  if(IsArray(arrobj)){
		  for(var s=0,lens=arrobj.length; s<lens; s++){
			  var obj= arrobj[s];
			  var innHTML = htmlLoader.FormInnerHTMLs(obj);
			  if(IsArray(innHTML)){
				 arr = arr.concat(innHTML);
			  }else{
				  arr.push(innHTML);
			  }
		  }
		  return arr;
	  }else{
		 var innHTML =  _(arrobj).innerHTML;
		 return innHTML;
	  }
  }

}

//create prototypes for html loader
String.prototype.HTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(String(this),url,Func,errorFunc)};
Object.prototype.HTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(this,url,Func,errorFunc)};
Array.prototype.HTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(this,url,Func,errorFunc)};

//append
String.prototype.AppendHTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(String(this),url,Func,errorFunc,1)};
Object.prototype.AppendHTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(this,url,Func,errorFunc,1)};
Array.prototype.AppendHTML = function(url,Func,errorFunc){return htmlLoader.LoadHTML(this,url,Func,errorFunc,1)};

//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();
				  
				}
			});
*/