// Main
MSGI.namespace('page.login', {
	/** Initialize the page and attach events */
	init: function() {
		var page = this;		
		$(document).ready(function() {
			page.trackPromo();
			MSGI.subscriber.authenticate(function(loggedIn) {
				if (loggedIn) {
					page.redirectToMyInsider();
				} else {
					page.setupEvents();
				}
			});
		});
	}
});

// Service
MSGI.namespace('page.login', {
	trackPromo: function() {
		var params = MSGI.getQueryParams();
		var promo = params && params['promo'];
		
		// if a promo was provided in the URL (from an external promotion)
		if (promo) {
			MSGI.channel.getCurrent(function(channel) {
				// track a clickthrough for this combination channel and promo
				MSGI.promo.track('click', channel, promo);
				
				// save a cookie, so we can later track if the user signs up for MSG Insider
				$.cookie('promo', promo);
			});
		}
	},
	
	/** Login the subscriber account */
	loginAccount: function() {
		var page = this;
		var form = $("#login_form")[0];
		var subscriber = this.initSubscriberFromForm(form);
		var button = $('#login_btn');
	
		page.resetLoginNotices($('#password_notices'));
		
		
		MSGI.lock(function(unlock) {
			MSGI.widgets.button.animate(button);
			MSGI.subscriber.login(subscriber, function(response) {
				MSGI.widgets.button.stop(button);
				if (response.error) {
					if (response.error == MSGI.subscriber.login.NO_EMAIL) {
						page.redirectToSignUp(subscriber);
					} else if (response.error == MSGI.subscriber.login.EMAIL_NO_PASS_MATCH) {
						page.loginFail();
					} else if (response.error == MSGI.subscriber.login.EMAIL_NO_PASS_IN_DB) {
						// reset password email modal
					}
				} else {
					page.loginSuccess(response.result);
				}
				unlock();
			});
		});
	},

	/** Reset the subscriber account password */
	resetPassword: function() {
		var page = this;
		var form = $('#resetPassword_form')[0];
		var email = form.email.value;
		var button = $('#resetPassword_btn');

		if (!page.checkEmail(email)) { return; }

		var subscriber = {'email': email, 'the_password': ''};

		MSGI.lock(function(unlock) {
			MSGI.widgets.button.animate(button);
			MSGI.subscriber.emailResetPassword(subscriber, function(response) {
				MSGI.widgets.button.stop(button);
				if (response.error) {
					if (response.error == MSGI.subscriber.emailResetPassword.EMAIL_DOES_NOT_EXIST) {
						page.redirectToSignUp(subscriber);
					} else if (response.error == MSGI.subscriber.emailResetPassword.UNABLE_TO_CHANGE_PASSWORD) {
						page.displayNoticeModal("Unable to change password.");
					} else if (response.error == MSGI.subscriber.emailResetPassword.UNABLE_TO_SEND_EMAIL) {
						page.displayNoticeModal("Unable to send email.");
					}
				} else {
					page.displayThankYouModal(subscriber.email);
				}
				unlock();
			});
		});
	},

	/** Reset the subscriber account password */
	lookupAccountResetPassword: function() {
		var page = this;
		var form = $('#lookupAccount_form')[0];
		var button = $('#lookupAccount_resetPassword_btn');
		
		var email = form.email.value;
		if (email == "") { return; }

		var subscriber = {'email': email, 'the_password': ''};

		MSGI.lock(function(unlock) {
			MSGI.widgets.button.animate(button);
			MSGI.subscriber.emailResetPassword(subscriber, function(response) {
				MSGI.widgets.button.stop(button);
				if (response.error) {
					if (response.error == MSGI.subscriber.emailResetPassword.UNABLE_TO_SEND_EMAIL) {
						page.displayNoticeModal("Unable to send email.");
					} else {
						page.displayNoticeModal("Unable to change password.");
					}
				} else {
					page.displayThankYouModal(subscriber.email);
				}
				unlock();
			});
		});
	},

	/** Reset the subscriber account password */
	lookupAccount: function() {
		var page = this;
		var form = $('#lookupAccount_form')[0];
		var button = $('#lookupAccount_btn');
		var email = form.email.value;

		if (!page.checkLookupEmail(email)) { return; }

		MSGI.lock(function(unlock) {
			MSGI.widgets.button.animate(button);
			MSGI.subscriber.exists(email, function(hasAccount) {
				MSGI.widgets.button.stop(button);
				if (hasAccount) {
					page.displayLookupAccountResetModal();
				} else {
					page.redirectToSignUp({'email':email, 'the_password':''});
				}
				unlock();
			});
		});
	}
});


