/**  **  ** **  **  ** **  **  ** **  **  ** **  **  ** **  **  ** **  **  **
 * Loader object
 */
var Loader = {
	activeCalls : 0,
	busyElement : null,
	
	/**
	 * init()
	 * Initializes busy indicator and hides it.
	 */
	init : function() {
		this.busyElement = '#requestLoader';
		this.hideBusy();
	},
	
	/**
	 * load()
	 * Load content with AJAX. Request type = POST, Response JSON.
	 * @param	string(data) Posted parameters, key value pairs
	 * @param   string(callback) Name of callback function. NO '()' at end, only name.
	 * @param   string(type) Type of data returned, default JSON
	 */
	load : function(url, data, callback, type, stackName) {
		
		if (type == undefined) {
			type = 'json';
		}
		
		if (stackName != undefined) {
			jQuery.ajaxSync({
				url: url,
				type : 'post',
				dataType : type,
				success: callback,
				data : data
			});
		} else {
			jQuery.post(url, data, callback, type);
		}
		
		Loader.increaseCallCount();
	},
	
	/**
	 * increaseCallCount()
	 * Increases activeCalls count - should not be called directly!
	 * @param	integer(i) Count used to increse activeCalls
	 */
	increaseCallCount : function(i) {
		if(i) {
			this.activeCalls = this.activeCalls + i;
		} else {
			this.activeCalls++;
		}
		this.updateBusy();
	},
	
	/**
	 * decreaseCallCount()
	 * Decreases activeCalls count
	 */
	decreaseCallCount : function() {
		if(this.activeCalls > 0) {
			this.activeCalls--;
		}
		this.updateBusy();
	},
	
	/**
	 * updateBusy()
	 * Updates the busy indicator.
	 */
	updateBusy : function() {
		if( this.activeCalls ) {
			this.showBusy();
		} else {
			this.hideBusy();
		}
	},
	
	/**
	 * showBusy()
	 * Shows the busy indicator element.
	 */
	showBusy : function() {
		if(this.busyElement !== null) {
			$(this.busyElement).fadeIn("fast");
		}
		$("body").css("cursor","wait");
	},
	
	/**
	 * hideBusy()
	 * Hides the busy indicator element.
	 */
	hideBusy : function() {
		if(this.busyElement !== null) {
			$(this.busyElement).fadeOut("slow");
		}
		$("body").css("cursor","default");
	},
	
	changeBusyElement : function(element) {
		this.busyElement = '#' +element;
	}
};

/**
 * javascript template loader
 */
var JSTLoader = {
		
	load : function(template,callback) {
		var params = {
			'id'	: template
		};
		
		JSTLoader.ajax(params, callback);
	},
	
	/**
	 * ajax()
	 * Load string with AJAX. Request type = POST, Response text/plain.
	 * @param	string(data) Posted parameters (json)
	 * @param   string(callback) Name of callback function. NO '()' at end, only name.
	 */
	ajax : function(data,callback) {
		Loader.increaseCallCount();
		jQuery.post('/jstemplates/gettemplate', data, function(object) {
			if (object.status == 1) {
				callback(object.data.template);
			}
		}, 'json');
	},
	
	decreaseCallCount : function() {
		Loader.decreaseCallCount();
	}
};
