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



//------------------------------------------------------------------------------------------
// track pageviews and set cookies for subsequent tracking
//------------------------------------------------------------------------------------------

(function() {
	MSGI.page.login.tracking = function() {
		trackPromo();
		trackCampaign();
	};
	
	MSGI.page.login.getParamFromRedirectURL = function(param) {
		var redirectURL = $.cookie('redirect_url');
		if (!redirectURL) return null;
		return MSGI.getQueryParam(param, unescape(redirectURL));
	};

	function trackPromo() {
		var promo = MSGI.getQueryParam('promo');
		if (!promo) return;
		
		MSGI.channel.getCurrent(function(channel) {
			// track a clickthrough for this combination of 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);
		});
	}

	// track that user attempted to view a campaign landing page, but was redirected to login page
	function trackCampaign() {
		// extract the campaign slug from the query string of the redirect URL
		var slug = MSGI.page.login.getParamFromRedirectURL('id');
		if (!slug) return;
		
		// if available, get the HTTP referrer of the page the user was attempting to reach 
		var http_referrer = $.cookie('redirect_http_referrer');
		
		// track this pageview
		MSGI.campaign.track({ 'type': 'login_pageview', 'slug': slug, 'http_referrer': http_referrer });
	}
})();



// Service
MSGI.namespace('page.login', {
	/** 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) {
		// save logged-in subscriber's first name in a cookie
		$.cookie('subscriber_name', subscriber.first_name);
		
		// if a redirect URL cookie was set by MSGI.authenticate() when the user failed authentication
		var redirectURL = $.cookie('redirect_url');
		if (redirectURL) {
			// delete cookie, then redirect to the page the user was initially trying to reach
			$.cookie('redirect_url', null);
			document.location = unescape(redirectURL);
		} else {
			// otherwise, just redirect to the My Insider page
			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;
	}

});

MSGI.namespace('page.login', {
	setupContent: function() {
		// if the redirect URL has an email address in the query string,
		// use it to prepopulate the login form
		var email = MSGI.page.login.getParamFromRedirectURL('email');
		if (email) $('#email_id').val(email);
		
		// extract the campaign slug from the query string of the redirect URL
		var slug = MSGI.page.login.getParamFromRedirectURL('id');
		if (slug) {
			MSGI.campaign.getDetailsBySlug(slug, function(campaign, isOver) {
				if (!isOver && campaign && campaign.loginpage_text) {
					$('h1').html(campaign.loginpage_text);
					Cufon.replace('.cufon');
				}
			});
		}
	}
});
