/**
 * @author -  Asit
 * @author -  Adarsh Pandey 
 * @version - 1.3
 * @param  1. strUrl - url for ajax call.
 *         2. placeHolder - if any to which wants to get the response of 
 *            call as inner html of html element with that id - optional. 
 *         3. retFunction - in case of asynchrous call if wants to call a method on response with 
 *            two parameters 1st - response text and 2nd - strparam if passed - optional.
 *         4. strParam - in case asynchronous call this parameter is passed 
 *            as second parameter to the retFunction - optional.
 * Remember 
 * 		   1. while invoking methods of object of AjaxAPI if not specifying asynch parameter then 
 *            default call will be synchrous - otherwise pass this parameter as true
 *         2. if you are not want to add a ajaxInstanceId for every call show that call 
 *         	  should lookup from cache first, then reset url value by calling ChangeURL method after
 *            creating AjaxAPI object.
 * Instructions for creating AjaxAPI object and invoking various methods for ajax call 
 *         1. How to create AjaxAPI object - var ajaxObj = 
 *                new  AjaxAPI("user.do?actionName=validateUserAjax"); - other 3 parameters are optional
 *         2. How to invoke methods
 *                i. ajaxObj.SendRequest(isAsync) pass isAsync value as true spacifies that call will 
 *                   be asynchronous - returns response text if call is synchronous - all parameters are optional.
 *               ii. ajaxObj.SubmitForm(formObj,strParamArr,isAsync) - all parameters are optional.
 *              iii. ajaxObj.SubmitAsForm(strParamArr,isAsync) - - all parameters are optional. 
 * Sample Use Example -
 *		var strParamArr = new Array("email",email,"password",password,"rememberme",rememberme);
 *		var url = "user.do?actionName=validateUserAjax";
 *		var ajaxObj = new AjaxAPI(url);
 *		var ResponseText = ajaxObj.SubmitAsForm(strParamArr);
 * 
 */
