// Provides a method to load scripts and css in the background
var BackgroundLoad = function(){
	//var loadJQueryCalled = false;
	var inProgress = false;
	var queue = [];
	function loadScriptNow(){
		if (queue.length === 0) {
			inProgress = false;
			return;
		}
		var script = queue.shift(); // removes and returns first element of array
		// get JQuery to load the script
		jQuery.getScript(script.fileName,function(){
				// give things a chance to settle and then load the next script in the queue
				setTimeout(loadScriptNow,20);
				// if the user has supplied a callback then invoke it
				if ('function' === typeof script.callback) {
					setTimeout(script.callback, 20); // give the browser time to process the script we've just loaded
				}
			});
	}
	// This function waits around for JQuery to be loaded
	function startLoading(){
		inProgress = true;
		if ('undefined' === typeof jQuery){
			// we need JQuery so wait until it's loaded
			setTimeout(arguments.callee,100);
			return;
		}
		loadScriptNow();
	}
	return {		
		/* Warning: Be wary of using this function multiple times, there is no guarantee what
		 * order the loaded scripts will be executed in by the browser.
		 * Recommended: Use this once to load JQuery, then use the loadScriptWithJQuery function */ 
		begin: new Date(),
		scriptNo$ : function(fileNames){
			if ('string' === typeof fileNames){
				fileNames = [fileNames];
			}
			setTimeout(function(){
				for (var i = 0; i < fileNames.length; i++) {
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = fileNames[i];
					document.getElementsByTagName('head')[0].appendChild(script);
				}
			},20);
		},
		/* Use this function to load a css file */
		css : function(fileNames){
			if ('string' === typeof fileNames){
				fileNames = [fileNames];
			}
			setTimeout(function(){
				for (var i = 0; i < fileNames.length; i++) {
					var css = document.createElement('link');
					css.rel = 'stylesheet';
					css.type = 'text/css';
					css.href = fileNames[i];
					document.getElementsByTagName('head')[0].appendChild(css);
				}
			},20);
		},
		/* Once JQuery is loaded, call this function as much as you like to load scripts.
		 * FileName can either be a string or an array of strings
		 */
		script : function(fileNames, callback){
			if ('string' === typeof fileNames){
				fileNames = [fileNames];
			}
			for (var i = 0; i < fileNames.length; i++) {
				queue.push({
					fileName: fileNames[i],
					callback: i === fileNames.length - 1 ? callback : null
				});
			}
			if (!inProgress){
				startLoading();
			}
		}
	};
}();

