/*
## Jorge 18/02/2011
   Initial coding.
*/
var progress_bar = new Image();
progress_bar.src = baseRootURL + 'media/images/wait_load.gif'; //preload image
var ajaxObjects = {};
var ajaxCounter = 0;

function ajax(name, params, url, callback)
{
	//"use strict";
	this.id = ajaxCounter ? ajaxCounter++ : 1;
	this.data = '...waiting...';
	ajaxObjects[this.id] = this;
	this.name = name+this.id;	
	this.xmlHttp = this.GetXmlHttpObject(); //begin the ajax session
	
	//progress
	this.xmlHttp.onload 	= this.showProgress();
	//this.xmlHttp.progress 	= this.xmlHttp.onload;
	//this.xmlHttp.onloadend 	= this.hideProgress();
	//this.xmlHttp.error 		= this.hideProgress();
	//this.xmlHttp.timeout 	= this.hideProgress();
	
	checkBrowser(this.xmlHttp);
	eval("this.xmlHttp.onreadystatechange = function(){ajaxObjects['"+this.id+"'].stateChanged(callback)}");
	var outputField = params.outputField ? params.outputField : 'ajaxDiv';
	this.parseRequest(outputField, params, baseRootURL+url);
}

ajax.prototype.GetXmlHttpObject = function()
{  //Browser Support Code
	try	{ return new XMLHttpRequest(); }// Opera 8.0+, Firefox, Safari
	catch (e)
	{  
		try { return new ActiveXObject("Msxml2.XMLHTTP"); } // Internet Explorer Browsers
		catch (e)
		{
			try { return ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e)
			{
				// Something went wrong
				alert("Your browser does not support AJAX and needs to be updated.");
				return false;
			}
		}
	}
}

ajax.prototype.parseRequest = function(id, data, url)
{
	if (data)
	{
		var content = "";
		for (var i in data) 
		{
			content += ((content)? "&" : "")+i+"="+(data[i]+"").replace(/&/g,"%26").replace(/=/g,"%3D").replace(/\+/g,"%2B");
		}
		this.xmlHttp.open("POST", url, true);
		this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		
		/**
		this.xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
		this.xmlHttp.setRequestHeader("Access-Control-Allow-Methods", "*");
		this.xmlHttp.setRequestHeader("Access-Control-Allow-Headers", "api-key,content-type");
		this.xmlHttp.setRequestHeader("Access-Control-Allow-Credentials", true);
		**/
		
		this.xmlHttp.send(content);
	}
	else
	{
		this.xmlHttp.open("GET", url, false)
		this.xmlHttp.send();		
	}
}

ajax.prototype.hideProgress = function()
{
	$("#ajaxDiv").hide();
	$(".body").css("cursor", "default");
}

function showErrorImg()
{
	/**
	document.getElementById('ajaxDiv').innerHTML = 
	'<img src="'+baseRootURL + 'media/images/dialog_warning.png" border="0" alt="There are errors." />';	
	**/
}

ajax.prototype.showProgress = function()
{
	$("#ajaxDiv").show();
	$(".body").css("cursor", "wait");
}

ajax.prototype.replace_html = function(id, content)
{
	document.getElementById(id).innerHTML = content;
}

function checkBrowser(req)
{
	var errors = false;
	if(req == null)
	{
		errors = true;
		alert("Your browser does not support AJAX and should to be updated.");
		return;
	}
}

ajax.prototype.stateChanged = function(callback)
{  	
	/*
		readyState Codes:
		0 = uninitialized
		1 = loading
		2 = loaded
		3 = interactive
		4 = complete
	*/	

	if (this.xmlHttp.readyState == 4 && this.xmlHttp.status == 200)
	{  
		/*
		We always get an object now as a response. This object will tell us how to handle the message:
		"redirect" = true if the user should be redirected, else false
		"location" = if "redirect" == true, then this is the page to redirect to
		"message" = the message to be displayed
		"msgType" = how the message should be displayed -: 
					0 = alert only
					1 = show in field ID only
					2 = alert & show in field (i.e. 0, and 1 above combined)					
					3 = append to field ID
					4 = alert & append to field ID
					5 = error message
					6 = Same as 5 but for the new error message (JS) format
					7 = success message
					8 = nicEdit TextArea Field
		"displayField" = Depending on "msgType", display the message in this field (id)
		"isValueField" = should be true if the field uses "value" for content else will use "innerHTML" for content.
		"focusField" = the field ID that should receive focus.
		*/

		this.hideProgress();
		if (DEBUGGING) console.log(this.xmlHttp.responseText);
		
		if (this.xmlHttp.responseText !== "")
		{
			var str = "var data = " + this.xmlHttp.responseText + ";"; //JSON decode
			if (DEBUGGING) alert(this.xmlHttp.responseText);
			eval(str);
			this.data = data;
	
			if ((data.msgType==6) && (!data.redirect))
			{
				var key, obj;
				for (key in data) 
				{
					if (data.hasOwnProperty(key))
					{
						obj = document.getElementById(key); 
						if (obj !== null) obj.value = data[key];
					}
				}
				//return data; //just a plain JSON call for data
			}
			else
			{
				switch(data.msgType)
				{
					case 0:
					{
						data.message = data.message.replace("%20", " ");
						alert(data.message);
						break;
					}
					case 1:								
						if (data.isValueField)
						{
							if (DEBUGGING) console.log('field populated: '+data.displayField);
							document.getElementById(data.displayField).value = data.message
						}
						else
						{
							if (DEBUGGING) console.log('innerHTML populated: '+data.displayField);
							document.getElementById(data.displayField).innerHTML = data.message;
						}
						break;	
					case 2:
						alert(data.message);
						if (data.isValueField)
							document.getElementById(data.displayField).value = data.message
						else
							document.getElementById(data.displayField).innerHTML = data.message;
						break;					
					case 3:
						if (data.isValueField)
							document.getElementById(data.displayField).value = document.getElementById(data.displayField).value + data.message
						else
							document.getElementById(data.displayField).innerHTML = document.getElementById(data.displayField).innerHTML + data.message;
						break;
					case 4:
						alert(data.message);
						if (data.isValueField)
							document.getElementById(data.displayField).value = document.getElementById(data.displayField).value + data.message
						else
						{
							document.getElementById(data.displayField).innerHTML = document.getElementById(data.displayField).innerHTML + data.message;
						}
						break;	
					case 5:
						handleError(data.displayField, data.message);
						showErrorImg();			
						break;
					case 6:
						document.getElementById("hint_"+data.displayField).innerHTML = data.message;
						showErrorImg();			
						break;	
					case 7:
						handleSuccess(data.displayField, data.message);		
						break;
					case 9:
						return data.message;
				} //case statement
				
				if (data.redirect) 
				{
					//alert(data.location);
					window.location = data.location;
				}
				else
					if (data.focusField) document.getElementById(data.focusField).focus;			
			}
		}
		if (callback !== undefined) 
		{
			if (DEBUGGING) console.log('ajax callback response...');
			callback(); //cater for a callback function after the remote ajax call
		}
	} // if(this.ajaxObject.readyState == 4)
} /* stateChanged() */