/**
 * @author Lokesh Gyanwali
 */

function $(elementId)
{
    return document.getElementById(elementId);
}

function AJAXObj(url, responseFunction, isPost, nameValuePairArray, extraObj, updateElements, isResponseXML, errorFunction, sendImmediatly)
{
	if(AJAXObj.GlobalArray == null)
		AJAXObj.GlobalArray = new Array();
		
	if(AJAXObj.GlobalCounter == null)
		AJAXObj.GlobalCounter = 1;
				
		
	if(typeof(url) == "string")
		this.Url = url + (url.indexOf('?')>-1? '&' : '?')+ (new Date()).getTime();
	else
		this.Url = null;
	
	if(typeof(responseFunction) == "function")
	    this.ResponseFunction = responseFunction;
	else
	    this.ResponseFunction = null;
	    
	if(typeof(isPost) == "boolean")   
	    this.Post = isPost;   
	else
	    this.Post = false;
	    
	if(typeof(nameValuePairArray) == "object")   
	  this.SetPostVariables(nameValuePairArray)
	else
	    this.NameValuePair = null;
	
	
	
	if(typeof(isResponseXML) == "boolean")   
	    this.RetrurnXML = isResponseXML;   
	else
	    this.RetrurnXML = false;
	
	if(typeof(extraObj) != "undefined")   
	    this.ExtraObject = extraObj; 
	else
	    this.ExtraObject = null;
	  
	if(typeof(updateElements) == "boolean")   
	    this.UpdateElements = updateElements;   
	else
	    this.UpdateElements = false;
	
	if(typeof(errorFunction) == "function")
	    this.onError = errorFunction;
	else
	    this.onError = null;
	    
	this.XMLHTTPObj = null;
	
	if(sendImmediatly)
	    this.Send();
}

AJAXObj.UpdateDropDown = function (optionList, dropdown)
{
    if(typeof(dropdown) == "string")
    {
        dropdown = $(dropdown); 
    }

    if(dropdown != null && dropdown.tagName.toUpperCase() == "SELECT")
    {
        
        var objParent = dropdown.parentNode;
        var strArray;
        if(objParent.innerHTML.indexOf("<option") > -1)
            strArray = objParent.innerHTML.split("<option");
        else if(objParent.innerHTML.indexOf("<OPTION") > -1)
            strArray = objParent.innerHTML.split("<OPTION");
        else if(objParent.innerHTML.indexOf("</SELECT>") > -1)
            strArray = objParent.innerHTML.split("</SELECT>");
        else
            strArray = objParent.innerHTML.split("</select>");  
               
        objParent.innerHTML = strArray[0] + optionList + "</select>"; 
    }

}

AJAXObj.UpdateInnerHTML = function (strBody, element)
{
    if(typeof(element) == "string")
    {
        element = $(element); 
    }
    
    
    if(element != null)
    {
        while (strBody.indexOf("<script") > -1)
        {
          var strFunction = strBody.substring(strBody.indexOf(">", strBody.indexOf("<script")) + 1,  strBody.indexOf("</script") );
          strBody = strBody.substring(0, strBody.indexOf("<script")) +  strBody.substring(strBody.indexOf(">", strBody.indexOf("</script")) + 1)
          var script = document.createElement('script');
          script.setAttribute('type','text/javascript');
          script.text = strFunction;
          document.getElementsByTagName("head")[0].appendChild(script);
        }

    
    
    
        element.innerHTML = strBody;    
    }
}

AJAXObj.UpdateValue = function (strValue, element)
{
    if(typeof(element) == "string")
    {
        element = $(element); 
    }
    if(element != null)
    {
        element.value = strValue;    
    }
}

AJAXObj.UpdateCheckOrRadio = function (strValue, element)
{
    if(typeof(element) == "string")
    {
        element = $(element); 
    }
    if(element != null)
    {
        strValue = strValue.toUpperCase();        
        element.checked = (strValue.indexOf("YES") > -1) || (strValue.indexOf("TRUE") > -1) || (strValue.indexOf("1") > -1);    
    }
}

