// filename    : ajaxLibrary.js
// description : ajax request functions
// namespace   : all functions and variables are prefixed "ajax_"
// author      : Sachin Korgaonkar
// email       : sachinkorgaonkar@gmail.com

//Ajax library information
var ajax_release_version = "1.0.0";
var ajax_release_date    = "2007-03-15";
var ajax_developer = "sachin korgaonkar"
var ajax_developer_email = "sachin.korgaonkar@cyquator.esselgroup.com"

//constants
var ajax_requestType_null = 0;
var ajax_requestType_string = 1;

var ajax_statusCode_null = 0;
var ajax_statusCode_ok = 200;
var ajax_statusCode_error = 500;
var ajax_statusCode_user = 600;

var objHTTP = getHTTPObject();
var ControlId=new String("");
var URL=new String("");
var DataProcessingMethod = "";


//This function will return the XMLHTTP Object for MSIE, Netscape, Mozilla and Opera Browsers
function getHTTPObject()
{
	var objXMLHTTP;
	try
	{
		objXMLHTTP=new ActiveXObject("Msxml2.XMLHTTP"); //IE5/6
	}
	catch(e)
	{
		try
		{
			objXMLHTTP=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e1)
		{
			objXMLHTTP=null;
		}
	}
	if (!objXMLHTTP && typeof XMLHttpRequest!='undefined') //FF,NS,OP,IE7
	{
		try
		{
			objXMLHTTP=new XMLHttpRequest();
		}
		catch(e)
		{
			objXMLHTTP=false;
		}
	}
	return objXMLHTTP;
}


function ajax_generateURL(QueryStr)
{
    //alert("current " + QueryStr)
	var strQueryString=new String(QueryStr);
	while(strQueryString.indexOf(",")>0)
		strQueryString=strQueryString.replace(",","&");
	return strQueryString ;
}

//Method called by User to
//Parameters
//strControId = name of the div to print the information eg. divMessage
//requestURL = url to get the information from eg. testAjax.aspx
//isDataNeedsProcessing = 0/1 if data needs to process, pass the process method
//I will hardcode this method for User 
//untill I didnot get any function to call Javascript method dynamically like Call MethodName

function ajax_CreateRequest(strControlId,requestURL,dataProcessingMethod)
{
    //alert(ControlId + "/" + ajax_generateURL(requestURL+",Rand="+Math.random()))
	ControlId = strControlId;
	DataProcessingMethod = dataProcessingMethod;
	//alert("ex" +DataProcessingMethod)
	objHTTP.open("GET",ajax_generateURL(requestURL+"&Rand="+Math.random()),true);
	objHTTP.onreadystatechange=ajax_RequestResponse;
	objHTTP.send(null);
}

function ajax_RequestResponse()
{
	if(objHTTP.readyState==4)
	{
		HTTPResponse(objHTTP.responseText);
	}
}

//Common functions to cleanup div element before putting data into it.
function ClearAllElement(drpId)
{
	document.getElementById(drpId).options.length=0;
}
function EnableElement(drpId)
{
	document.getElementById(drpId).disabled='';
}
function DisableElement(drpId)
{
	document.getElementById(drpId).disabled='disabled';
}
function ClearDiv(divId)
{
	document.getElementById(divId).innerHTML="";
}



//Do the actual calculation
//Need to cleanup and make it generic function
//Added in Todo list

function HTTPResponse (strHTTPResult) 
{
    
    //alert(strHTTPResult)
    
    if(DataProcessingMethod == ""){
        document.getElementById(ControlId).innerHTML = strHTTPResult;
    }else {
        alert("ex" +DataProcessingMethod)    
       //User Need to create this method using their function to process data 
        ProcessOutputData(strHTTPResult);
    }
}
/*
function HTTPResponse(strHTTPResult)
{
	//alert(strHTTPResult);
	if(strHTTPResult!="")
	{
		var arrResponse=new Array();
		arrResponse=strHTTPResult.split("|");
		for(var i=0;i<arrResponse.length;i++)
		{
			arrResponse[i]=arrResponse[i].toString().split("=");
		}
		if(ControlId.toLowerCase()=="divshowtiming")
		{
			var divShowTimings=new String("");
			divShowTimings="<table class='showtimings01' border='0' cellspacing='0' cellpadding='0'>";
			for(var i=0;i<arrResponse.length;i=i+2)
			{
				divShowTimings=divShowTimings+"<tr>";
				for(var j=0;j<2;j++)
				{
					if((i+j)<arrResponse.length)
						divShowTimings=divShowTimings+"<td class='almostsold01' width='50%' align='left'><a href=\"#\" onclick=\"openSelectSeats('"+arrResponse[i+j][1]+"');return false;\">"+arrResponse[i+j][0]+"</a></td>";
					else
						divShowTimings=divShowTimings+"<td width='50%'>&nbsp;</td>";
				}
				divShowTimings=divShowTimings+"</tr>";
			}
			divShowTimings=divShowTimings+"</table>";
			document.getElementById(ControlId).innerHTML=divShowTimings;
		}
		if(ControlId.toLowerCase()=="ddlcity" || ControlId.toLowerCase()=="ddllocation"
		|| ControlId.toLowerCase()=="ddlmovie" || ControlId.toLowerCase()=="ddldate")
		{
			for(var i=0;i<arrResponse.length;i++)
			{
				var drpOption=document.createElement("OPTION");
				drpOption.text=arrResponse[i][0];
				drpOption.value=arrResponse[i][1];
				document.getElementById(ControlId).options[document.getElementById(ControlId).length]=drpOption;
			}
			if(document.getElementById(ControlId).length>1)
			{
				EnableElement(ControlId);
			}
		}
	}
}
*/

