//================================================
/*
http://www.lonssx.net
Juan Garcia
General JS Library
2010-07-24
*/
//================================================

//General Variables
var srvname = "http://www.lonssx.net/";
//var srvname = "http://casinfolap007/lonssx/";
var ajaxObj = new jgAjax("gralObj", "", "", "", "POST");

//General Functions

/*AJAX Object Library*/
function jgAjax(reqName, sendUrl, sendMsg, cbackFx, sendMethod)
{
	var infoMsg;
	var xmlHttp;
	var ajaxResult = "none";	
	var isAborted = false;

	//Configuration Parameters
	//Add the ResponseId, WaitingMessage, ProcessingType (wait, cancel, warn)
	//wait = put new requests in a queue
	//cancel = cancel actual request and put the new request
	//warn = pops a message to the user to select if the actual request maybe cancelled and process the new request, queue the new request or not cancel actual request.
	this.name = reqName;
	this.id = reqName;	//For Now it generates the same value as the name
	this.url = sendUrl;
	this.msg = sendMsg;
	this.cback = cbackFx;
	this.astatus = "idle";
	this.method = sendMethod.toUpperCase();
		
	//Properties for automated answers on the page.
	//If a callback is defined, this option will be ignored
	//If this variables are defined the answer in getResult will also be palced but the status will change from processing to idle before this method is called
	//Defines the position in which the answer should be place in the report
	this.resPos = "none";
	//Define a custom message while the request is being retrieved. If waitMSgPos is not defined, this wont be used
	this.waitMsg = '<p align="center" style="color:#333333; font-family:verdana; font-size:10 px;">Searching requested data...</p>';		
	//Defines the place in which the default or custome message should appear.
	this.waitMsgPos = "none";	
	
	//Handling error properties
	//Using the error manager is disabled by default, write on to make it work
	this.errMgr = "Off";
	
	//Set a new request parameters, overriding existing
	this.sendParams = function(nReqName, nSendUrl, nSendMsg, nCbackFx, nSendMethod)
					  {
						this.name = nReqName;
						this.id = nReqName;	//For Now it generates the same value as the name
						this.url = nSendUrl;
						this.msg = nSendMsg;
						this.cback = nCbackFx;
						this.astatus = "idle";
						this.method = nSendMethod.toUpperCase();
					  }
					  		
	this.info = function()
				{
					infoMsg = "Process Name: " + this.name + "\n";
					infoMsg = infoMsg + "Process ID: " + this.id + "\n";
					infoMsg = infoMsg + "Send URL: " + this.url + "\n";
					infoMsg = infoMsg + "Send Msg: " + this.msg + "\n";
					infoMsg = infoMsg + "Call Back Defined: " + this.cback + "\n";
					infoMsg = infoMsg + "Send Method: " + this.method + "\n";
					infoMsg = infoMsg + "Object Status: " + this.astatus + "\n";
					infoMsg = infoMsg + "Response position: " + this.resPos + "\n";
					infoMsg = infoMsg + "Waiting Request Message: " + this.waitMsg + "\n";
					infoMsg = infoMsg + "Waiting Request Message Position: " + this.waitMsgPos + "\n";
					
					alert(infoMsg);
				}
				
	//Function to send Data
	this.sendRequest = function ()
						{
								if(this.astatus=="idle")
								{
									var type = "default";
									var me = this;
									
									//check if cBack is defined, if not set answer to the result variable
									if(this.cback!="")
									{
										type = this.cback;
									}
							
									//alert(msg);
							
									xmlHttp=getAjax();
							
									if (xmlHttp==null)
									{
											alert("Your Browser don't support AJAX!");
											return;
									}
			
									//Check and send Ajax request
									try
									{
											xmlHttp.onreadystatechange = function () {stateChanged(type, me);};
											xmlHttp.open(this.method,this.url,true);
											xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
											xmlHttp.send(this.msg);
											this.astatus = "processing";
											
											if(this.waitMsgPos!="none" && this.waitMsgPos!="")
											{
												document.getElementById(this.waitMsgPos).innerHTML = this.waitMsg;
											}
									}
									catch(e)
									{
											alert("Process can't be completed due to: " + e.description);
											return;
									}
								}
						}
	
	//Function to cancel the ajax request
	this.cancel = function()
					{
						this.astatus = "idle";
						ajaxResult = "Cancelled!"
						isAborted = true;
						xmlHttp.abort();
						//alert("Request Cancelled");
					}

	//Function to get Ajax result
	this.getResult = function()
					{		
						//alert(this.astatus);
						this.astatus = "idle";
						return ajaxResult;
					}
	
	//Function to verify if Ajax is available
	function getAjax()
	{
	  try
		{
			// Firefox, Opera 8.0+, Safari
					xmlHttp=new XMLHttpRequest();
			}
	  catch (e)
		{    // Internet Explorer
			try
		  {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      }
		catch (e)
		  {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");   }
			 }
			 return xmlHttp;
	}
			
	//Funcion that process Ajax Result
	function stateChanged(cback, props)
	{
			var strRes;
						
			if(props.waitMsgPos=="none" && props.waitMsgPos=="")
			{
				document.getElementById(props.waitMsgPos).inerHTML = "";
			}

			//clipboardData.setData("Text", xmlHttp.responseText);
			//alert("Copied");

			if(xmlHttp.readyState==4 && xmlHttp.status==200)
			{
				strRes = xmlHttp.responseText;
												
				props.astatus = "ok";
				
				if(cback=="default")
				{
					ajaxResult = strRes;
					
					if(props.resPos!="none" && props.resPos!="")
					{
						document.getElementById(props.resPos).innerHTML = props.getResult();
					}
				}
				else
				{
					setTimeout(cback + "('"+ escape(strRes) +"')", 1);
				}
				
			}
			else if(xmlHttp.readyState==4 && xmlHttp.status!=200)
			{
				strRes = xmlHttp.responseText;
				
				//Check if the request was aborted
				if(isAborted==false)
				{
					ajaxResult = "There was an error with the server, Please try again. If the problem persist contact your System Administrator";
				
					props.astatus = "errors";
					
					//Checks if the error manager is used or activated			
					if(props.errMgr.toLowerCase()=="on")
					{
						errHandle("Page cannot be found!", strRes);
					}
					else
					{
						//If resPos variable is set, then shows the answer
						if(props.resPos!="none" && props.resPos!="")
						{
							document.getElementById(props.resPos).innerHTML = props.getResult();
						}
					}
				}
				else
				{
					//If resPos variable is set, then shows the answer
					if(props.resPos!="none" && props.resPos!="")
					{
						document.getElementById(props.resPos).innerHTML = props.getResult();
					}
				
					isAborted = false;
				}	
			}
	}		
}

//Funciones para el manejo de errores
function errHandle(errText, errData)
{
	//intSurvRrefresh = setInterval("getSurveillanceData()", survRefreshRate);
	
	 //style="height:60px; overflow:auto;
	
	errData = escape(errData);
	
	document.getElementById("errManager").style.display = "block";
	
	document.getElementById("errorReport").style.height = "60px";
	document.getElementById("errorReport").style.overflow = "auto";
	document.getElementById("errorReport").innerHTML = '<br>' + errCount + '. ' + errText + '<a href="javascript:;" onclick="javascript:clipboardData.setData(\'Text\', unescape(\'' + errData + '\'));" class="topMnu">(copy to clipboard)</a></li>' + document.getElementById("errorReport").innerHTML;
	
	errCount = errCount + 1;
}

//Funcion para limpiar el panel de errores
function errClear()
{
	document.getElementById("errManager").style.display = "none";
	
	errCount = 1;
	
	document.getElementById("errorReport").style.height = "0px";
	document.getElementById("errorReport").style.overflow = "auto";
	document.getElementById("errorReport").innerHTML = "";	
}
/*AJAX Object library ends*/

/*String and characters processing functions*/
//Function to join an array into a string and back
function dataStreamFormat(rcvData, rcvFormat, rcvOutFormat)
{	
	//Converting everything to a string
	var rcvDataConvert = "";
	var dataConverted = "";
	
	switch(rcvFormat.toLowerCase())
	{
		case "string":
			rcvDataConvert = rcvData;
		break;
		
		case "array":
			for(key in rcvData)
			{
				rcvDataConvert = rcvDataConvert + key + "=" + rcvData[key] + "&";
			}
			
			if(rcvDataConvert.length>0)
			{
				rcvDataConvert = rcvDataConvert.substr(0, rcvDataConvert.length - 1);
			}
		break;
		
		case "xml":
		
		break;
	}
	
	//Converting the $rcvDataConvert to the output format
	switch(rcvOutFormat.toLowerCase())
	{
		case "string":
			dataConverted = rcvDataConvert;
		break;
		
		case "array": 
			dataConverted = new Array();
			divStr = rcvDataConvert.split("&");
			
			for(ic=0;ic<divStr.length;ic++)
			{
				divVar = divStr[ic].split("=");				
				dataConverted[divVar[0]] = divVar[1];
			}
		break;
		
		case "xml":
		
		break;
	}
	
	return dataConverted;
}

/*String and characters processing functions*/

/*Fx Functions*/
//Function that switch state on a tab between visible to hide
function switchTabState(tabId)
{
	var tabObj = document.getElementById(tabId);
	
	switch(tabObj.style.display)
	{
		case "block":
			tabObj.style.display = "none";
		break;
		
		case "none":
			tabObj.style.display = "block";
		break;
	}
	
}
/*Fx Functions*/
