/*This function is constructor for AJAX class. It takes followng paramaters
1. pstrURL - URL to which data is needed to be posted
2. pblnNoCache - Can take true/false. If this value is true then URL will prefix with
current date time so that page will not get loaded from cache.
3. pstrElement - HTML object where loading image is needed to be shown
4. pstrLoadingImage - Path of loading effect image.
*/
function AJAXRequest(pstrURL,pblnNoCache,pstrElement,pstrLoadingImage)
{
	this.objHTTP = this.GetHTTPObject();
	this.URL = pstrURL;
	if(pstrElement == null || pstrElement == "")
	{
		pstrElement = document.getElementById("divBody");
	}
	else
	{
		pstrElement = document.getElementById(pstrElement);
	}

	this.objElement = pstrElement;
	
	if(pstrLoadingImage == null || pstrLoadingImage == "")
	{
		pstrLoadingImage = "<img src=\"indicator.gif\">";
	}
	else
	{
		pstrLoadingImage = "<img src=\"" + pstrLoadingImage + "\">";
	}
	
	if(pblnNoCache == null)
	{
		this.NoCache = true;
	}
	else
	{
		this.NoCache = pblnNoCache;
	}
	
	this.LoadingImage = pstrLoadingImage
	this.objTimer = null;
	this.ResponseText = "";
	this.JavaScript = "";
	this.Error = false;
	this.ErrorMessage = "Couldnot able to connect server. Try again later";
}	