// Helpers
MSGI.namespace('page.login', {
	/**
	 * Initialize a subscriber from the form.
	 * @param {object} form the signup form
	 * @returns {object} the subscriber object
	 */
	initSubscriberFromForm: function(form) {
		return {
			email: form.email.value,
			the_password: form.password.value
		};
	},

	/** The login was successful */
	loginSuccess: function(subscriber) {
		$.cookie('subscriber_name', subscriber.first_name);

		var params = MSGI.getQueryParams();
		if (params && params['ref']) {
			document.location = unescape(params['ref']);
		} else {
			this.redirectToMyInsider();
		}
    },

	/** The login was not successful */
	loginFail: function() {
		$('#password_id').focus();
		this.addLoginNotice($('#password_notices'), 'incorrect password');
	},

	/** Redirects to My Insider page */
	redirectToMyInsider: function() {
		document.location = 'my-insider.html';
	},

	/**
	 * Redirects to the signup page
	 * @param {object} subscriber the subscriber data
	 */
	redirectToSignUp: function(subscriber) {
		$.cookie('subscriber_data', JSON.stringify(subscriber));
		document.location = 'signup.html';
	},

	/** Adds a notice to the list of notice messages */
	addLoginNotice: function(list, notice) {
		list.css('display', 'block');
	},

	/** Resets the notice messages to the default */
	resetLoginNotices: function(list) {
		list.css('display', 'none');
	},

	/** Display modal */
	displayModal: function(name) {
		$('#super_modal .modal_toggle').hide();
		$('#'+name).show();
		$('#super_modal').overlay().load();
	},

	/** Display notice modal */
	displayNoticeModal: function(text) {
		$('#notice_modal #notice_message').html(text);
		this.displayModal('notice_modal');
	},

	/** Display thank you modal */
	displayThankYouModal: function(email) {
		$('#resetPassword_Thankyou_modal #thankYouEmail').html(email);
		this.displayModal('resetPassword_Thankyou_modal');
	},

	/** Display reset password modal */
	displayResetPasswordModal: function() {
		this.resetLabelAndNotices($('#reset_email_label'), $('#reset_email_notices'));
		$('#resetPassword_form')[0].email.value = $('#login_form')[0].email.value;
		this.displayModal('resetPassword_modal');
	},

	/** Display lookup account modal */
	displayLookupAccountModal: function() {
		this.resetLabelAndNotices($('#lookupAccount_email_label'), $('#lookupAccount_email_notices'));
		this.displayModal('lookupAccount_modal');
	},

	/** Display lookup account reset password modal */
	displayLookupAccountResetModal: function() {
		this.displayModal('lookupAccount_reset_modal');
	},

	/** Highlights the input field */
	highlightLabel: MSGI.page.signup.highlightLabel,

	/** Resets the label to the default */
	resetLabel: MSGI.page.signup.resetLabel,

	/** Resets the notice messages to the default */
	resetNotices: MSGI.page.signup.resetNotices,

	/** Resets the label and notices to the default */
	resetLabelAndNotices: MSGI.page.signup.resetLabelAndNotices,

	/** Adds a notice to the list of notice messages */
	addNotice: MSGI.page.signup.addNotice
});



// Events
MSGI.namespace('page.login', {

	setupEvents: function() {
		this.setupClickEvents();
		this.setupFormEvents();
		this.setupFieldEvents();
	},

	/** Click Events */
	setupClickEvents: function() {
		var page = this;
		
		// login
		$("#login_btn").click(function() {
			page.loginAccount();
			return false;
		});

		// reset password
		$("#displayResetPasswordModal_btn").click(function() {
			updateOmniture('forgot-password-modal');
			page.displayResetPasswordModal();
			return false;
		});
		$("#resetPassword_btn").click(function() {
			page.resetPassword();
			return false;
		});
		$('#resetPassword_form').submit(function() {
			page.resetPassword();
			return false;
		});

		// lookup account
		$("#displayLookupAccountModal_btn").click(function() {
			updateOmniture('already-registered-modal');
			$('#lookupAccount_email_id').val('');
			page.displayLookupAccountModal();
			return false;
		});		
		$('#lookupAccount_form').submit(function() {
			page.lookupAccount();
			return false;
		});
		$("#lookupAccount_btn").click(function() {
			page.lookupAccount();
			return false;
		});
		$("#lookupAccount_resetPassword_btn").click(function() {
			page.lookupAccountResetPassword();
			return false;
		});
	},

	/** Form Events */
	setupFormEvents: function() {
		$('#login_form').submit(function() {
			return false;
		});
		$('#resetPassword_form').submit(function() {
			return false;
		});
	},

	/** Field Events */
	setupFieldEvents: function() {
		var page = this;
		$("#password_id").keypress(function(event) {
			if (event.which == 13) {
				page.loginAccount();
			}
		});
		$("#email_id").keypress(function(event) {
			if (event.which == 13) {
				if ($('#password_id').val()) {
					page.loginAccount();
				} else {
					$("#password_id").focus();
				}
			}
		});
	},

	checkEmail: function(email) {
		var isValid = true;
		this.resetLabelAndNotices($('#reset_email_label'), $('#reset_email_notices'));

		if (!MSGI.form.validateEmail(email)) {
			this.highlightLabel($('#reset_email_label'));
			this.addNotice($('#reset_email_notices'), "The email must be of the form user@example.com");
			isValid = false;
		}

		return isValid;
	},

	checkLookupEmail: function(email) {
		var isValid = true;
		this.resetLabelAndNotices($('#lookupAccount_email_label'), $('#lookupAccount_email_notices'));

		if (!MSGI.form.validateEmail(email)) {
			this.highlightLabel($('#lookupAccount_email_label'));
			this.addNotice($('#lookupAccount_email_notices'), "The email must be of the form user@example.com");
			isValid = false;
		}

		return isValid;
	}

});
