

/*************************
	Required for Input/Label redesign
*************************/
var $originalPassword;
var inputFields = function($){
	return{
		validateDoubleEntry : function( firstField, secondField ) {
			var isValid = false;

			// if is undefined the field not exist
			if (firstField == undefined){
				return true;
			}

			if ((firstField.val() != firstField.attr("name")) && ( firstField.val() == secondField ) ){
				isValid = true;
			}

			return isValid;
		},
		originalFieldChanged : function(firstFieldVal, secondFieldVal, validationSelector) {
         	if(( secondFieldVal != "")) {
         		if( secondFieldVal != firstFieldVal)
         			validationSelector.removeClass("valid").addClass("invalid");
         		else
         			validationSelector.removeClass("invalid").addClass("valid");
         	}
		}
	};

}($);

var overLabels = function($) {
	var _getLabelText = function(labelObj) {
		var labelText = labelObj.text();
		
		if($(labelObj).length > 0) {
			if (labelObj.html().indexOf("optionalKey") > 0) {
				labelText = labelText.replace(labelObj.find(".optionalKey").text(), "");
			}
			/* check for asterisk not needed with UEG change to move asterisks outside of the label,
				if asterisks are desired inside the label add this code back in  */
			/*
			else if (labelObj.html().indexOf("asterisk") > 0) {
				labelText = labelText.replace(labelObj.find(".asterisk").text(), "");
			}
			*/
		}
		
		return labelText;
	};

	return {
		checkField : function(field) {
			field.focus().blur();
		},

		resetField : function(field, resetLabel) {
			var _scope = field.parents(".formFieldContainer");
			var myLabel = _scope.find('label');
			var myVerify = _scope.find(".verify");
			myVerify.html("&nbsp;");
			if (resetLabel && _scope.find('select').length == 0) {
				/* this is not a select */
				field.val("");
				myLabel.css('visibility', 'visible');
			}
			_scope.removeClass("valid").removeClass("invalid");
		},

		init : function(_scope) {
			if (_scope.hasClass("overLabeled"))
				return;
			_scope.addClass("overLabeled");
			var myInput = [];
			var fieldType = "input"; /* should be input, select or textarea */
			/* checks for inputs that aren't buttons, then selects, then textareas */
			if (myInput.length == 0) { myInput = _scope.find('input:not([class=formButton],[type=hidden])'); }
			if (myInput.length == 0) { myInput = _scope.find('select'); fieldType = "select"; }
			if (myInput.length == 0) { myInput = _scope.find('textarea'); fieldType = "textarea"; }
			var myLabel = _scope.find('label');
			var myError = _scope.find('.error').text();

			if ($.trim(myInput.val()) == '' && (fieldType != "select")) {
				myLabel.css('visibility', 'visible');
			}

			myLabel.click(function() {
				myInput.focus();
				return false;
			});

			myInput.attr("autocomplete","off");
			if (fieldType != "select") {
				myInput.bind("focus.overLabels", function() {
					myLabel.fadeTo(300, 0);
				}).bind("blur.overLabels", function() {
					myLabel.fadeTo(150, 1);
					if ($.trim(myInput.val()) != '') {
						myLabel.css('visibility', 'hidden');
					} else {
						myLabel.css('visibility', 'visible');
					}
				});
			}

			/* setup the inline validation */
			if (!_scope.hasClass("dontVerify")) {
				/* this could be changed to .before or .after if the message needs to be above or below the input */
				if (_scope.hasClass("tipAbove"))
					myInput.parent().prepend('<span class="verify">&nbsp;</span>');
				else
					myInput.parent().append('<span class="verify">&nbsp;</span>');
					
				var myVerify = _scope.find(".verify");

				myInput.bind("focus.overLabels", function(e){
					_scope.removeClass("invalid").removeClass("valid");
					myVerify.html(_getLabelText(myLabel));
				});

				myInput.bind("blur.overLabels", function(e){
					if ($.trim(myInput.val()) == "") {
						if (myLabel.hasClass("optional"))
							myVerify.html("&nbsp;");
						else
							_scope.addClass("invalid");
					} else if (validate.fieldIsValid(this)) {
						_scope.addClass("valid");
					} else {
						_scope.addClass("invalid");
					}
				});

				/* handle a prefilled form */
				if ($.trim(myInput.val()) != '') {
					myVerify.html(_getLabelText(myLabel));
					if (validate.fieldIsValid(myInput)) {
						_scope.addClass("valid");
					} else {
						_scope.addClass("invalid");
					}
				}
			}

			if (_scope.hasClass("formFieldError")) {
				/* used when a JSP is showing a server side error */
				myInput.clearOverLabel();

			}
		}
	};
}($);

