/* SimpleModal Login Box
 * Revision: $Id: mr.popbox.js,v 1.2 2010/03/04 05:39:10 even_tian Exp $
 */
$(document).ready(function () {
	$('.loginlink').click(function (e) {
		e.preventDefault();
		// load the contact form using ajax
		$.get("/ajax/login.php", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ['0%',],
				overlayId: 'popbox-overlay',
				containerId: 'header',
				onOpen: popbox.open,
				onShow: popbox.show,
				onClose: popbox.close
			});
		});
	});
	$('.logoutlink').click(function (e) {
		e.preventDefault();
		$.cookie('UID', null, {
			domain: '.morerebates.com',
			path: '/'
		});
		$.post("/ajax/popup.php", {'msg':'You have successfully been logged out.'}, function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ['0%',],
				overlayId: 'popbox-overlay',
				containerId: 'header',
				onOpen: popbox.open,
				onClose: popbox.close_reload
			});
		});
	});
	// preload images
	var img = ['ajax-loader.gif'];
	$(img).each(function () {
		var i = new Image();
		i.src = '/img/default/' + this;
	});
});

var loginredir = function (url) {
	if ($.cookie('UID')) {
		window.open(url, '_blank');
	} else {
		$.get("/ajax/login.php", function(data){
			// create a modal dialog with the data
//			popbox.redir = url; // auto redir after login
			$(data).modal({
				close: false,
				position: ['0%',],
				overlayId: 'popbox-overlay',
				containerId: 'header',
				onOpen: popbox.open,
				onShow: popbox.show,
				onClose: popbox.close
			});
		});
	}
}

var msgbox = function (msg) {
	$.post("/ajax/popup.php", {'msg':msg}, function(data){
		// create a modal dialog with the data
		$(data).modal({
			close: false,
			position: ['0%',],
			overlayId: 'popbox-overlay',
			containerId: 'header',
			onOpen: popbox.open,
			onClose: popbox.close
		});
	});
}