//delocalize newlines
function ajax_newlines( s )
{
    return s.replace(/\r\n|\r/g,"\n")
}

// TODO
// make it easier for users to generate post / get requests with a custom field/value collection and encoder
// similar to ASP's Request.Form - but in reverse? some kind of parseForm( formName ) function might be a 
// cool way of submitting a form via ajax.





// AJAX request object

// fCallback	= handle to callback function
// sURL			= url to make request to
// sPost		= POST form data to send (leave as "" for GET request)
// userObject   = user var - passed to callback
// requestType	= request type enum
// bSkipHeader	= (reserved)
function ajax_requestObject( fCallback , sURL , sPost , userObject , requestType , bSkipHeader )
{
	var me              = this;
	this.m_fCallback    = fCallback;
	this.m_sURL         = sURL;
	this.m_sPost        = sPost;
	this.m_requestType	= requestType;
	this.m_userObject   = userObject;
	this.m_bSkipHeader	= bSkipHeader;
	this.retry = function(){ ajax_retry( me ); };

	//spawn and attatch the request
	this.m_HttpRequest	= ajax_spawnRequest( me );
}	

// create a native httpRequest object from the paramrs in a requestObject and return
// hRO		= handle to request object
function ajax_spawnRequest( hRO )
{
	var l_HttpRequest = null;
	
	if( window.XMLHttpRequest )	//FF,NS,OP,IE7
	{
		l_HttpRequest = new XMLHttpRequest();
	}
	else
	if( window.ActiveXObject )	//IE5/6
	{
		l_HttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
	}

	if( l_HttpRequest )
	{
		if( hRO.m_sPost != "" )
		{
			l_HttpRequest.open( 'POST', hRO.m_sURL , true );
			l_HttpRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			l_HttpRequest.onreadystatechange = function(){ ajax_stateChange( hRO ); };
			l_HttpRequest.send( hRO.m_sPost );	
		}
		else
		{
			l_HttpRequest.open( 'GET', hRO.m_sURL , true );
			l_HttpRequest.onreadystatechange = function(){ ajax_stateChange( hRO ); };
			l_HttpRequest.send( null );	
		}
	}
	
	return l_HttpRequest;
}

// .retry() - resends a request
// hRO		= request object
function ajax_retry( hRO )
{
	//dont usurp a request in action
	if( hRO.m_HttpRequest && hRO.m_HttpRequest.readyState != 4 )
		return;
		
	hRO.m_HttpRequest = ajax_spawnRequest( hRO );
}

// ..onreadystatechange()
// hRO		= request object
function ajax_stateChange( hRO )
{
    //got a response?
	if( hRO && hRO.m_HttpRequest && hRO.m_HttpRequest.readyState == 4 )
	{
		var s = hRO.m_HttpRequest.responseText;
		var f = hRO.m_fCallback;
		
		//if the http status is 200 then we have a response!
		var statusCode = ajax_statusCode_error;
		if( hRO.m_HttpRequest.status == "200" )
		{
		    statusCode = parseInt( s.substr(0,3) );
		    
		    //bound to know codes but allow user to pass through 600 etc.
		    if( statusCode != ajax_statusCode_ok && statusCode != ajax_statusCode_error && statusCode < ajax_statusCode_user )
		        statusCode = ajax_statusCode_error;
		}
		
		// user recieves a null object if the status = 500
		// but they can still manually get to the http request response text if they need to
		var obj = null;
		if( statusCode == ajax_statusCode_ok || statusCode >= ajax_statusCode_user )
		{
			if( hRO.m_requestType == ajax_requestType_string )
				obj = s.substring(4)
		}
		
        //invoke user callback
		f( obj , statusCode , hRO );
	}
}


