/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!					
//
//@implementing and optimizing for Talent Banque: Alex Baskov, 2009
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatusForgot = 0;


//loading popup with jQuery magic!
function loadPopupForgot()
{
	//loads popup only if it is disabled
	if(popupStatusForgot == 0)
	{
		$("#popupForgotBackground").css({
			"opacity": "0.5" // set to zero, if you don't want to have a background
		});
		$("#popupForgotBackground").fadeIn("slow");
		$("#popupForgot").fadeIn("slow");
		popupStatusForgot = 1;
	}
	$.validator.addMethod('customEmail', function(value, element) {
		return this.optional(element) || /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(element.value);
		},"Enter a valid "
	);
	forgot_validator = $("#form_forgot").validate({
		errorElement: "div",
		rules: {
			forgot_username: {
				//required: true,
				//minlength: 2,
				maxlength: 200
			},
			forgot_email: {
				//required: true,
				email: true,
				customEmail: true,
				//minlength: 5,
				maxlength: 400
			}
		},
		messages: {
			forgot_username: {
				//required: "Missing your name",
				//minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			forgot_email: {
				//email: "Enter a valid email",
				//customEmail: "Enter a valid email",
				required: "Missing your email",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			}
		},
		errorPlacement: function(error, element) {
				element.next().append(error);
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
			label.parent().hide();
		},
		highlight: function(element, errorClass) {
			$(element).next().show();
		},
		invalidHandler: function() {
			//$("#popupForgot .field_error").show();
		},
		submitHandler: function() {
			//alert("submitted!");
		}
	});
	$("#popupForgot .popup_field input, #popupForgot .popup_field textarea").keypress(function(){
		forgot_validator.element("#" + $(this).attr('id'));
	});
}

//disabling popup with jQuery magic!
function disablePopupForgot()
{
	//disables popup only if it is enabled
	if(popupStatusForgot == 1)
	{
		$("#popupForgotBackground").fadeOut("slow");
		$("#popupForgot").fadeOut("slow");
		popupStatusForgot = 0;
	}
	$("#forgot_username").val("");
	$("#forgot_email").val("");
	$("#form_forgot .field_error").hide();
}

//centering popup
function centerPopupForgot()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupForgot").height();
	var popupWidth = $("#popupForgot").width();

	//
	// we need here to emulate fixed position... so we use offsetHeight and offsetWidth instead
	// (c) Alex Baskov
	//
	var topScrollerPosition = 0;
	
	// we may just scroll to top and see nice popup
	//scroll(0,0);

	// center vertically in the visible area...
	if ($.browser.msie) {
		topScrollerPosition = document.body.scrollTop;
	}
	else {
		topScrollerPosition = window.pageYOffset;
	}

	//centering
	$("#popupForgot").css({
		"position": "fixed",
		"top": windowHeight/2-popupHeight/2,
		//"top": parseInt((windowHeight-popupHeight)/2) + topScrollerPosition,
		//"top": topScrollerPosition + 60,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#popupForgotBackground").css({
		"height": windowHeight
	});
	
}

function showResetSuccess() {
	$("#forgot_form_holder").hide();
	$("#forgot_form_title").text("Thank You");
	$("#forgot_form_desc").html("Successful! Please check your email for details about your password.")
		.removeClass("desc_error");
	$("#forgot_button_ok_holder").show();
}

function showResetProgress() {
    $("#forgot_form_desc").html("Processing request. Please wait!").removeClass("desc_error");
}

function showResetErrors() {
	$("#forgot_form_holder").hide();
	$("#forgot_form_title").text("Try Again");
	if ($("#forgot_form_desc").html() == "") {
		$("#forgot_form_desc").html("Sorry we checked that your Username does not match with your email address. <br />Please try again.");
	}
	$("#forgot_form_desc").addClass("desc_error");
	$("#forgot_form_holder").show();
}

function sendPasswordReset() {
	if (!$("#forgot_email").val()) {
		$("#forgot_form_desc").html("A valid email address is required.");
		$("#forgot_form_desc").addClass("desc_error");
		return false;
	}
	if (!(forgot_validator.form())) {
		return false;
	}

	var data = "username=" + escape($("#forgot_username").val()) +
			   "&email=" + escape($("#forgot_email").val());
    
    var url = "";
    if ($("#popupForgot input[type=radio]:checked").val() == "Client") {
        url = "/external/user/forgotPassword";
    }
    else {
        url = "/external/user/forgotArtistPassword";
    }

	showResetProgress();
	$.ajax({
		type: "POST",
		url: url,
		data: data,
		success: function(msg) {
			if (msg.indexOf("success:") != -1) {
			   showResetSuccess();
			}
			else if (msg.indexOf("error:") != -1) {
				var errors = msg.substring(msg.indexOf("error:") + "error:".length);
				var errorsList = errors.split(";");
				var message = "";
				for (var i = 0; errorsList.length; i++) {
					var errorInfo = errorsList[i];
					if (errorInfo == undefined || errorInfo == "") {
						break;
					}
                    var splitted = errorInfo.split("=");
					var key = splitted[0];
					var value = splitted[1];
					message += key + ": " + value +"<br/>";
				}
				if (message == "") message = "Error during sending request.";
				if (message.indexOf("Value is required") > 0) {
					message = "A valid email address is required.";
				}
                $("#forgot_form_desc").html(message);
				showResetErrors();
			}
		}
	});
	return false;
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function() {

	//LOADING POPUP
	//Click the button event!
	
	$("#linkIamSuperLucky, #loginButtonForgot").click(function() {
		$("#forgot_form_title").text("Retrieve Password");
		
		disablePopupLogin();
		
		$("#forgot_form_desc")
			.html("Please fill in your email and hit Submit. We will send your password to your email. ")
			.removeClass("desc_error");
		$("#forgot_button_ok_holder").hide();
		$("#forgot_form_holder").show();
		
		//centering with css
		centerPopupForgot();
		//load popup
		loadPopupForgot();
	});
				
	//CLOSING POPUP
	$("#popupForgotClose, #buttonForgotOk").click(function() {
		disablePopupForgot();
	});
	
	//Click out event!
	$("#popupForgotBackground").click(function() {
		disablePopupForgot();
	});
	
	//Press Escape event!
	$(document).keypress(function(e) {
		if(e.keyCode == 27 && popupStatusForgot == 1) {
			disablePopupForgot();
		}
	});

});


