/**
 * DrPepper.SignInForm
 *	
 * Sign-In form functionality
 *
 * Author:	Silvan Reinhold
 * Date:	2009-03-17
 **/

//---Made in  NY---------//
$(document).ready(function(){ 		
	errorsToClear = new Array();
	
	$('#btn-register').click(function (){					
			return DrPepper.SignInForm.register();
	});
	
	$('#btn-signin').click(function (){					
			return DrPepper.SignInForm.signIn();
	});
	
	alertErrors();

});


function printErrors(p_asErrors){
		r_sError = "";
		for(var i=0; i < p_asErrors.length; i++){			
			r_sError += p_asErrors[i]+"<br />";			
		}		
		return r_sError;
	}	
	 
   function correctFields(cFields)
	{
		for(h = 0; h < cFields.length; h++)
		{
			cFields[h].setAttribute('class', 'input_correct');
		}
		errorsToClear = [];
	}
	
    function hilightFields(fields)
	{		
		for(i = 0; i < fields.length; i++)
		{
			fields[i].setAttribute('class', 'input_error');
			errorsToClear.push(fields[i]);
		}
	}
		
	function lertUser(pErrors)
	{
		var yes = new LertButton('Close Window', function() {
			//do nothing
		});

		var message = pErrors;
		var errorLert = new Lert(
			message,
			[yes],
			{
				defaultButton:yes
			});

		errorLert.display();

	}



//-------------Made in NY ends---------------//


//-------------Made in CA starts---------------//


var DrPepper = DrPepper || {};
DrPepper.SignInForm = {};

// Error message to display when entries in the submission form require correction
//
DrPepper.SignInForm.ERROR_INVALID = "THE FIELDS MARKED IN RED REQUIRE CORRECTION";

// Alert message to pop up when entries are missing or invalid
//
DrPepper.SignInForm.ALERT_CHECK_VALIDATION			= "Some of the fields you filled out require correction:<br/>";
DrPepper.SignInForm.ALERT_FIELD_REQUIRED			= "%1 is a required field.<br/>"
DrPepper.SignInForm.ALERT_EMAIL_INVALID				= "%1 is not a valid e-mail address.<br/>"
DrPepper.SignInForm.ALERT_ZIP_INVALID				= "%1 is not a valid zipcode.<br/>"
DrPepper.SignInForm.ALERT_PASSWORD_SHORT			= "%1 must be at least 6 characters long.<br/>";
DrPepper.SignInForm.ALERT_PASSWORD_CONFIRM_NOMATCH	= "%1 does not match your chosen password.<br/>";

// Spanish error messages
//
DrPepper.SignInForm.ERROR_INVALID_ES                  = "LOS ESPACIOS EN ROJO NECESITAN CORRECCIÓN";
DrPepper.SignInForm.ALERT_CHECK_VALIDATION_ES         = "Algunos de los espacios de información que llenaste requieren corrección:<br/>";
DrPepper.SignInForm.ALERT_FIELD_REQUIRED_ES           = "%1 es información requerida.<br/>"
DrPepper.SignInForm.ALERT_EMAIL_INVALID_ES            = "La %1 no es una dirección de email válida.<br/>"
DrPepper.SignInForm.ALERT_ZIP_INVALID_ES              = "El %1 no es un código postal válido.<br/>"
DrPepper.SignInForm.ALERT_PASSWORD_SHORT_ES           = "La %1 debe tener mínimo 6 caracteres.<br/>";
DrPepper.SignInForm.ALERT_PASSWORD_CONFIRM_NOMATCH_ES = "%1 no es igual a tu contraseña elegida.<br/>";



// Fields to tab through with the enter key (see init())
//
DrPepper.SignInForm.signInFields = [
	"signin-email", "signin-password", "btn-signin"
];

DrPepper.SignInForm.registerFields = [
	"register-email", "register-password", "register-confirm-password", "register-birthday-day", "register-birthday-month", "register-birthday-year", "register-first-name", "register-last-name", "register-zip-code", "register-gender",  "btn-register"
];


