/**
 * Elements interactive Standard Library
 */
window.addEvent('domready', function(){esl.initialize();});

var Esl,esl = {
    version: '1.0.1',
    callbacks: {},
	loadedFiles: {},
	domready: false,
	log: function() {
    	if(typeof console != 'undefined' && typeof console.log != 'undefined') {
    		try{
    			console.log.apply(this, arguments);
    		} catch(e) {
    			//foo
    		}
    	}
    },
	initialize: function(){
		// Load modules dynamically
		var defaultModules = '';
		var js = /esl\.js(\?.*)?$/;
		$$('script[src]').each(function(s){
			if(s.src.match(js)) {
				esl.workDir = s.src.replace(js, 'modules/'), includes = s.src.match(/\?.*load=([a-z0-9_,]*)/);
				esl.basePath = esl.workDir.replace('/js/modules/', '');
				(includes ? includes[1] : defaultModules).split(',').each(function(include){
					esl.require(include)
				});
			};
		});
	},
	require: function(s, callback) {
		
		// If the module has been loaded before, we execute the callback right away
		var module = s.replace('.js');
		if (!esl.callbacks[module]) {
			esl.callbacks[module] = new Array();
		}
		
		if (callback) {
			esl.callbacks[module].push(callback);
		}
		
		if (this.loadedFiles[module] == undefined) {
			window.addEvent('domready', function(){
				new Asset.javascript((s.match(/^http/) ? '' : esl.workDir) + s.replace('_', '/') + (s.match(/\.js$/) ? '' : '.js'));
			});
		}
		else {
			//this.callback(module);
		}
	},

	/**
	 * Each require can contain a callback, the module will call this function to execute it
	 *
	 * @param string	The Filename of the module
	 * @return void
	 */
	callback: function(module) {
		this.loadedFiles[module] = true;
		this.callbacks[module].each(function(fnc) {
			if (typeof fnc == 'function') {
				fnc();
			}
		});
		this.callbacks[module] = new Array();
	}
};