﻿var AuthBase = Class.extend
({
	container: null,
	globalContainer: null,

	init: function(params) {
	},

	clearInvalid: function(selector) {
		if ($(selector, this.getContainer()).siblings('.erorMsg').length > 0) {
			$('#' + this.globalContainer).height($('#' + this.globalContainer).height() - 15);
			$(selector, this.getContainer()).siblings('.erorMsg').remove();
		}

		$(selector, this.getContainer()).parent().removeClass('error');
	},

	markInvalid: function(selector, error) {
		$('#' + this.globalContainer).height($('#' + this.globalContainer).height() + 15);
		$(selector, this.getContainer()).parent().addClass('error');
		$('<span class="erorMsg">' + error + '</span>').insertAfter($(selector, this.getContainer()));
	},

	validateEmail: function(email) {
		var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		if (email != '' && emailReg.test(email) == false) {
			return false;
		}

		return true;
	},

	getContainer: function() {
		return $('#' + this.container).get(0);
	},

	clearErrors: function() {
	}
});

/******************************************Login*******************************************/
SignInManager = AuthBase.extend({
	init: function(params) {
		this.container = params.container;
		this.globalContainer = params.globalContainer;
		this.servicePath = params.servicePath;
		this.formName = params.formName;
	},

	login: function() {
		if (!this.validate()) {
			return false;
		}

		var email = $.trim($('#xemail', this.getContainer()).val());
		var password = $('#pwd', this.getContainer()).val();
		var remember = $('#rememberme', this.getContainer()).length > 0 ? $('#rememberme', this.getContainer()).get(0).checked : true;

		$('#loadingBox', this.getContainer()).show();

		var manager = this;

		$.ajax({
			type: "POST",
			url: this.servicePath + '/LoginUser',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			data: $.toJSON({ email: email, password: password, rememberMe: remember }),
			success: function(data) {
				var result = data.d;

				if (result == true) {
					$('#xemail', manager.getContainer()).val(email);
					document.forms[manager.formName].submit();
				}
				else {
					manager.markInvalid('#pwd', 'Incorrect email or password');
				}

				$('#loadingBox', manager.getContainer()).hide();
			},
			error: function(xhr, msg) {
				$('#loadingBox', manager.getContainer()).hide();

				var response = $.toJSON(xhr.responseText);

				alert('Error occured during processing request.');
			}
		});

		return false;
	},

	validate: function() {
		var result = true;

		this.clearErrors();

		var email = $.trim($('#xemail', this.getContainer()).val());
		var password = $('#pwd', this.getContainer()).val();

		// Validate required fields
		if (email == '') {
			this.markInvalid('#xemail', 'Email is required');
			result = false;
		}

		if (this.validateEmail(email) == false) {
			this.markInvalid('#xemail', 'Incorrect email');
			result = false;
		}

		if (password == '') {
			this.markInvalid('#pwd', 'Password is required');
			result = false;
		}

		return result;
	},

	clearErrors: function() {
		this.clearInvalid('#xemail');
		this.clearInvalid('#pwd');
	}
});

