
'Redarea.Core.Widget.Loader'.namespace();

/**
 * Redarea.Core.Widget.Loader
 * This class required plugins:
 * - ajaxq
 * - jquery.json
 */
Redarea.Core.Widget.Loader = function() {};

Redarea.Core.Widget.Loader.baseUrl = '/';

/**
 * Put the widget loading to queue
 * 
 * @param string module Name of module
 * @param string name Name of widget
 * @param string Parameters names and values in JSON format
 * @param string containerId The DIV container that render the widget
 * @param string callback Function or name of callback function (since 2.0.8)
 * @return void
 */
Redarea.Core.Widget.Loader.queue = function(module, name, data, containerId, callback) {
	Redarea.Core.Widget.Loader.queueAction(module, name, 'show', data, containerId, callback);
};

/**
 * Put the widget action to queue
 * 
 * @param string module Name of module
 * @param string name Name of widget
 * @param string act Action's name
 * @param string Parameters names and values in JSON format
 * @param string containerId The DIV container that render the widget
 * @param string callback Function or name of callback function (since 2.0.8)
 * @return void
 */
Redarea.Core.Widget.Loader.queueAction = function(module, name, act, data, containerId, callback) {
	//*LUX*/$('#' + containerId).addClass('loading').html('');
	var baseUrl = Redarea.Core.Widget.Loader.baseUrl;
	baseUrl = baseUrl.replace(/\/+$/, "");
	$.ajaxq('widget', {
		url: baseUrl + '/core/widget/ajax/',
		data: { mod: module, name: name, act: act, params: data },
		success: function(response) {
			response = $.evalJSON(response);
			//*LUX*/$('#' + containerId).removeClass('loading').html(response.content);
            //*LUX*/$('#' + containerId).fadeOut(250);
            $('#' + containerId).html(response.content);
            /*LUX*/$('#' + containerId).fadeIn(250);
			
			for (var i in response.css) {
				if ($('head').find('link[href="' + response.css[i] + '"]').length == 0) {
					$('<link rel="stylesheet" type="text/css" href="' + response.css[i] + '" />').appendTo('head');
				}
			}
			
			for (i in response.javascript) {
				if (response.javascript[i].file != null && $('body').find('script[src="' + response.javascript[i].file + '"]').length == 0) {
					$('<script type="text/javascript" src="' + response.javascript[i].file + '"></script>').prependTo('body');
				}
				
				/**
				 * Add scripts to the end of page
				 * @since 2.0.6
				 */
				if (response.javascript[i].script != null) {
					$('<script type="text/javascript">' + response.javascript[i].script + '</script>').prependTo('body');
				}
			}
			
			/**
			 * Run the callback
			 * @since 2.0.8
			 */
			if (callback) {
				callback(response);
			}
		}
	});
};