jQuery.fn.checkOverLabel = function(callback){
	/* reruns inline validation, useful if modifying the value via javascript */
	overLabels.checkField(this);
	return this;
};

jQuery.fn.clearOverLabel = function(callback){
	/* reset the inline validation without clearing the value or resetting the label */
	overLabels.resetField(this);
	return this;
};

jQuery.fn.resetOverLabel = function(callback){
	/* reset the inline validation, clears the input value and places the label back in the field */
	overLabels.resetField(this, true);
	return this;
};

var validate = function($) {
	var _isNumeric = function(testStr) {
		var isValid = true;
		var validChars = "0123456789";
		var character;
		if ( typeof(testStr) != "undefined" && testStr != null && testStr != "" ) {
			for (i = 0; i < testStr.length && isValid; i++) {
				character = testStr.charAt(i);
				if (validChars.indexOf(character) == -1) {
					isValid = false;
				}
			}
		} else {
			isValid = false;
		}
		return isValid;
	};

	return {
		fieldIsValid : function(input) {
			var container = $(input).parents(".formFieldContainer");
			var val = $(input).val();
			var inputFormScope = $(input).parents("form");
			var inputReEntryField;
			var inputValidationSelector;
			var isValid = false;
			var classArr = (container.attr("class")).split(" ");
			var fieldType = null;
			for (i=0; i<classArr.length; i++) {
				if (classArr[i].indexOf("type_") == 0) {
					fieldType = classArr[i].replace("type_","");
					break;
				}
			}
			switch (fieldType) {
				case "select":
					if ($.trim(val).length != "")
						isValid = true;
					break;
				case "firstName":
				     
					if ($.trim(val).length > 0)
						isValid = true;
					break;
				case "lastName":
					if ($.trim(val).length > 0)
						isValid = true;
					break;
				case "companyName":
					if ($.trim(val).length > 0)
						isValid = true;
					break;
				case "address":
					if ($.trim(val).length > 0)
						isValid = true;
					break;
				case "city":
					if ($.trim(val).length >= 3)
						isValid = true;
					break;
				case "zipCode":
				    var zipRegex='(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})';
				    var $userInput =val;
				    var checkregex= new RegExp(zipRegex);
					/* run zipCode validation */
					if (checkregex.test($userInput))
					{
						isValid = true;
					}
					break;
				case "storeLocatorText":
					val = $.trim(val);
					if( val != "")
						isValid = true;
					break;
			   case "vat":
				    var vatRegex="^([GB-gb]).(([0-9]{9}|[0-9]{12})|([GD-gd]).[0-9]{3}|([HA-ha]).[0-9]{3})";
				    var $userInput =val;
				  	var checkregex= new RegExp(vatRegex);
					/* run vatNumber validation */
					if (checkregex.test($userInput))
					{
						isValid = true;
					}
					break;
			  case "fiscale":
				    var fiscaleRegex="^[A-Z]{6}[0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]";
				    var $userInput =val;
                	var checkregex= new RegExp(fiscaleRegex);
					/* run fiscale_code validation */
					if (checkregex.test($userInput))
					{
						isValid = true;
					}
					break;
				case "phone":
		            var phoneRegex="^[\\+]{1}[0-9]{5,20}$|[0-9]{5,20}$";
				    var $userInput =val;
				    var numReg = /^[0-9]+$/;
					var strReg = /[A-Za-z]+/;
                    var checkregex= new RegExp(phoneRegex);
					/* run phone validation */
					if (checkregex.test($userInput))
					{
						isValid = true;
					}
					break;
				case "emailAddress":
					val = $.trim(val);
					var re = /^[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}@[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}\.[-\w]{2,4}$/;
					if (re.exec(val)) {
						isValid = true;
						inputReEntryField = inputFormScope.find("input#reEnterEmailAddress");
						inputValidationSelector = inputFormScope.find(".type_emailAddressCheck");
						inputFields.originalFieldChanged(  val, $.trim( inputReEntryField.val() ), inputValidationSelector );
					}
					break;
				case "emailAddressVerify":
					val = $.trim(val);
					var re = /^[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}@[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}\.[-\w]{2,4}$/;
					if (re.exec(val)) {
						inputReEntryField = inputFormScope.find("input.js_emailReEntry");
						inputOriginalField = inputFormScope.find("input.js_originalEmail");
						isValid = inputFields.validateDoubleEntry( inputReEntryField, val) && ! inputFields.validateDoubleEntry( inputOriginalField, val);
					}
					break;
										
				case "emailAddressCheck":				
				val = $.trim(val);
				var re = /^[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}@[-A-Za-z0-9_]+(\.[-A-Za-z0-9_]+){0,3}\.[-\w]{2,4}$/;
				if (re.exec(val)) {
				inputReEntryField = inputFormScope.find("input#emailAddress");
			    inputValidationSelector = inputFormScope.find(".type_emailAddressCheck");
				inputFields.originalFieldChanged($.trim( inputReEntryField.val() ),  val,  inputValidationSelector );
				}
				break;
									
				case "password":
					val = $.trim(val);
					$originalPassword = $("input:not([class=formButton],[type=hidden])", $(this));
					if ((val.length >= 6) && (val.length <= 25)){
						//inputOriginalField = inputFormScope.find("input.js_originalPassword");
						isValid = true;
						inputReEntryField = inputFormScope.find("input#actualPassword");
						inputValidationSelector = inputFormScope.find(".type_passwordVerify");
						//inputOriginalField = inputFormScope.find("input.js_originalPassword");
						inputFields.originalFieldChanged(val, $.trim(inputReEntryField.val()), inputValidationSelector);
					}
					break;
				case "passwordVerify":
					val = $.trim(val);
					
					if ((val.length >= 6) && (val.length <= 25)){
						//inputReEntryField = inputFormScope.find("input.js_passwordReEntry");
						inputNewEntryField = inputFormScope.find(".js_newPassword");
						inputOriginalField = inputFormScope.find(".#type_actualPassword");
						if (inputNewEntryField.val() != undefined){
							isValid = inputFields.validateDoubleEntry(inputNewEntryField, val);
						} else {
							isValid = true;
						}
						if (inputOriginalField.val() != undefined){
							isValid = isValid && !inputFields.validateDoubleEntry( inputOriginalField, val);
						}

					}
					break;
				case "ccName":
					if ($.trim(val).length > 0)
						isValid = true;
					break;
				case "ccNumber":
				  
				    var regex=/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
					var checkregex= new RegExp(regex);
					if ($.trim(val).length > 0 && checkregex.test(val) ){
					 
					 isValid = true;
					
					};
				
					break;
				case "securityCode":
				 var regex=/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
				 var checkregex= new RegExp(regex);
					if ($.trim(val).length >= 3 && checkregex.test(val) )
					{
						var newVal = $.trim(val);
						var re = /^\d+/;
						if( re.exec(newVal) )
						{
						  isValid = true;
						}
					}
					break;
				default :
					return true;
			}
			return isValid;
		}
	};
}($);