DrPepper.SignInForm.init = function()
{
	// NOTE: g_sLangAbbrev determined in __global.php
	// This var in turn determines whether to use standard English or Spanish validation error messages
	g_sLangSuffix = (g_sLangAbbrev == "es") ? "_ES" : "";
	
	// Allow checkboxes to toggle
	//
	$(".remember-me").click(function() {
		var l_xCheckBox = $(".checkbox", this);
		$(l_xCheckBox).toggleClass("checked");
		$("#remember-me").val($(l_xCheckBox).hasClass("checked") ? 1 : 0);
	});

	$("#opt-in-box").click(function() {
		var l_xCheckBox = $(".checkbox", this);
		$(l_xCheckBox).toggleClass("checked");
		$("#opt-in").val($(l_xCheckBox).hasClass("checked") ? 1 : 0);
	});

	// Focus on the first form field
	//	
	$("#signin-email").focus();
	
	// Click handlers for links and buttons
	//
	//$(".forgot-password").click(DrPepper.SignInForm.forgotPassword);

	$("input, select").change(function() { if ($(this).val() != "") DrPepper.SignInForm.clearErrorHighlights(this); });

	if ($.browser.safari) {
		$("input, select").focus(function() {
			$(this).css("outline", "auto 1px -webkit-focus-ring-color");
		});
		$("input, select").blur(function() {
			$(this).css("outline", "none");
		});
	}

	// Disable selection on "forgot password" and "remember me" elements to avoid unwanted selection during clicks
	//
	DrPepper.Util.disableSelection("signin-aux");
	
	// Avoid unwanted selection on opt-in box
	//
	DrPepper.Util.disableSelection("opt-in-box");

	// The ENTER key will tab through the fields inside the same form.
	//
	$("input, select").keydown(function(e) {
		if (document.getElementById('lertDefaultButton') == null && e.keyCode == 13) {
			// Find out whether the user is currently "tabbing" through the Sign-In or the Registration form
			//
			var l_aArray = DrPepper.SignInForm.signInFields;
			var l_nIndex = $.inArray($(this).attr("id"), l_aArray);
	
			if (l_nIndex == -1) {
				l_aArray = DrPepper.SignInForm.registerFields;
				l_nIndex = $.inArray($(this).attr("id"), l_aArray);
			}
			
			// Pressing ENTER in last field or on the submit button will validate + submit the form
			// 
			if (l_nIndex >= l_aArray.length - 2) {
				if(l_aArray == DrPepper.SignInForm.signInFields) {
					DrPepper.SignInForm.signIn();
				}
				else {
					DrPepper.SignInForm.register();
				}
				return false;
			}
	
			if (l_nIndex != -1) {
				l_nIndex = (l_nIndex >= l_aArray.length - 1) ? 0 : l_nIndex + 1;
			}
	
			$("#" + l_aArray[l_nIndex]).focus();
			
			// Clear error highlight for the field that the user just tabbed away from, if it is not empty
			//
			if ($(this).val() != "") DrPepper.SignInForm.clearErrorHighlights(this);

			// Do not process the ENTER key any further
			return false;
		}
	});

	// Safari won't let us modify the text color on a combo box unless the border is explicitly set; Firefox (Mac) will
	// break the Aqua skin IF the border is set.
	//
	if ($.browser.safari) {
		$("select").css("border", "2px transparent");
	}
}


/**
 * Validate and sign in
 **/
DrPepper.SignInForm.signIn = function()
{
	if ($.browser.safari) {
		$("input, select").css("outline", "none");
	}

	var l_sValidationAlert = DrPepper.SignInForm.validateSignIn();
	
	if (l_sValidationAlert == "") {
		return true;
	}
	else {
		//$("#error-signin").text(DrPepper.SignInForm["ERROR_INVALID"+g_sLangSuffix]);
		//alert(l_sValidationAlert);
		lertUser(l_sValidationAlert);
		return false;
	}
}


/**
 * Validate and register
 **/
DrPepper.SignInForm.register = function()
{
	if ($.browser.safari) {
		$("input, select").css("outline", "none");
	}

	var l_sValidationAlert = DrPepper.SignInForm.validateRegistration();
	
	if (l_sValidationAlert == "") {
		return true;
	}
	else {
		//$("#error-registration").text(DrPepper.SignInForm["ERROR_INVALID"+g_sLangSuffix]);
		lertUser(l_sValidationAlert);
		return false;
	}
}


/**
 * Handler for "forgot password" link
 **/
DrPepper.SignInForm.forgotPassword = function()
{
	alert("forgot your password");
}


/**
 * Validate Sign In form
 **/