AJAXObj.prototype.Send = function()
{
    
    if(typeof(this.Url) != "string")
        return false;
        
	this.GetAJAXObj();
	
	if(this.XMLHTTPObj == null)
		return false;
		
	
	
	var UniqueId = "AJAXObj_Request"+ AJAXObj.GlobalCounter++;
	
	this.XMLHTTPObj.onreadystatechange = new Function("AJAXObj.ResponseFunction('"+ UniqueId +"')");
	AJAXObj.GlobalArray[UniqueId] = this;
	try{
		this.XMLHTTPObj.open(this.Post? "POST" : "GET", this.Url , true);
		if(this.Post)
		{
			this.XMLHTTPObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
		
		this.XMLHTTPObj.send(this.NameValuePair);
	}
	catch(e)
	{
		alert("Error: "+ e.message)
		delete AJAXObj.GlobalArray[UniqueId];
		return false;
	}
	return true;
}

AJAXObj.HTMLEscape = function(str)
{
    if(typeof(str) != "string")
        str = str.toString();                                
         
    return escape(str.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;'));                                                                
}

AJAXObj.ResponseFunction = function (UniqueId)
{
	var objCurrent = AJAXObj.GlobalArray[UniqueId];
	
	if(objCurrent != null && objCurrent.IsReady())
	{
		if(!objCurrent.HasError())
		{
		    var objResp = objCurrent.Response();
		    if(objResp.indexOf("THIS IS THE LOGIN PAGE") > -1)
		    {
		        alert("Your session has expired, you will be taken to the login page");
		        var varVars = objResp.substring(objResp.indexOf("THIS IS THE LOGIN PAGE (") + "THIS IS THE LOGIN PAGE (".length);
		        varVars = varVars.substring(0, varVars.indexOf(") -->"));
		        location.href = varVars;
		        //alert(varVars);
		        return;
		    }
		//alert("Is Update Eletment?: "+ objCurrent.UpdateElements + objCurrent.ResponseFunction);
		   if(objCurrent.UpdateElements) 
		   {
		        if(objCurrent.ExtraObject != null)
		        {
		            var element = objCurrent.ExtraObject;
    		         
		            if(typeof(element) == "string")
                    {
                        element = $(element); 
                    }
                    
                    if(element != null && element.tagName)
                    {
                        switch(element.tagName.toUpperCase())
                        {
                            case "INPUT":
                                switch(element.type.toUpperCase())
                                {
                                    case "CHECKBOX":
                                    case "RADIO":
                                        AJAXObj.UpdateCheckOrRadio(objCurrent.Response(), element);
                                        break;
                                    default:
                                        AJAXObj.UpdateValue(objCurrent.Response(), element);
                                        break;
                                }
                                break;
                             case "TEXTAREA":
                                    AJAXObj.UpdateValue(objCurrent.Response(), element);
                                    break;
                             case "SELECT":
                                AJAXObj.UpdateDropDown(objCurrent.Response(), element);
                                break;
                             
                              default:
                                AJAXObj.UpdateInnerHTML(objCurrent.Response(), element);
                                break;
                        
                        }
                    }   
		        }
		        else
		        {
		            alert(objCurrent.Response());
		        }
		    }
		    
		    if(objCurrent.ResponseFunction)
			{
				objCurrent.ResponseFunction(objCurrent.Response(), objCurrent.ExtraObject)
			}
			
		}
		else if(typeof(objCurrent.onError) == "function")
		{
			objCurrent.onError(AJAXObj.GlobalArray[UniqueId], objCurrent.XMLHTTPObj.status, objCurrent.XMLHTTPObj.statusText)
		}
		else
		{
			alert("Remote Connection Failed. \nError Code:"+ objCurrent.XMLHTTPObj.status +".\nMessage:"+ objCurrent.XMLHTTPObj.statusText)
		}
		delete AJAXObj.GlobalArray[UniqueId];
	}
	
}

AJAXObj.prototype.Response = function()
{
	return this.RetrurnXML? this.XMLHTTPObj.responseXML : this.XMLHTTPObj.responseText;
}


AJAXObj.prototype.IsReady = function()
{
	return this.XMLHTTPObj && this.XMLHTTPObj.readyState == 4; 
}

AJAXObj.prototype.HasError = function()
{
	return this.XMLHTTPObj == null || this.XMLHTTPObj.status != 200; 
}

AJAXObj.prototype.SetPostVariables = function(NameValPairArray)
{
	if(NameValPairArray != null)
	{
		this.Post = true;
		var tmpArray = new Array();
		for(key in NameValPairArray)
		{
			tmpArray.push(key +"="+ AJAXObj.HTMLEscape(NameValPairArray[key]));
		}
		this.NameValuePair = tmpArray.join("&");
		
		
	}	
}

AJAXObj.prototype.UseFormVariables = function(FormObject, useFormUrl)
{
	if(typeof(FormObject) == "string")
		FormObject = $(FormObject);
	
	
	
	if(typeof(FormObject) == "object")
	{
		if(useFormUrl)
		{
			this.Url = FormObject.action + (FormObject.action.indexOf('?')>-1? '&' : '?')+ (new Date()).getTime();
		}
		var arrPost = new Array();
		for(var i=0; i < FormObject.elements.length; i++)
		{
		    var objElement = FormObject.elements[i];
		    if(!useFormUrl && objElement.name.indexOf("VIEWSTATE") > -1)
		        continue;
		    if((objElement.type == "checkbox" || objElement.type == "radio") &&!(objElement.checked))
				continue;
			arrPost[objElement.name] = objElement.value;
		}
		
		this.SetPostVariables(arrPost);
	}
}

AJAXObj.prototype.GetAJAXObj = function()
{
	if(window.XMLHttpRequest)
	{
		 this.XMLHTTPObj = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		try
		{
			this.XMLHTTPObj = ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			
		}
		
		if(this.XMLHTTPObj == null)
		{
			try
			{
				this.XMLHTTPObj = new ActiveXObject("Microsoft.XMLHTTP");
		
			}
			catch(e)
			{
				
			}
		}
		
	}
	
}