$(document).ready(function() {
	$(".formFieldContainer:not(.checkRadio)").each(function(i) {
		overLabels.init($(this));
	});
});

$(function(){

	$(".birthDay").focus(function(){
		var userEmail = $(this).val();
		if (userEmail == 'DD'){
			$(this).val('');
		}
	}).blur(function(){
		var userEmail = $(this).val();
		if (trim(userEmail) == ''){
			$(this).val('DD');
		}
	});
	
	if($(".birthDay").val() == '')
		$(".birthDay").val('DD');
	
	$(".birthMonth").focus(function(){
		var userEmail = $(this).val();
		if (userEmail == 'MM'){
			$(this).val('');
		}
	}).blur(function(){
		var userEmail = $(this).val();
		if (trim(userEmail) == ''){
			$(this).val('MM');
		}
	});
	
	if($(".birthMonth").val() == '')
		$(".birthMonth").val('MM');
	
	$(".birthYear").focus(function(){
		var userEmail = $(this).val();
		if (userEmail == 'YYYY'){
			$(this).val('');
		}
	}).blur(function(){
		var userEmail = $(this).val();
		if (trim(userEmail) == ''){
			$(this).val('YYYY');
		}
	});
	
	if($(".birthYear").val() == '')
		$(".birthYear").val('YYYY');
	
	$(".button").assignMouseEvents();
});