var logoutUrl = "user.do?actionName=logout"; 
function AjaxAPI(strUrl, placeHolder, retFunction, returnBackParam)
{
	var xmlHttp = null;

	var URL = strUrl;
	if(URL.indexOf("?")!=-1)
		if(URL.indexOf("?") == URL.length - 1)
			URL = URL + "ajaxInstanceId=" + Math.random();
		else
			URL = URL + "&ajaxInstanceId=" + Math.random();
	else
		URL = URL + "?ajaxInstanceId=" + Math.random();
	var PlaceHolder = placeHolder;
	var ReturnBackParam = returnBackParam;
	var RetFunction = retFunction;
	
	this.SendRequest = SendRequest;
	this.SubmitForm = SubmitForm;
	this.SubmitAsForm = SubmitAsForm;
	this.ChangeURL = ChangeURL
	
	xmlHttp = getXMLHttpRequestObject();
	
	this.ResponseHandler = function ()
    {
       if (xmlHttp.readyState == 4) 
        {
            if (xmlHttp.status == 200)
            {
            	if(handleResponse())
            	{
					if(RetFunction != null)
					{
						if(ReturnBackParam != null)
		    				RetFunction(xmlHttp.responseText,ReturnBackParam);
						else
		    				RetFunction(xmlHttp.responseText);
					}
					if(PlaceHolder != null && document.getElementById(PlaceHolder) != null)
						document.getElementById(PlaceHolder).innerHTML = xmlHttp.responseText;
            	}
            }
        }
    }
    /**
     * Code for handling errors/exceptions raised during ajax call
     * goes here in handleResponse.
     *
     */
	function handleResponse()
	{	
		if((xmlHttp.responseText).match("Session Expired")!=null)
		{
			window.location.href = logoutUrl;
			return false;
		}
		return true;
	}
    function getXMLHttpRequestObject()
    {  
    	var xmlHttpLocal = null;
    	try
    	{    // Firefox, Opera 8.0+, Safari    
    		xmlHttpLocal=new XMLHttpRequest();    
    	}
    	catch (e)
    	{    // Internet Explorer    
    		try
    		{      
    			//Internet Explorer 6.0+
    			xmlHttpLocal=new ActiveXObject("Msxml2.XMLHTTP");      
    		}
    		catch (e)
    		{      
    			try
    			{     
    				//Internet Explorer 5.5+   
    				xmlHttpLocal=new ActiveXObject("Microsoft.XMLHTTP");       
    			}
    			catch (e)
    			{        
    				alert("Your browser does not support AJAX!");               
    			}      
    		}    
    	} 
    	return xmlHttpLocal;
    }
    function SendRequest(isAsync)
    {
		isAsync = isCallAsynchronous(isAsync);
        if(xmlHttp!=null)
    	{
    		xmlHttp.open("GET", URL, isAsync);
    		//xmlHttp.open("POST", URL, isAsync);
        	if (isAsync == true)
                xmlHttp.onreadystatechange = this.ResponseHandler;
    		xmlHttp.send(null);
    		if (isAsync == false && handleResponse())
			{
				if(RetFunction != null)
				{
					if(ReturnBackParam != null)
	    				RetFunction(xmlHttp.responseText,ReturnBackParam);
					else
	    				RetFunction(xmlHttp.responseText);
				}
				if(PlaceHolder != null && document.getElementById(PlaceHolder) != null)
					document.getElementById(PlaceHolder).innerHTML = xmlHttp.responseText;
                return xmlHttp.responseText;
			}
        }
    }
    function SubmitForm(formObj,strParamArr,isAsync)
    {
    	isAsync = isCallAsynchronous(isAsync);
        if(xmlHttp!=null)
    	{
            xmlHttp.open("POST", URL, isAsync);
            //setting content type header of request for submitting form.
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
            //getting formvalues as string in key/value pair.
            var frmValues = getFormValues(formObj,strParamArr);

            if (isAsync == true)
                xmlHttp.onreadystatechange = this.ResponseHandler;
            xmlHttp.send(frmValues);
    		if (isAsync == false && handleResponse())
			{
				if(RetFunction != null)
				{
					if(ReturnBackParam != null)
	    				RetFunction(xmlHttp.responseText,ReturnBackParam);
					else
	    				RetFunction(xmlHttp.responseText);
				}
				if(PlaceHolder != null && document.getElementById(PlaceHolder) != null)
					document.getElementById(PlaceHolder).innerHTML = xmlHttp.responseText;
                return xmlHttp.responseText;
			}
    	}
    }
	function SubmitAsForm(strParamArr,isAsync)
	{
		isAsync = isCallAsynchronous(isAsync);
		if(xmlHttp!=null)
    	{
            xmlHttp.open("POST", URL, isAsync);
            //setting content type header of request for submitting form.
            xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
            if (isAsync == true)
                xmlHttp.onreadystatechange = this.ResponseHandler;
            var strParams = getParamValues(strParamArr);
            xmlHttp.send(strParams);
    		if (isAsync == false && handleResponse())
			{
				if(RetFunction != null)
				{
					if(ReturnBackParam != null)
	    				RetFunction(xmlHttp.responseText,ReturnBackParam);
					else
	    				RetFunction(xmlHttp.responseText);
				}
				if(PlaceHolder != null && document.getElementById(PlaceHolder) != null)
					document.getElementById(PlaceHolder).innerHTML = xmlHttp.responseText;
                return xmlHttp.responseText;
			}
		}
  	} 
    function getFormValues(formObj,strParamArr)
    {
    	if(formObj.elements!=null)
    	{
           	var str = "";
           	for(var i = 0;i < formObj.elements.length;i++)
           	{
               	if (formObj.elements[i].type == "radio")
               	{ 
                    if(formObj.elements[i].checked==true)
                        str += formObj.elements[i].name + "=" + escape(formObj.elements[i].value) + "&";
               	}
			   	else if(formObj.elements[i].type == "checkbox")
			   	{
			   		if(formObj.elements[i].checked==true)
						str += formObj.elements[i].name + "=true&";
					else
						str += formObj.elements[i].name + "=false&";
			   	}
               	else
                    str += formObj.elements[i].name + "=" + escape(formObj.elements[i].value) + "&";      
           	}
           	if(str != "")
           		str = str.substr(0,(str.length - 1));
           	var str2 = getParamValues(strParamArr);
           	if(str != "" && str2 != "")
           		return str + "&" + str2;
           	else
           		return str + str2;
        }
    } 
    function getParamValues(strParamArr)
    {
       	var str = "";
    	if(strParamArr!=null && strParamArr.constructor.toString().indexOf("Array") != -1)
    	{
           	for(var i = 0;i+1 < strParamArr.length;i+=2)
				str += escape(strParamArr[i]) + "=" + escape(strParamArr[i+1]) + "&";
           	if(str != "")
         		str = str.substr(0,(str.length - 1));
        }
        return str;
    } 
	function isCallAsynchronous(isAsync)
	{
		if(isAsync ==null || isAsync != true)
			return false;
		else
			return true;
	}
	
	function ChangeURL(changedURL) {
		URL = changedURL;
	}
}

function fileLoaderAjax(url, placeHolder, callBack, params, isAsync)
{
	var ajaxObj = new AjaxAPI(url, placeHolder, callBack, params);
	if(isAsync == null){
		ajaxObj.SendRequest(true);
	}else{
		ajaxObj.SendRequest(false);
	}
}