﻿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 = $('#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) {
					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 = $('#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 = $('#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 {
					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,

	init: function(params) {
		this.container = $('#' + params.container);
	},

	startup: function() {
		var popup = this;

		$("#loginMenu li", this.container.get(0)).click(function() {
			$(this).addClass("active").siblings().removeClass("active");
			$("." + this.id).addClass("active").fadeIn(300).siblings().not("#loginMenu", popup.container.get(0)).removeClass("active").fadeOut(300);

			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() {
		var signUpManager = jQuery.data($('#loginPop #signUpBlock').get(0), 'manager');
		var signInManager = jQuery.data($('#loginPop #signInBlock').get(0), 'manager');

		signUpManager.clearErrors();
		signInManager.clearErrors();
	},

	show: function(closeFrame) {
		var dialog = new PixDialog('#loginPop', { title: 'Login', autoOpen: false, dialogClass: 'JOBPopup', width: 462 });

		dialog.onHiding = function() {
			dialog.destroy();
			if (closeFrame) {
				closeFrame.call();
			}
		};

		dialog.show();

		$('#loginPop').parent().addClass('loginPopupWrapper');
	}
});