/******************************************Registration************************************/
SignUpManager = AuthBase.extend({
	init: function(params) {
		this.container = params.container;
		this.globalContainer = params.globalContainer;
		this.registerUrl = params.registerUrl;
		this.formName = params.formName;

		this.attachEvents();
	},

	attachEvents: function() {
		var manager = this;

		$('#reason', this.getContainer()).change(function() {
			var reason = $(this).val();

			if (reason == 'FRIEND') {
				$('.reasonCont', manager.getContainer()).show();
			}
			else {
				$('.reasonCont', manager.getContainer()).hide();
			}
		});

		$('#terms', this.getContainer()).click(function() {
			var dialog = new PixDialog('#termsPopup', { title: 'AdoramaPix Terms and Conditions', autoOpen: false, dialogClass: 'JOBPopup', width: 560, height: 507 });

			dialog.onHiding = function() { dialog.destroy(); };

			dialog.show();
		});

		$('#agreement', this.getContainer()).click(function() {
			manager.clearInvalid('#agreement');
		});
	},

	collect: function(isFlash) {
		var result = {};

		result.FirstName = $('#firstName', this.getContainer()).val();
		result.LastName = $('#lastName', this.getContainer()).val();
		result.Email = $.trim($('#email', this.getContainer()).val());
		result.Password = $('#password', this.getContainer()).val();
		result.ConfirmPassword = $('#confirmPassword', this.getContainer()).val();
		result.Reason = $('#reason', this.getContainer()).val();
		result.FriendEmail = $('#friendEmail', this.getContainer()).val();
		result.RegisterUrl = '';
		result.IsFlashLogin = isFlash;
		result.Reasons = [];

		return result;
	},

	register: function(isFlashLogin) {
		if (!this.validate()) {
			return false;
		}

		var model = this.collect(isFlashLogin);

		$('#loadingBox', this.getContainer()).show();

		var manager = this;

		$.post
		(
			this.registerUrl,
			model,
			function(result) {
				$('#loadingBox', manager.getContainer()).hide();

				if (result.Succeeded == true) {
					window.location.href = result.Data.Url;
				}
				else if (result.Succeeded == false && result.Data.Error != null) {
					manager.markInvalid('#email', result.Data.Error);
				} else {
					alert('Error occured during registration.');
				}
			},
			'json'
		);
	},

	validate: function() {
		var result = true;

		this.clearErrors();
		
		var model = this.collect();

		if (model.FirstName == '') {
			this.markInvalid('#firstName', 'First Name is required');
			result = false;
		}

		if (model.LastName == '') {
			this.markInvalid('#lastName', 'Last Name is required');
			result = false;
		}

		if (model.Email == '') {
			this.markInvalid('#email', 'Email is required');
			result = false;
		}

		if (this.validateEmail(model.Email) == false) {
			this.markInvalid('#email', 'Incorrect email');
			result = false;
		}

		if (model.Password == '') {
			this.markInvalid('#password', 'Password is required');
			result = false;
		}

		if (model.Reason == 'NONE') {
			this.markInvalid('#reason', 'We would like to know how did you hear about us');
			result = false;
		}

		if (model.Password != model.ConfirmPassword) {
			this.markInvalid('#password', 'Passwords are not equal');
			result = false;
		}

		var agreement = $('#agreement', this.getContainer()).get(0).checked;

		if (agreement == false) {
			this.markInvalid('#agreement', 'Please check to agree our terms and conditions');
			result = false;
		}

		return result;
	},

	clearErrors: function() {
		this.clearInvalid('#firstName');
		this.clearInvalid('#lastName');
		this.clearInvalid('#email');
		this.clearInvalid('#password');
		this.clearInvalid('#confirmPassword');
		this.clearInvalid('#reason');
		this.clearInvalid('#agreement');
	}
});

/******************************************Login Popup*******************************************/
var LoginPopupManager = Class.extend
({
	container: null,
	isShown: false,

	init: function(params) {
		this.container = $('#' + params.container);
	},

	startup: function() {
		var popup = this;

		$(this.container.get(0)).find("#loginMenu li").click(function() {
			$(this).addClass("active").siblings().removeClass("active");
			$(popup.container.get(0)).find("." + this.id).addClass("active").fadeIn(300).siblings().not("#loginMenu").removeClass("active").fadeOut(10);

			popup.clearErrors();
		});

		var testimonialCache = $(".loginMarketing li", this.container.get(0));
		var randomTestimonial = Math.round(Math.random() * testimonialCache.length - 1)
		testimonialCache.eq(randomTestimonial).siblings().hide();

	},

	clearErrors: function() {
		try {
			var signUpManager = jQuery.data($('#loginPop #signUpBlock').get(0), 'manager');
			var signInManager = jQuery.data($('#loginPop #signInBlock').get(0), 'manager');
			var socialSignUpManager = jQuery.data($('#loginPop #socialSignUpBlock').get(0), 'manager');

			signUpManager.clearErrors();
			signInManager.clearErrors();
			socialSignUpManager.clearErrors();
		} catch (e) {
			//do nothing picasa issue
		}
	},
	showSocialLogin: function(email, openId, firstName, lastName) {
		var popup = this;
		$(popup.container.get(0)).find("#socialSignUpBlock #signUpSocialUser").text("Confirm and create account");
		$(popup.container.get(0)).find("#socialSignUpBlock .signUpMsg").text("You are almost done. All we need from you is your email address to be able to send you transactional emails and job updates.");
		$(popup.container.get(0)).find("#signUpContainer").addClass("active").siblings().removeClass("active");
		$(popup.container.get(0)).find(".socialSignUpContainer").addClass("active").fadeIn(300);
		$(popup.container.get(0)).find(".signInContainer").removeClass("active").fadeOut(10);
		$(popup.container.get(0)).find(".signUpContainer").removeClass("active").fadeOut(10);
		$(popup.container.get(0)).find(".socialSignUpContainer #emailAddress").val(email);
		if (email.length > 0) {
			$(popup.container.get(0)).find(".socialSignUpContainer li.emailCont").hide();
			$(popup.container.get(0)).find("#socialSignUpBlock .signUpMsg").text("Please verify that you agree with our Terms and Conditions so we can create your AdoramaPix account (Your facebook account will be linked to it automaticaly).");
		}
		$(popup.container.get(0)).find(".socialSignUpContainer #OpenId").val(openId);
		$(popup.container.get(0)).find(".socialSignUpContainer #Fname").val(firstName);
		$(popup.container.get(0)).find(".socialSignUpContainer #Lname").val(lastName);

		popup.clearErrors();
	},
	resetStatus: function() {
		this.isShown = false;
	},

	show: function(closeFrame) {
		if (this.isShown)
			return;
		var dialog = new PixDialog('#loginPop', { title: 'Login', autoOpen: false, dialogClass: 'JOBPopup', width: 462 });

		dialog.onHiding = function() {
			loginPopupManager.resetStatus();
			dialog.destroy();
			if (closeFrame) {
				closeFrame.call();
			}
		};

		dialog.show();
		$(".loginMarketing .testimonialsInnerContainer").height($(".loginMarketing li:visible").height() + 70);
		$('#loginPop').parent().addClass('loginPopupWrapper');
		this.isShown = true;
	}
});

