/**
 * CBSL PE Widget Registry.
 * 
 * Dynamically loads PE widget scripts and their support scripts.  Once a script has been successfully loaded, 
 * the supplied callback function will be triggered.
 * 
 * Depends on:
 *  - jquery (1.5.1 or greater)
 *
 * Author: Andrew Pitt
 * @since 2.2
 */

// PE Widget Initializers will register themselves with this variable.
var initializers = {};

// Tracks import status of non-pe scripts.
var supportScript = {
        modernizr: false,
        calendarFr: false
};

(function( $ ){
	
	/**
	 * Override the built in cache because for the static files we want to be able to cache it.
	 * See http://jamiethompson.co.uk/web/2008/07/21/jquerygetscript-does-not-cache/
	 * 
	 * @param url A string containing the URL to which the request is sent.
	 * @param callback A callback function that is executed if the request succeeds.
	 * @param cache if the file should be cachable or not
	 */
	$.getScript = function(url, callback, cache){
		$.ajax({
				type: "GET",
				url: url,
				success: callback,
				dataType: "script",
				cache: cache,
				crossDomain: true
		});
	};
	
	/**
	 * Extending jQuery for datalist detection.
	 * 
	 * See https://github.com/Modernizr/Modernizr/issues/146
	 */
	$.support.datalist = !!(document.createElement('datalist') && window.HTMLDataListElement);
    
                   
    /** 
     * Load support script if it doesn't exist. 
     * @param args <code>Object</code>
     */
    var loadSupportScript = function(args) {
        var scriptName = args['name'];
        if (supportScript[scriptName] == false) {
            console.info("Loading support script '" + scriptName + "'.");
            $.getScript(scriptRoot + args['script'], args['callback'], true);
            supportScript[scriptName] = true;
        } else {
            console.info("Support script '" + scriptName + "' already imported.  Executing callback.");
            args['callback']();
        }     
    };                        
    
    /** 
     * Load a specific widget script.
     * @param args <code>Object</code>
     */
    var loadWidget = function(args) {
        var widget = args['name'];
        if (typeof(initializers[widget]) == 'undefined') {
            console.info("PE-" + widget + " not detected.  Loading it now.");
            $.getScript(scriptRoot + args['script'], function() { initializers[widget].init(args['callback']); }, true);
        } else {
            //console.info("PE-" + widget + " already imported.  Executing callback.");
            args['callback']();
        }   
    }
    
    /**
     * Load a widget by name.  After the widget has been loaded, the callback will be executed.
     * If the widget cannot be found, the callback will be called anyway.
     * @param widgetName <code>String</code>
     * @param callback <code>Function</code>
     */
    $.loadPEWidget = function(widgetName, callback) {
        //console.info("LoadPEWidget: " + widgetName);
        var args = {name: widgetName, callback: callback};
        switch (widgetName) {
            case 'modernizr':               
                loadSupportScript($.extend({script: '/utils/js/modernizr.min.js'}, args));
                break;
            case 'calendar':
                loadWidget($.extend({script: '/calendar/js/jQuery.calendar.js'}, args));
                break; 
            case 'calendarFr':
                loadSupportScript($.extend({script: '/calendar/js/jquery.ui.datepicker-fr.js'}, args));
                break; 
            case 'clfTabs':                
                loadWidget($.extend({script: '/tabs/js/jQuery.clfTabs.js'}, args));
                break;                   
            case 'collapsible':                
                loadWidget($.extend({script: '/collapsible/js/jQuery.collapsible.js'}, args));
                break;
            case 'detectCapsLock':                
                loadWidget($.extend({script: '/detectcapslock/js/jQuery.detectCapsLock.js'}, args));
                break;
            case 'formInput':                       
                loadWidget($.extend({script: '/forminput/js/jQuery.forminput.js'}, args));
                break;     
            case 'interstitial':                
                loadWidget($.extend({script: '/interstitial/js/jQuery.interstitial.js'}, args));
                break;                  
            case 'keyUtils':                
                loadWidget($.extend({script: '/keyutils/js/jQuery.keyUtils.js'}, args));
                break;                
            case 'peAutocomplete':                
                loadWidget($.extend({script: '/autocomplete/js/jQuery.autocomplete.js'}, args));
                break;
            case 'sessionTimeout':                       
                loadWidget($.extend({script: '/sessiontimeout/js/jQuery.sessionTimeout.js'}, args));
                break;                   
            case 'showHide':                       
                loadWidget($.extend({script: '/showhide/js/jQuery.showhide.js'}, args));
                break;     
            case 'tooltip':                
                loadWidget($.extend({script: '/tooltip/js/jQuery.tooltip.js'}, args));
                break;
            case 'tree':                
                loadWidget($.extend({script: '/tree/js/jQuery.tree.js'}, args));
                break;
            case 'validateAddress':                
                loadWidget($.extend({script: '/validation/address/js/jQuery.validate.address.js'}, args));
                break;
            case 'validateUrl':                
                loadWidget($.extend({script: '/validation/url/js/jQuery.validate.url.js'}, args));
                break;
            case 'validateEmail':                
                loadWidget($.extend({script: '/validation/email/js/jQuery.validate.email.js'}, args));
                break;
            default:
                console.info("Widget named '" + widgetName + "' not recognized.");
                callback();
        }
    };    
    
})( jQuery );