/*This function will create XMLHTTP object needed for AJAX*/
AJAXRequest.prototype.GetHTTPObject = function()
{
	if(window.XMLHttpRequest) 
	{
		var objHTTP;
		try 
		{
			objHTTP = new XMLHttpRequest();
		} 
		catch(objException)
		{
			objHTTP = null;
		}

	// branch for IE/Windows ActiveX version
	} 
	else if(window.ActiveXObject) 
	{
		try 
		{
			objHTTP = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch(objException) 
		{
			try 
			{
				objHTTP = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch(objException) 
			{
				objHTTP = null;
			}
		}
	}
	
	return objHTTP;
}

/* This function will execute AJAX request. This function takes following parameters
1. pstrMethod - This can be "GET" or "POST"
2. pblnAutomate - if you want that whole form is needed to be posted then set this value to "true" otherwise "false"
3. pstrData - Data which needed to be posted to URL.
4. pstrFormName - Optional parameter. It required only if pblnAutomate is set to true.
*/
AJAXRequest.prototype.PerformRequest = function(pstrMethod,pblnAutomate,pstrData,pstrFormName)
{
	if(pblnAutomate == true)
	{
		pstrData = this.BuildRequst(pstrFormName);
	}
	this.objElement.innerHTML = this.LoadingImage;
	this.SendRequest(pstrMethod,pstrData);
}

/* This function will actually sent data posted page
1. pstrMethod - This can be "GET" or "POST"
2. pstrData - Data which needed to be posted to URL.
*/
AJAXRequest.prototype.SendRequest = function(pstrMethod,pstrData)
{
	clearTimeout(this.objTimer);
	
	if(this.NoCache == true)
	{
		var intIndex = this.URL.indexOf("?");
		if(intIndex > 0)
		{
			this.URL += "&q_timestamp=" + this.GenerateTimeStamp();
		}
		else
		{
			this.URL += "?q_timestamp=" + this.GenerateTimeStamp();

		}
	}
	
	this.objHTTP.open(pstrMethod,this.URL,false);
	
	if(pstrMethod.toLowerCase() == "post")
	{
		this.objHTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	this.objHTTP.send(pstrData);
	this.objHTTP.onreadystatechange = function(){ this.ReadyStateChange(); };
	var strResult = this.objHTTP.responseText;
	this.GetAJAXResponse(strResult);
}

/* Add your logic in this function for showing execute any logic before AJAX page get loaded*/
AJAXRequest.prototype.OnLoading = function()
{
  this.objElement.innerHTML = this.LoadingImage;
}

/* Add your logic in this function for showing execute any logic on various states of AJAX operation*/
AJAXRequest.prototype.ReadyStateChange = function ()
{
	if(this.XmlHttp.readyState == 1 )
	{
		this.OnLoading();

	}
  	else if(this.objHTTP.readyState == 4 )
	{
		if(this.objHTTP.status == 0 )
		{
		}
		else if(this.objHTTP.status == 200 && this.objHTTP.statusText == "OK")
		{
		}
		else
		{
			alert("Could not able to connect to server. Try Again Latter");
			this.Error = true;
		}
        
	}
}

/* This function will seperate HTML content and validatio JavaScript Code. It required following parameter
1. pstrData - This will contain value returned by AJAX request
*/
AJAXRequest.prototype.GetAJAXResponse = function(pstrData)
{
	var arrSplitData = pstrData.split("<!--Validation-->");
	
	if(arrSplitData.length > 1)
	{
		var objRegEx = new RegExp ("<script language='JavaScript' type='text/javascript'>", "gi") ;
		arrSplitData[1] = arrSplitData[1].replace(objRegEx,"");
		objRegEx = new RegExp ("<\/script>", "gi") ;
		arrSplitData[1] = arrSplitData[1].replace(objRegEx,"");
		
		this.JavaScript = arrSplitData[1];
	}
	this.ResponseText = arrSplitData[0];
		
}

/* This function will add JavaScrit logic in runtime. It required following parameters
1. pstrJavaScript - If supplied then it will add passed JavaScript to page 
otherwise it will add JavaScript return by AJAx request.
*/
AJAXRequest.prototype.RegisterJavaScript = function(pstrJavaScript)
{
	var objScript = document.createElement("SCRIPT");
	objScript.language="javascript";
	
	if(pstrJavaScript == null)
	{
		objScript.text =  this.JavaScript;
	}
	else
	{
		objScript.text = pstrJavaScript;
	}
	objScript.type = 'text/javascript';
	var objHead = document.getElementsByTagName("head")[0];
	objHead.appendChild(objScript);
}

/* This function will get all values from form and format values in query string format
This function take following parameters
1. pstrFormName - This will be form name whose elemets are needed to be converted into
query string
*/
AJAXRequest.prototype.BuildRequst = function(pstrFormName)
{
	var objForm = eval("document." + pstrFormName +".elements");
	var strPostData = ""
	if(objForm != null)
	{
		for(var intCounter = 0; intCounter < objForm.length; intCounter++)
		{
			
			//Excluding viewstate variable
			if(objForm[intCounter].name.toLowerCase() !="__viewstate")
			{
			
				//Checking type of control
				switch (objForm[intCounter].type)
				{
					case "select-one":
						strPostData += objForm[intCounter].name + "=" + objForm[intCounter].options[objForm[intCounter].selectedIndex].value + "&";
						break;
					case "text" :
						strPostData += objForm[intCounter].name + "=" + objForm[intCounter].value + "&";
						break;
					case "textarea" :
						strPostData += objForm[intCounter].name + "=" + objForm[intCounter].value + "&";
						break;
					default :
						strPostData += objForm[intCounter].name + "=" + objForm[intCounter].value + "&";
						break;
				}
			}
		}
	}
	if(strPostData.length > 0)
	{
		strPostData = strPostData.substring(0,strPostData.length - 1);
	}
	return strPostData;
}

/* This function will get return time stamp value*/
AJAXRequest.prototype.GenerateTimeStamp = function()
{
	var objDate = new Date();
	var strDate = objDate.getDate() + objDate.getMonth() + objDate.getFullYear() + objDate.getHours() + objDate.getMinutes() + objDate.getSeconds() + objDate.getMilliseconds();
	
	return strDate;
}

/*------------Sample Code-----------------
function GetAJAXPage()
{
	var objAJAX = new AJAXRequest("http://localhost/TestApplication/TestManager/Validation.aspx","divForm");	
	objAJAX.PerformRequest("GET",false,"","");
	if(objAJAX.Error == true)
	{
		alert(objAJAX.ErrorMessage);
	}
	else
	{
		document.getElementById("divForm").innerHTML = objAJAX.ResponseText;
		objAJAX.RegisterJavaScript();
		objAJAX.RegisterJavaScript("function Validate(){return eval('frmvalidator.validateAll()');}");
	}
}
----------------------------------------*/