/*--------------------------------------------------------------------------
 *  Teliase Ajax JavaScript framework, version 2.0
 *  (c) TeliaSonera AB
 *
 *	Requires tse_core.js and the Prototype JavaScript framework, version 1.6 +
 *--------------------------------------------------------------------------*/

Tse.Ajax = function() {
	var log = Tse.Log;

	// Private functions and variables
	var handleJaxletResponse = function(xhr,url,id) {
		if(xhr.status == 404) {
			$(id).update("<!-- URL: " +url+ " har inte laddats ännu -->");
		} else if(xhr.status == 206) {
			// Not finished - wait and try again
			$(id).update("Ej klar. Laddar igen.");
			setTimeout(function(){
				Tse.Ajax.jaxletCall('"+url+"', '"+id+"');
			}, 1000);
		} else {
			$(id).update("<!-- Status: " + xhr.status+ " -->" + xhr.responseText);
		}
	}
	
	var handleJsonResponse = function(xhr, url, callback, pars) {
		//log.debug('handleJsonResponse' + xhr.status);
		//alert('handleJsonResponse' + xhr.status);
		if(xhr.status == 404) {
			// Not finished 
		} else if(xhr.status == 206) {
			// Not finished - wait and try again
			setTimeout(function(){Tse.Ajax.doJsonCall(url, callback, pars);}, 1000);
		} else {
			var s = xhr.responseText;
			try {
				var jsonResponse = s.evalJSON(true);
				callback(jsonResponse, pars);
			}
			catch (e) {
				log.error("Unable to handle JSON response <!-- "+s.escapeHTML()+" -->. URL: "+url+", Status: " + e.status + ", text: " + e.statusText);
			}
		}
	}			
	
	// Public functions and variables
	return {
		/**
		 * Performs an Ajax/jaxlet request. Consider to use Tse.Ajax.doJsonCall instead of a jaxlet call.
		 * @param {string} url the url of the jaxlet to use 
		 * @param {string} id the id of the container element to be updated by the response
		 */
		jaxletCall: function(url,id) {
			try {
				new Ajax.Request(
					url, 
					{
						method: 'get',
						onComplete: function(response) {
							handleJaxletResponse(response,url,id);
						}
					});
			} catch(e) {
				log.error("Unable to make jaxlet call. Status: " + e.status + ", text: " + e.statusText);
			} 
		},
		/**
		 * Performs an Ajax-request that returns an JSON object. Triggers <code>callback</code> on success.
		 * @param {string} url the url to address
		 * @param {function} callback the callback funtion to run on success
		 * @param {array} pars parameters to send along to the callback function 
		 */
		doJsonCall: function(url, callback, pars) {
			//log.debug('Tse.Ajax.doJsonCall, url: ' + url);
			//alert('Tse.Ajax.doJsonCall, url: ' + url);
			new Ajax.Request(
				url, 
				{
					method: 'get', 
					onComplete: function(data) {
									handleJsonResponse(data,url,callback,pars);
								},
					requestHeaders: ['X-JSON', 'true', 'If-Modified-Since', 'Fri, 31 Dec 1999 00:00:00 GMT']
				});
		}
	}
}();
				

