/**
 * AkylaAjax
 *
 * AkylaAjax is a wrapper for Ajax calls. Creates ajax requests and handles them. Is
 * more or less a wrapper / factory in one. Because every Ajax call actually ends up
 * in its own prototype wrapper
 */
var Akyla_Prototype_Ajax = Class.create(
{
	/**
	 * Constructor
	 *
	 * Just because there should be one!
	 */
	initialize : function ()
	{
		this.currentRequest = 0;
		this.queue = {};
	},
	/**
	 * Creates an ajax request and sends it to url. Url is prepended by
	 * the Akyla.preferences.baseUrl
	 * @param string url Url of the ajax resource
	 * @optional @param form HTMLElement|String A html form or the ID to the form
	 * @optional @param options Extra options. These options get merged with the standard
	 * funcitons which are declared/initialized below in requestOptions and will be passed to
	 * prototype Ajax.Request which means it also takes all the options which are usable by
	 * prototype Ajax object
	 */
	ajaxRequest : function (url, form, options)
	{
		this.queue = this.queue || {};
		var currentTime = new Date().getTime();
		var alreadyExecuting = false
		for (stamp in this.queue)
		{
			var queueItem = this.queue[stamp];
			if (url == queueItem.url && currentTime < (queueItem.timestamp+1000))
			{
				alreadyExecuting = true;				
			}
			if (queueItem.timestamp < currentTime - 1000)
			{
				delete this.queue[stamp]
			}
		}
		if (alreadyExecuting)
		{
			return;
		}
		else
		{
			this.queue[currentTime] = {
				timestamp : currentTime,
				url : url
			};
		}
		if (typeof url == "undefined" || url === null )
		{
			return;
		}
		url=url.gsub("//","/0/");
		url = url.replace('http:/0/','http://');
		if ($(form) && $(form).tagName.toLowerCase() == "form")
		{
			parameters = $(form).serialize();
		}
		else
		{
			parameters = "";
		}
		var requestOptions = Object.extend(
		{
			method : "post",
			parameters : parameters,
			onRequestSuccess : function (data) {},
			onRequestError : function (data) {},
			onSuccess: function(transport) 
			{
				Akyla.Ajax.processRequest(transport,requestOptions);
			},
			on500 : function(transport)
			{
				Akyla.Ajax.processDefaultTransport(transport,requestOptions);
			}
		},options);
		var requestUrl = url;
		if ( url.indexOf("http://") !== 0 )
		{
			requestUrl = Akyla.preferences.baseUrl + "/" + url;
		}
		new Ajax.Request(requestUrl,requestOptions);
		this.currentRequest++;
	},
	dumpObject : function (obj, indent)
	{
		if (indent)
		{
			var result = indent+"{\n";
		}
		else
		{
			var result = "<textarea class=\"errorReport\">{\n";
			indent = "";
		}
		for (var key in obj) 
		{
			if (typeof obj[key] == "object")
			{
				result += "&nbsp;&nbsp;"+indent+key+" : \n"+this.dumpObject(obj[key],indent+"&nbsp; &nbsp;")+"\n";
			}
			else if  (typeof obj[key] == "function")
			{
				result += "&nbsp;&nbsp;"+indent+key+" : Internal Function, \n";
			}
			else
			{
				result += "&nbsp;&nbsp;"+indent+key+" : \""+(obj[key])+"\",\n";
			}
		}
		if (!indent)
		{
			result += "\n}</textarea>";
		}
		else
		{
			result += indent+"},";
		}
		return result;
	},
	dumpArray : function (dataArray, className)
	{
		if (typeof className == "undefined" || className === null )
		{
			className = "errorReport";
			}
		var result = '<textarea class="'+className+'">';
		result += dataArray.join("\n");
		result += "</textarea>";
		return result;
	},
	/**
	 * Default processor for the transport of the response. Extensions can override this prototype
	 * to make sure they get an extra functionality in AkylaAjax
	 * @param object transport The Ajax transport object
	 */
	processDefaultTransport : function (transport,requestOptions)
	{
		if (Akyla.WindowHandler)
		{
			var details = 
				{
					url : transport.request.url,
					parameters : transport.request.parameters,
					responseText : transport.responseText
				};
			Akyla.WindowHandler.factory("Alert", {
				id : "alert",
				content : this.dumpObject(details)
			}).setTitle(Akyla.translate("Unexpected error occurred.")).setFooter(Akyla.translate("Please contact akyla with page details.")).show();
		}
		else
		{

			var overlay = new Element("div",{ style: "overflow-y : scroll; padding : 5px; border : solid 1px gray; z-index : 9999; display:block; position : fixed; background-color : #EEEEEE; left : 20px; right : 20px; top : 20px; bottom : 20px;" },
				[new Element("h2",null,"Something went wrong.")]);
			$(overlay).update(transport.responseText);
			$(document.body).insert( {top : overlay });
			$(overlay).observe("click", $(overlay).remove);
		}
			// Something is wrong...		
	},
	
	/**
	 * JSON processor for the transport of the response. Extensions can override this prototype
	 * to make sure they get an extra functionality in AkylaAjax
	 * @param object transport The Ajax transport object
	 */
	processJSONTransport : function (transport,requestOptions)
	{
	},
	/**
	 * Processes an Ajax request. If the responseText is JSON format this.processJSONTransport gets called
	 * If otherwise processDefaultTransport gets called
	 * @param object transport The Ajax transport object
	 * TODO : add XML support
	 */
	processRequest : function (transport,requestOptions)
	{
		if(transport.responseText.isJSON())
		{
			//evaluate the JSON file 
			this.processJSONTransport(transport,requestOptions);
		}
		else
		{
			this.processDefaultTransport(transport,requestOptions);
		}
	}
});

Akyla.Ajax = new Akyla_Prototype_Ajax();

