// from unexpectancy.com

var js_includes = new Array();

function js_include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

function js_include_once(script_filename) {
    if (!in_array(script_filename, js_includes)) {
        js_includes[js_includes.length] = script_filename;
        js_include_dom(script_filename);
    }
}


// Checks if an expression exists in the global JS namespace
// returns true or false
function isset(varname) { return eval('typeof(' + varname + ') != "undefined"'); }

// Calls a function
//#TODO : find a sexier way to implement that...
function callFunction(funcName)
{
	setTimeout(funcName+"();",0);
}

// Warning : the JS file containing funcTest has to be the last one in the file list
// sample call : js_include_once_wait( { func:"displayStuff", files:[ "js/displayLib.js", "js/utils.js"] } );
function js_include_once_wait(params)
{
	// Asks for required files
	var i = 0;
	for (i=0; i< params.files.length; i++)
	{
		js_include_once(params.files[i]);
	}

	var funcTest = "";
	if (params.funcTest != null)
	{
		funcTest = params.funcTest;
	}
	else
	{
		funcTest = params.func;
	}

	// If the final file is not loaded yet
	// the call is scheduled for later
	if (!isset(funcTest))
	{
		var call = "js_include_once_wait( ";
		call += " { func:\""+params.func+"\" ,";
		if (params.funcTest != null)
		{
			call += " funcTest:\""+params.funcTest+"\" ,";
		}
		call += " files: ["
		for (i=0; i< params.files.length-1; i++)
		{
			call += "\""+params.files[i]+"\",";
		}
		call += "\""+params.files[params.files.length-1]+"\"";
		call += " ] } );";
		setTimeout(call,100*params.files.length);
	}
	else // otherwise the call can be done
	{
		callFunction(params.func);
	}
}