DrPepper.SignInForm.validateSignIn = function()
{
	var l_sAlert = "";
	var l_aFailedFields = [];
		
	DrPepper.SignInForm.clearErrorHighlights();

	$(".signin-box input").each(function() {
		var l_sLabelForThisField = DrPepper.SignInForm.getLabelForField(this);

		// *all* fields must be filled in, no exceptions //this prevents the easy addition of hidden fields which may or may not have a value
		//
		if ($(this).val() == "") {
			DrPepper.SignInForm.showErrorHighlight(this);

			if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
				l_sAlert += DrPepper.SignInForm["ALERT_FIELD_REQUIRED"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
			}
			if (l_sAlert == "") {
				$(this).focus();
			}
			l_aFailedFields.push(l_sLabelForThisField);
		}

		// check special cases
		//
		if ($(this).attr("id") == "signin-email") {
			if (!DrPepper.SignInForm.isValidEmail($(this).val())) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_EMAIL_INVALID"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
		else if ($(this).attr("id") == "signin-password") {
			if ($(this).val().length < 6) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_PASSWORD_SHORT"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
	});

	if (l_sAlert != "") {
		l_sAlert = DrPepper.SignInForm["ALERT_CHECK_VALIDATION"+g_sLangSuffix] + l_sAlert;
	}
	return l_sAlert;
}


/**
 * Validate Reigstration form
 **/
DrPepper.SignInForm.validateRegistration = function()
{
	var l_sAlert = "";
	var l_aFailedFields = [];
	
	DrPepper.SignInForm.clearErrorHighlights();

	$(".registration-box input, .registration-box select").each(function() {

		var l_sLabelForThisField = DrPepper.SignInForm.getLabelForField(this);
		
		// *all* fields must be filled in, no exceptions
		//
		if ($(this).attr("value") == "") {
			DrPepper.SignInForm.showErrorHighlight(this);

			if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
				l_sAlert += DrPepper.SignInForm["ALERT_FIELD_REQUIRED"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
			}
			if (l_sAlert == "") {
				$(this).focus();
			}
			l_aFailedFields.push(l_sLabelForThisField);
		}

		// check special cases
		//
		if ($(this).attr("id") == "register-email") {
			if (!DrPepper.SignInForm.isValidEmail($(this).val())) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_EMAIL_INVALID"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
		else if ($(this).attr("id") == "register-password") {
			if ($(this).val().length < 6) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_PASSWORD_SHORT"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
		else if ($(this).attr("id") == "register-confirm-password") {
			if ($(this).val() != $("#register-password").val()) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_PASSWORD_CONFIRM_NOMATCH"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
		else if ($(this).attr("id") == "register-zip-code") {
			if (!DrPepper.SignInForm.isValidZipCode($(this).val())) {
				DrPepper.SignInForm.showErrorHighlight(this);

				if ($.inArray(l_sLabelForThisField, l_aFailedFields) < 0) {
					l_sAlert += DrPepper.SignInForm["ALERT_ZIP_INVALID"+g_sLangSuffix].replace(/%1/, l_sLabelForThisField);
				}
				if (l_aFailedFields.length == 0) {
					$(this).focus();
				}
			}
		}
	});
	
	if (l_sAlert != "") {
		l_sAlert = DrPepper.SignInForm["ALERT_CHECK_VALIDATION"+g_sLangSuffix] + l_sAlert;
	}
	return l_sAlert;
}


/**
 * Show error highlight for specified form field
 *
 * @param p_xDomElement	DOM element to show an error highlight for
 **/
DrPepper.SignInForm.showErrorHighlight = function(p_xDomElement)
{
	$(p_xDomElement).addClass("error-highlight");
}


/**
 * Hide all error highlights, or hide error highlight for a specific form field
 *
 * @param p_xDomElement	DOM element to hide the error highlight for, or null to clear highlights for all form element highlights
 **/
DrPepper.SignInForm.clearErrorHighlights = function(p_xDomElement)
{
	function clear(p_xDomElement)
	{
		$(p_xDomElement).removeClass("error-highlight");
	}
	
	if (p_xDomElement) {
		clear(p_xDomElement);
	}
	else {
		$(".signin-box input, .registration-box input, .registration-box select").each(function() {
			clear(this);
		});
	}
	if ($(".error-highlight").size() == 0) {
		$("#error-signin").text("");
		$("#error-registration").text("");
	}
}


/**
 * Check whether the specified string is a valid e-mail address
 *
 * @param p_sEmail	String to be tested
 * @return			true if valid, false if invalid
 **/
DrPepper.SignInForm.isValidEmail = function(p_sEmail)
{
	var l_xEmailExpression = /^\w+?([\.-]?\w+)+?([\+-\.]?\w+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/i;
	return l_xEmailExpression.test(p_sEmail);
}


/**
 * Return the label title for the specified form field
 *
 * @param p_xField	Form field for which to get the label title
 * @return			Label title (string)
 **/
DrPepper.SignInForm.getLabelForField = function(p_xField)
{
	return $(".form-label label", $(p_xField).parent().parent()).text();
}

/**
 * Check whether the specified string is a valid zipcode
 *
 * @param p_sZipCode	String to be tested
 * @return			true if valid, false if invalid
 **/
DrPepper.SignInForm.isValidZipCode = function(p_sZipCode)
{				
	var l_xZipCodeExpression = 	/^[0-9]{5}$/i;		
	return l_xZipCodeExpression.test(p_sZipCode);
}

//--------------Made in CA ends----------------//


   