// Add view to the application.
window.application.addView((function( $, application ){
    
    // ViewProfile view class
	function Login(){
        this.uEmail = null;
        this.uPass = null;
        this.uName = null;
        this.loggedOutSelector = null;
        this.loggedInSelector = null;
        this.submitLoginSelector = null;
	}
	
	// intialize the view with the init prototype
	Login.prototype.init = function(){
		// initialize properties
        this.uEmail = "#uEmail";
		this.uPass = "#uPass";
        this.uName = "";
        this.loggedOutSelector = "#loggedOut";
        this.loggedInSelector = "#loggedIn";
        this.submitLoginSelector = "#loggedOut .submit";
	};

	// show view
	Login.prototype.checkLoginState = function(){
		var self = this;
		// check auth cookie
        application.getModel("Interface").execute(
            {mode:'token'},
            function(json){
                if (json.result == "success"){
                    self.loggedIn(json.name);
                } else {
                    self.loggedOut();
                }
            },
            function(json){
                try{
                    console.log(json.message);
                }
                catch(ex){
                    self.loggedOut();
                }
            }
        );
	};
    
    // show logged out state
    Login.prototype.loggedOut = function(){
        // display logged out state
        $(this.loggedOutSelector).show();
        //bind login submit
        this.bindLogin();
    };
    
    // show logged in state
    Login.prototype.loggedIn = function(name){
        // display logged in state
        $(this.loggedInSelector).find('a').text(name).end().show();
    };
	
	// bind login submission
	Login.prototype.bindLogin = function(){
		var self = this;
		$(self.submitLoginSelector).live('click', function(e){
			e.preventDefault();
			if (
				$(this.uEmail).validate(application.controllers[0].REGEX_LOOSE_EMAIL, function(val){
					$.showError('Please enter a valid email address.');
				})
			) {
				self.submitLogin($('#uEmail').val(), $('#uPass').val());
			}
		});
	};
	
	// submit registration data to server
	Login.prototype.submitLogin = function(e, p){
		var self = this;
        var postData = { mode: 'login', email: e, pass: p};
		application.getModel("Interface").execute(
			postData, 
			function(json){
				if (json.result == 'success'){
					self.loggedIn(e);
				}
				else {
					alert(json.message);
				}
			}, 
			function(json){
				alert('Oops! Something went wrong!');
			});
	};
	
	// return a new view class
	return (new Login());
	
})( jQuery, window.application ));
