//add the controller for the application
window.application.addController((function($, application){
    // the controller function
	function Controller(){
		this.REGEX_LOOSE_EMAIL = null;
		this.REGEX_PASSWORD = null;
		// Route URL events to the controller's event handlers.
		this.route("/", this.index);
		this.route("/register/", this.register);
		// default properties
		this.HomePage = null;
		this.Registration = null;
		this.loginLink = null;
		this.loginBox = null;
	}
	
	// Extend the core application controller (required).
	Controller.prototype = new application.Controller();
	
	// Initialize the controller. This runs once the application starts running. 
	//This ensures the DOM is ready and all the other model and view classes have been added to the system.
	Controller.prototype.init = function(){
		this.REGEX_LOOSE_EMAIL = /(([^<>()[\]\\.,;:\s(@|&\#64;)\""""]+(\.[^<>()[\]\\.,;:\s(@|&\#64;)\""""]+)*)|(\"""".+\""""))(@|&\#64;)((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
		this.REGEX_PASSWORD = /(?=.{6,})/;
		//load the views into the properties
		this.HomePage = application.getView('HomePage');
		this.Registration = application.getView('Register');
        this.Login = application.getView('Login');
        this.loginLink = ".login .links a:eq(0)";
        this.loginBox = ".login .box";
	};
	
	// the default event for the controller
	Controller.prototype.index = function(event){
		// Show the home page view
		this.showView(this.HomePage, event);
	};
	
	// the default event for the controller
	Controller.prototype.register = function(event){
		// Show the registration view
		this.showView(this.Registration, event);
	};
	
	// Show the give view after hiding any existing view
	Controller.prototype.showView = function(view, event){
		// Check for current view and hide it
		if (this.currentView && this.currentView.hideView){
			this.currentView.hideView();
		}
		//show the given view
		view.showView(event.parameters);
		
		//store given view as the current view
		this.currentView = view;
		
		//run global event handlers
		this.globalEvents();
	};
	
	// global event handlers
	Controller.prototype.globalEvents = function(){
		var self = this;
		self.loginHandler();
		$(self.loginLink).live('click', function(e){
			e.preventDefault();
			$(self.loginBox).toggleClass('dn');
		});
        $('.close').live('click', function(e){
			e.preventDefault();
			$(this).parent().hide();
		});
	};
    
    // global login controller
    Controller.prototype.loginHandler = function(){
        this.Login.checkLoginState();
    };
	
	//return a new controller instance
	return (new Controller());
})(jQuery, window.application));

