/**
 * The Front Controller
 * Be aware it's a Singleton; only one object can be created at a time, and
 * if a new instance is created, the same object will always be returned.
 *
 * @package    site
 * @author     Luis Merino <mail@luismerino.name>
 * @return 	   (Object) Controller
 */
(function(){
	
	// Variable for holding the instance.
	var instance = null;
	
	var Controller = this.Controller = new Class({
	
		Implements: Options,
	
		options: {
			currentLang: function(){ return $E('html').get('lang'); }
		},
		
		_prepareLanguages: function(){
			for (var lang in Vadingo.languages) {
				MooTools.lang.addLanguage(lang);
				MooTools.lang.set(lang, 'cascade', Vadingo.languages[lang]['cascade']);
				MooTools.lang.set(lang, 'Currency', Vadingo.languages[lang]['Currency']);
				MooTools.lang.set(lang, 'Date', Vadingo.languages[lang]['Date']);
			}
		}.protect(),
	
		initialize: function(options){
			if (instance) return instance;
			instance = this;
			this.setOptions(options);
			this._prepareLanguages();
		},
	
		dispatch: function(){
			MooTools.lang.setLanguage($try(this.options.currentLang) || this.options.currentLang);
			// Interface checking.
			var ISiteMethods = new MethodsInterface('SiteMethods', this.methods);
			// This function will throw an error if any of the functions are not implemented in the object, halting the execution.
			// First parameter will be the object to watch out for. Params second, third, etc. will be one or many Interface objects respectively.
			MethodsInterface.ensureImplements(Vadingo.methods, ISiteMethods);
			// Call main players of the system, e.g.: Ajax manager, Forms manager or other automated processes.
			// Init the ajax manager.
			this.ajax = new AjaxCommand();
			// Init the notification system.
			this.notification = new FlashMessage('notification', {animate: false});
			// Init the translation manager.
			this.translationManager = Vadingo.translationManager = new TranslationManager({
				'lang': MooTools.lang.getCurrentLanguage().substr(0, 2)
			});
			// Now execute every method passed in.
			$each(this.methods, this.run, this);
		},
	
		run: function(name, index){
			Vadingo.methods[name].bind(this)();
		}
	
	});
	
	Controller.preload = function(methods){
		Controller.prototype.methods = methods;
	};
	
	Controller.run = function(methods){
		for (var i = 0; i < methods.length; i++) Controller.prototype.run.call(this, methods[i]);
	};
	
	Controller.getInstance = function(){
		if (!instance) return new Controller();
		return instance;
	};
	
})();