var popbox = {
	redir: null,
	message: null,
	open: function (dialog) {
		// hide all code flashes in firefox
		if (!$.browser.msie) {
			$("object").each(function(i){$(this).attr('style', 'visibility:hidden;');});
		}
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					// todo : add event after open
				});
			});
		});
	},
	show: function (dialog) {
		// focus email input
		setTimeout(function(){
			$('#loginform form input[name="loginemail"]').focus();
		}, 600);
		// login form validate
		$('#loginbtn').click(function (e) {
			e.preventDefault();
			if (popbox.validate()) {
				popbox.message = '<img src="/img/default/ajax-loader.gif" class="popbox-loader" align="absmiddle"/>&nbsp;check account ...';
				$('#loginmsgbox').animate({
					height: '22px'
				}, function(){
					popbox.showError();
					$.ajax({
						url: '/ajax/login.php',
						data: $('#loginform form').serialize(),
						type: 'post',
						cache: false,
						dataType: 'html',
						complete: function (xhr) {
							if (xhr.responseText == '') {
								$('#loginform').fadeOut(200, function () {
									$('#loginbox').fadeOut(200, function () {
										$('#popbox-overlay').fadeOut(200, function () {
											if (popbox.redir) {
												window.open(popbox.redir, '_blank');
											} else if ('/user/register.php' != location.pathname) {
												window.location.reload();
											} else {
												location.href = '/';
											}
										});
									});
								});
							} else if (xhr.responseText == 1) {
								var msg = '<div style="width: 100%; text-align: center; margin-top: 100px;">You have used 6 out of 6 login attempts. <br />You will be unable to login for 15 minutes.</div>';
								$('#loginform').html(msg);	
								$('#loginform').fadeOut(3000, function () {
									$('#loginbox').fadeOut(200, function () {
										$('#popbox-overlay').fadeOut(200, function () {
											window.location.reload();
										});
									});
								});
							} else {
								popbox.message = 'The username and/or password supplied was incorrect.';
								popbox.showError();								
							}
						},
						error: popbox.error
					});
				});
			} else {
				$('#loginmsgbox').animate({
					height: '20px'
				}, popbox.showError);
			}
		});
		// goto forgot password page
		$('#forgotpwbtn').click(function (e) {
			e.preventDefault();
			$.modal.close();
			setTimeout(function(){
				$.get("/ajax/forgot.php", function(data){
				// create a modal dialog with the data
					$(data).modal({
						close: false,
						position: ['0%',],
						overlayId: 'popbox-overlay',
						containerId: 'header',
						onOpen: popbox.open,
						onClose: popbox.close,
						onShow: popbox.show_forgot
					});
				});
			}, 600);
		});
	},
	show_forgot: function (dialog) {
		// focus email input
		setTimeout(function(){
			$('#forgotform form input[name="loginemail"]').focus();
		}, 600);
		var do_submit = function () {
			if (popbox.validate_forgot()) {
				popbox.message = '<img src="/img/default/ajax-loader.gif" class="popbox-loader" align="absmiddle"/>&nbsp;check account ...';
				$('#loginmsgbox').animate({
					height: '22px'
				}, function(){
					popbox.showError();
					$.ajax({
						url: '/ajax/forgot.php',
						data: $('#forgotform form').serialize(),
						type: 'post',
						cache: false,
						dataType: 'html',
						complete: function (xhr) {
							if (xhr.responseText == 'non-existed') {
								popbox.message = 'Your email is non-existed.';
							} else {
								popbox.message = 'Your password has been sent to your email.';
								// close forgot box
								setTimeout(function(){$.modal.close()}, 600);
							}
							popbox.showError();
						},
						error: popbox.error
					});
				});
			} else {
				$('#loginmsgbox').animate({
					height: '20px'
				}, popbox.showError);
			}
		}
		// register form validate
		$('#forgotbtn').click(function (e) {
			e.preventDefault();
			do_submit();
		});
		// fix 'Enter' key bug for IE
		$(document).keypress(function(e){
			switch(e.which){
				case 13 : 
					e.preventDefault();
					do_submit();
					break;
			}
		});
	},
	close: function (dialog) {
		dialog.data.fadeOut(200, function () {
			dialog.container.fadeOut(200, function () {
				dialog.overlay.fadeOut(200, function () {
					// show all code flashes in firefox
					if (!$.browser.msie) {
						$("object").each(function(i){$(this).attr('style', 'visibility:visible;');});
					}
					// unbind events here not to effect other forms
					$(document).unbind("keypress");
					$.modal.close();
				});
			});
		});
	},
	close_reload: function (dialog) {
		dialog.data.fadeOut(200, function () {
			dialog.container.fadeOut(200, function () {
				dialog.overlay.fadeOut(200, function () {
					window.location.reload();
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		popbox.message = '';
		var email = $('#loginemail').val();
		if (!email) {
			popbox.message += 'Email is required. ';
		} else {
			if (!popbox.validateEmail(email)) {
				popbox.message += 'Email is invalid. ';
			}
		}
		if (!$('#loginpassw').val()) {
			popbox.message += 'Password is required. ';
		}
		if (popbox.message.length > 0) {
			return false;
		} else {
			return true;
		}
	},
	validate_forgot: function () {
		popbox.message = '';
		var email = $('#loginemail').val();
		if (!email) {
			popbox.message += 'Email is required. ';
		} else {
			if (!popbox.validateEmail(email)) {
				popbox.message += 'Email is invalid. ';
			}
		}
		if (popbox.message.length > 0) {
			return false;
		} else {
			return true;
		}
	},
	validateEmail: function (email) {
		// trim space first
		var email = this.trim(email);
		var at = email.lastIndexOf("@");
		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;
		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;
		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);
		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;
		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;
		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}
		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	},
	showError: function () {
		$('#loginmsgbox')
			.html(popbox.message)
			.fadeIn(200);
	},
	trim: function (str) {
		return str.replace(/^\s+/, '').replace(/\s+$/, '');
	}
};