﻿
// ScriptMgr : To dynamically load scripts and trigger callbacks
    
ScriptMgr = createSingleton(ScriptMgr = {});
ScriptMgr.prototype.init = function(args) {
    /*	        
        scriptRoot	: Root folder for scripts
        version		: Version control for scripts
    */
	if(!isDefined(args))
		args = {};
	defaults = { scriptRoot: "", version: "1.0" };
	for(var pr in defaults)
		this[pr] = isDefined(args[pr]) ?args[pr] :defaults[pr];
	
	// List of script-batches to be loaded
	this.batches = [];
	this.bodyLoadStatus = false;

	var mgr = this;
	
	DOM.addEvent(window, "load", function(ev) {
		mgr.onBodyLoad(ev);
	});

	// Add script-batch or a script to list
	this.push = function(batch) {
		this.batches.push(batch);
		
		if(isDefined(batch.scripts)) {
			for(var script in batch.scripts)
				this.setScriptUrl(script);
		}
		else {
			this.setScriptUrl(batch);
		}
	};

	// Body onLoad handler 
	this.onBodyLoad = function(ev) {
		this.bodyLoadStatus = true;
		for(var i=0; i<this.batches.length; i++)
			if(this.batches[i].sentRequest && this.batches[i].checkBodyLoad)
				this.batches[i].onScriptLoad();
	};

	// Script onLoad handler
	this.onScriptLoad = function(scriptId, errCode) {
		for(var i=0; i<this.batches.length; i++) {
			if(isDefined(this.batches[i].scripts)) {
				// if its a script-batch
				if(isDefined(this.batches[i].scripts[scriptId])) {
					this.batches[i].scripts[scriptId].onLoad();			
					return;
				}
			}
			else {
				// if its a script
				if(this.batches[i].id == scriptId) {
					this.batches[i].onLoad(errCode);
					return;
				}
			}
		}
	};

	// Set script url for absolute url and version control
	this.setScriptUrl = function(script) {
		script.url = this.scriptRoot + script.url + "?v=" + this.version;
	};
};

// Create Script-Manager singleton object
ScriptMgr.getInstance();