// namespacing object
var ajax=new Object();

// Constructor
ajax.Loader=function(target,parameters,func,theForm,containerId,fadeId)
{
	this.request=null;
	this.containerId = containerId;
	this.fadeId = fadeId;
	this.startTime = new Date().getTime();
	this.loadingDiv = null;
	if (this.fadeId) {
	    this.loadingDiv = document.getElementById(this.fadeId + "_loading");
	    var container = document.getElementById(this.fadeId);
	    if (container) {
			this.hadBackgroundColour="N";
			if (container.style.backgroundColor)
				this.hadBackgroundColour="Y";
			else
				container.style.backgroundColor = "#ffffff";
			if (!this.loadingDiv) {
				this.loadingDiv = document.createElement("DIV")
				this.loadingDiv.id=this.fadeId + "_loading";
				this.loadingDiv.className = "wrLoading";
				container.parentNode.appendChild(this.loadingDiv);
			}
			this.loadingDiv.style.marginTop = ((container.clientHeight/2) * -1) - (36/2) + "px";
			this.loadingDiv.style.marginLeft = ((container.clientWidth/2)) - (89/2) + "px";
			this.loadingDiv.style.display = "block";
		    opacity(this.fadeId, 100, 50, 500);
		}
	}
	this.target=target;
	this.parameters=parameters;
	this.method="post";
	if (this.containerId) {
	    this.func=this.processHTML;
        var obj=document.getElementById(this.containerId + "Popup");
        if (obj) 
            obj.parentNode.removeChild(obj);
    }	    
	else
	    this.func=func;
	if (theForm) {
	    if (this.processForm(theForm) == false) return false;
	}
	this.loadXMLDoc();
	return true;
}

ajax.Loader.prototype.processHTML=function(HTMLResponse)
{
    document.getElementById(this.containerId).innerHTML = HTMLResponse;
}

// Process a form being submitted
ajax.Loader.prototype.processForm=function(theForm)
{
    if (this.parameters !="")
        this.parameters +="&";
        
    var value="";

	if (document.all || document.getElementById)
	{
		// Process all the inputs on the form
		for (i = 0; i < theForm.length; ++i)
		{
			var elem = theForm.elements[i]
			if (elem.name && elem.name.substring(0, 4) == "req_")
			{
				if (elem.type && (elem.type=="text" || elem.type=="textarea" || elem.type=="password" || elem.type=="file") && elem.value=='')
				{
					alert("\"" + elem.name.substring(4) + "\" is a required field in this form")
					elem.focus()
					return false
				}
			}
			if (elem.name) {
			    if (theForm.elements[i].type != "checkbox" || theForm.elements[i].checked == true) {
			        // Add to the parameter string to submit via Ajax
                    this.parameters += theForm.elements[i].name+"=" + theForm.elements[i].value+"&";
                }
            }
            
		}
	}
	
    // We need to extract action, because forum uses button called "action" too, which corrupts the .action property
    if (this.target == "") {
        var html = theForm.parentNode.innerHTML;
        var index = html.indexOf("action=",0);
        var index2 = html.indexOf(" ",index+7);
        var action = html.substr(index+7,index2-(index+7));
        action = action.replace(/\"/g,"");
        this.target = action;
	    this.method = theForm.method;
	}
	
	return true;
}

// Send request
ajax.Loader.prototype.loadXMLDoc=function()
{
	if (window.XMLHttpRequest){
		this.request=new XMLHttpRequest();
	} else if (window.ActiveXObject){
		this.request=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (!this.request) return;

//	SetTimer();
	  
	try {
		var loader=this;
		this.request.onreadystatechange=function(){ajax.Loader.onReadyState.call(loader);}
		// TODO Add bit of logic to get rif of Origination and make this generic
		var url="";

		if (this.target.indexOf("http://") < 0)
		    var url=HTTP_SERVER + this.target;
		else
		    var url = this.target;
		   
        if (this.method=="post") {
	        this.request.open(this.method,url,true);
	    }
	    else {
	        this.request.open(this.method,url+"?"+this.parameters,true);
	    }
	    this.request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	    this.request.send(this.parameters);

	} catch (err) {
		this.processResponse(true);
	}

}

// Process reply
ajax.Loader.onReadyState=function()
{
	var request=this.request;
	var ready=request.readyState;
	
	var READY_STATE_UNINITIALISED=0;
	var READY_STATE_LOADING=1;
	var READY_STATE_INTERACTIVE=3;
	var READY_STATE_COMPLETE=4;
	
	//	Make sure we have got the reply
	if(ready==READY_STATE_COMPLETE){
		var httpStatus=request.status;
		if (httpStatus==200 || httpStatus==0){
            var thisObj = this;
            var timeRemaining = 750 - (new Date().getTime() - this.startTime);
            if (timeRemaining > 0)
                setTimeout(function(){ thisObj.processResponse() }, timeRemaining);
            else
                this.processResponse();
  		} else {
			this.processResponse(true);
		}
	}
}

ajax.Loader.prototype.processResponse=function(cancel)
{     
    if (this.fadeId) {
		if (this.loadingDiv) {
			this.loadingDiv.style.display="none";
			opacity(this.fadeId, 50, 100, 500);
			if (this.hadBackgroundColour=="N") {
				var thisObj = this;
    			setTimeout(function(){ thisObj.resetBackground() }, 500);
			}
		}
    }
    
    // Returned text must start with a tag "<"
    if (cancel)
        this.func(false);
    else {
		if (this.request.responseText)
			this.func(this.request.responseText.replace(/^[^<]*</, '<'));    
    }
}

ajax.Loader.prototype.resetBackground=function()
{
    var container = document.getElementById(this.fadeId);
    if (container)
		container.style.backgroundColor = "";
}

