// Add view to the application.
window.application.addView((function( $, application ){
    
	// ViewProfile view class
	function Register(){
		this.loadURL = null;
		this.content = null;
		this.submit = null;
	}
	
	// intialize the view with the init prototype
	Register.prototype.init = function(){
		// initialize properties
		this.loadURL = 'register.htm #content';
		this.content = $('#contentWrapper');
		this.submit = '#register .submit';
	};

	// show view
	Register.prototype.showView = function(){
		var self = this;
		// load register content
		self.content.load(self.loadURL, function(){
			self.bindEvents();
		}).show();

	};
	
	// bind validation and event submission
	Register.prototype.bindEvents = function(){
		var self = this;
		$(self.submit).live('click', function(e){
			e.preventDefault();
			if (
				$('#nEmail').validate(application.controllers[0].REGEX_LOOSE_EMAIL, function(val){
					$.showError('Please enter a valid email address.');
				}) && $.compare($('#nPass').val(),$('#nConfirm').val(),function(){
					$.showError('Passwords don\'t match.');
				}) && $('#nPass').validate(application.controllers[0].REGEX_PASSWORD, function(){
					$.showError('Passwords need to be 6 characters or longer.');
				})
			) {
				self.submitRegistration($('#nEmail').val(), $('#nPass').val());
			}
		});
	};
	
	// submit registration data to server
	Register.prototype.submitRegistration = function(e, p){
		var postData = { mode: 'create', email: e, pass: p};
		application.getModel("Interface").execute(
			postData, 
			function(json){
				if (json.result == 'success'){
					alert('Account created! You can now log in.');
					location.hash = "#/";
				}
				else {
					if (typeof json.message != 'undefined'){
						if (json.message.indexOf('Duplicate entry') < 0){
							$.showError(json.message);
						}
						else {
							$.showError("That email already exists in our database.", {link:{href:'#/recover/',copy:'Lost your password?'}});
						}
					}
					else {
						$.showError("unspecified error. Please try again later.");
					}
				}
			}, 
			function(json){
				alert('Oops! Something went wrong!');
			});
	};
	
	// hide view
	Register.prototype.hideView = function(){
		this.content.hide();
	};
	
	// return a new view class
	return (new Register());
	
})( jQuery, window.application ));
