/** 
* Extend jQuery with our custom multi-resource asynchronous script receiver. 
* 
* It ensures that the onLoaded callback will only be executed when all scripts have been
* loaded. It also maintains a cache of already loaded URL's to prevent multiple downloads.
* 
* It also supports loading script that have their own loading mechanism, like Google Maps,
* by offering a way to take their callback and inject it into ourselves.
* 
* Resources are passed in the following style:
* 
* 	[ 
* 		"simple_javascript_file.js", 
* 		{
* 			url: 'js_file_with_own_loader', 
* 			callbackSetter: function(callback) {
* 				// The callback parameter is the callback that 'js_file_with_own_loader' _needs_
* 				// to call when it completes. So you could do it like this for example:
* 				module.addListener( 'onLoad', callback ) ;
* 				// Or you can check the example below for how it works with Google Maps e.g.
* 				self._callbackCalledWhenResourceCompletes = callback ;
* 			} 
* 		} 
* 	]
* 
*  This is a sample resource definition for loading Google Maps with our own custom script that 
*  extends the Google Map object:
*  
* 	[ "my_google_maps_extension.js", 
* 		{ 
* 			url: "http://maps.google.com/maps?file=api&v=2&key=" + GMAP_KEY + "&async=2&callback=_gmapsOwnOnLoadCallback",	
* 			callbackSetter: function(callback) { self._gmapsOwnOnLoadCallback = callback } 
* 		} 
* 	] ;
* 
*/
window.reloadScriptsFlag=false;
function getScript(url,callback) {
    if(!window.reloadScriptsFlag)
    {
        var script = document.createElement("script");
        script.src = url.toString();
        script.type = "text/javascript";
        //script.charset = scriptCharset;
        var done = false;
        // Attach handlers for all browsers
        //$(script).ready(function(){if(url.indexOf('irectory')>0){alert($(script).attr('src'));}});
        
        script.onload = script.onreadystatechange = function(){
            if ( !done && (!this.readyState || 
                        this.readyState == "loaded" || this.readyState == "complete") ) {
                done = true;
                //if(url.indexOf('irectory')>0){alert("1 "+url);}
                if(callback)
                {callback();}
                script.parentNode.removeChild( script );
            }
        };		
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
    }
    else
    {
        if(callback)
        {
            $.getScript(url,callback);
        }
        else
        {
            $.getScript(url);
        }    
    }
}

jQuery.getScriptSet = function( resources, onLoadCallback ) {
    
    // Before we do anything we check if we have any resources in here, and if not call our callback.
    if (resources.length < 1) {
        if (onLoadCallback) onLoadCallback() ;
        return ;
    }

    // Initialize the counter for the closure with the number of resources we have,
    var counter = resources.length ;

    // and define the closure creator, which tracks completion of resource downloads.
    var callbackCreator = function(resource) { 
        var loaded = false ;
        return function() {
            // Which checks if the resource was already loaded (second callback call)  
            if ( ! loaded ) {
                // If not loaded it sets the resource as loaded
                loaded = true ;
                // Mark the URL of the resource as loaded in the cacheRegister.
                jQuery.getScriptSet.cacheRegister[resource.url] = true ;
                // And if the counter decremented by 1 is 0 (all resources loaded) 
                if ( --counter == 0 ) {
                    // call the postFetchCallback
                    onLoadCallback() ; 	
                }
            }
        }
    } ;


    // Loop over all resources	
    for( i = 0 ; i < resources.length ; i++ ) {
        var resource = resources[i] ;
        if ( typeof(resource) == 'string' ) resource = { url: resource } ;
        registerEntry = jQuery.getScriptSet.cacheRegister[resource.url] ;

        // Check if the resource is already retrieved (check url cache)
        if ( registerEntry == undefined ) {
            // If we are going to fetch the resource give it a 'false' value to indicate a load in progress.
            registerEntry = false ;

            // If we have an onLoadCallback
            if (onLoadCallback) {
                var callback = callbackCreator(resource) ; 
                // If we've been provided with a way to set the callback
                if (resource.callbackSetter) {
                    // let our callback be set there.
                    resource.callbackSetter(callback);
                    getScript( resource.url ) ; 
                } else {
                    // Otherwise fetch the script with the callback					
                    getScript( resource.url, callback ) ; 
                }
            } else {
                getScript( resource.url ) ;
            }
            // If the prefetch returns false, decrease counter because we have one less resource to load.
        } else {
            // And if the counter decremented by 1 is 0 (all resources loaded) 
            if ( --counter == 0 && this.onLoadCallback) 
            {
                // call the postFetchCallback
                this.onLoadCallback() ; 
            }            
        }

    }

}
jQuery.getScriptSet.cacheRegister = [] ;