/******************************************Registration(SocialSignUpManager)************************************/
SocialSignUpManager = AuthBase.extend({
	init: function(params) {
		this.container = params.container;
		this.globalContainer = params.globalContainer;
		this.registerUrl = params.registerUrl;
		this.formName = params.formName;

		this.attachEvents();
	},

	attachEvents: function() {
		var manager = this;

		$('#socialterms', this.getContainer()).click(function() {
			var dialog = new PixDialog('#termsPopup', { title: 'AdoramaPix Terms and Conditions', autoOpen: false, dialogClass: 'JOBPopup', width: 560, height: 507 });

			dialog.onHiding = function() { dialog.destroy(); };

			dialog.show();
		});

		$('#SocialAgreement', this.getContainer()).click(function() {
			manager.clearInvalid('#SocialAgreement');
		});
	},

	collect: function(isFlash) {
		var result = {};

		result.FirstName = $('#Fname', this.getContainer()).val();
		result.LastName = $('#Lname', this.getContainer()).val();
		result.Email = $.trim($('#emailAddress', this.getContainer()).val());
		result.OpenId = $('#OpenId', this.getContainer()).val();
		result.Password = $('#currentPassword', this.getContainer()).val();
		result.NextPage = $('input[name=nextpage]', this.getContainer()).val();
		result.RegisterUrl = '';
		result.NeedToLinkAccount = false;
		return result;
	},

	register: function(isFlashLogin) {
		if (!this.validate()) {
			return false;
		}

		var model = this.collect(isFlashLogin);

		$('#loadingBox', this.getContainer()).show();

		var manager = this;

		$.post
		(
			this.registerUrl,
			model,
			function(result) {
				$('#loadingBox', manager.getContainer()).hide();

				if (result.Succeeded == true) {
					window.location.href = result.Data.Url;
				}
				else if (result.Succeeded == false && result.Data.Error != null) {
					if (result.Data.ErrorCode != "registred") {
						if (result.Data.Error.length > 0) {
							manager.markInvalid('#currentPassword', result.Data.Error);
						}
						$(manager.getContainer()).find(".socialSignUpContainer li.passwordCont").show();
						$(manager.getContainer()).find("#socialSignUpBlock .signUpMsg").text("Please enter you AdoramaPix password so we can link your Twitter to AdoramaPix account.");
						$(manager.getContainer()).find("#socialSignUpBlock #signUpSocialUser").text("Confirm and link accounts");
					} else {
						$(manager.getContainer()).find(".socialSignUpContainer li.passwordCont").hide();
						manager.markInvalid('#emailAddress', "You have already used this email address to log in with another third party provider (Facebook or Twitter). Please close this window and log in with the third party provider you previously used.");
					}

				} else {
					alert('Error occured during registration.');
				}
			},
			'json'
		);
	},

	validate: function() {
		var result = true;

		this.clearErrors();

		var model = this.collect();


		if (model.Email == '') {
			this.markInvalid('#emailAddress', 'Email is required');
			result = false;
		}

		if (this.validateEmail(model.Email) == false) {
			this.markInvalid('#emailAddress', 'Incorrect email');
			result = false;
		}

		if (model.Password == '' && model.NeedToLink) {
			this.markInvalid('#currentPassword', 'Password is required');
			result = false;
		}

		var agreement = $('#SocialAgreement', this.getContainer()).get(0).checked;

		if (agreement == false) {
			this.markInvalid('#SocialAgreement', 'Please check to agree our terms and conditions');
			result = false;
		}

		return result;
	},

	clearErrors: function() {
		this.clearInvalid('#emailAddress');
		this.clearInvalid('#currentPassword');
		this.clearInvalid('#SocialAgreement');
	}
});

/******************************************Login Popup*******************************************/

