// SECTION FUNCTIONS
var closeDirectionsPopup = function(){
	$("#directions").css("display", "none");
}
$.fn.changeLocation = function(){
	var container = $(this).parent().parent();
	switch($(this).attr("value")){

		case "domestic":
			$($(container).children("label.address3").get(0)).addClass('hidden');
			$($(container).children("label.address4").get(0)).addClass('hidden');
			$($(container).children("label.countryField").get(0)).addClass('hidden');
			$($(container).children("label.otherCountryField").get(0)).addClass('hidden');
			$($(container).children("label.postalcodeField").get(0)).addClass('hidden');
			$($(container).children("label.stateField").get(0)).removeClass('hidden');
			$($(container).children("label.zipField").get(0)).removeClass('hidden');
			$($(container).children("label.provinceField").get(0)).addClass('hidden');
			break;
		case "canada":
			$($(container).children("label.address3").get(0)).removeClass('hidden');
			$($(container).children("label.address4").get(0)).removeClass('hidden');
			$($(container).children("label.stateField").get(0)).addClass('hidden');
			$($(container).children("label.zipField").get(0)).addClass('hidden');
			$($(container).children("label.provinceField").get(0)).removeClass('hidden');
			$($(container).children("label.postalcodeField").get(0)).removeClass('hidden');
			$($(container).children("label.countryField").get(0)).addClass('hidden');
			$($(container).children("label.otherCountryField").get(0)).addClass('hidden');
			break;
		case "international":
			$($(container).children("label.address3").get(0)).removeClass('hidden');
			$($(container).children("label.address4").get(0)).removeClass('hidden');
			$($(container).children("label.stateField").get(0)).addClass('hidden');
			$($(container).children("label.provinceField").get(0)).addClass('hidden');
			$($(container).children("label.zipField").get(0)).addClass('hidden');
			$($(container).children("label.provinceField").get(0)).addClass('hidden');
			$($(container).children("label.postalcodeField").get(0)).removeClass('hidden');
			$($(container).children("label.countryField").get(0)).removeClass('hidden');

			if($($(container).children("label.countryField select").get(0)).val() != "XX"){
				$($(container).children("label.otherCountryField").get(0)).removeClass('hidden');
			} else {
				$($(container).children("label.otherCountryField").get(0)).addClass('hidden');
			}
			break;
	}
}

$.fn.autoClearWatermark = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue || this.value == "" ) {
			$(this).removeClass('loginEmailBG');
		}
	}).blur(function() {
		if( !this.value.length ) {
			$(this).addClass('loginEmailBG');
		}
	});
}

$.fn.autoClearPasswordWatermark = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			$(this).removeClass('loginPasswordBG');
		}
	}).blur(function() {
		if( !this.value.length ) {
			$(this).addClass('loginPasswordBG');
		}
	});
}

// This stops multiple AJAX request from being fired off
var pendingRequest;




$(document).ready(function(){
	
	//Added for clearning the fields for wishList email functionality
	$(".sendemail input.required").click(function(){
		if(!($(this).attr("id") == "fromname" || $(this).attr("id") =="fromEmail")){
		    	$(this).val("")
	    	}
	  })

	// SEGMENT THE JS FUNCTIONS BY BODY CLASS, ID TO AVOID COMFLICTS

	/* Create Account Page Functions */
	if($("body#createAccount").length > 0){

		//Initializes the Classic Awards awardInfo fieldset if radio button is yes fieldset is open, closes if radio is no
			if($("#yesRewards:checked").length > 0){
				$("#awardsInfo").show();
			} else if($("#noRewards:checked").length > 0){
				$("#awardsInfo").hide();
			}

		$("fieldset#f_awardsMember").click(function(e){

			var el = $("fieldset#f_awardsMember input:checked").get(0);
			if($(el).attr("id") == "yesRewards"){
				$("#awardsInfo").show();
			} else {
				$("#awardsInfo").hide();
			}
		});

		$("#morereasons").click(function (){
			$('#registerFAQ').jqm();
			$('#registerFAQ').jqmAddClose($('.closeButton'));
			$('#registerFAQ').jqmShow();
		});

		
		if($(".loginPasswordBG").length > 0){
			$("#loginEmail").autoClearWatermark();
			
			if($("#loginEmail").value == "") {
				$("#loginEmail").addClass('loginEmailBG');
			} 
			
			$("#loginPassword").autoClearPasswordWatermark();
			$("#loginPassword").addClass('loginPasswordBG');
		}
		
		/*
			This is for the security login box, it listens for a
			submit of the  login form, creates an ajax form get to a
			service url and then populates the security question
		*/
		$('#securityQuestionWindow').jqm();
		$('#securityQuestionWindow').jqmAddClose($('.closeButton'));
		/* ajax integration code */
		//listen for the login form, submit it and return the security question.

		$("#loginForm").bind("submit", function(){
			//test that the login form is valid, then continue on processing the form
			if($("form#loginForm").valid()){
				/* form IS valid */
				if(pendingRequest != true){
					pendingRequest = true;
					action = $(this).attr("action");
					method = $(this).attr("method");
					var data = new Array;
					$("form#loginForm input").each(function(){
						//collect form data
						var type = $(this).attr("type");
						if(type != "submit" && type != "reset" && type != "button"){
							var prop = $(this).attr("name");
							if(type == "checkbox"){
								var value = $(this).attr("checked");
							} else {
								var value = escape($(this).attr("value"))
							}
							data.push(prop + "=" + value);
						}
					})

					$.ajax({
						type: "POST",
						url: action,
						//dataType: json,
						data: $("form#loginForm").serialize(),
						beforeSend: function(xhr) {
							xhr.setRequestHeader( "Accept", "text/json" );
	              		},

						success: function(data){
							pendingRequest = false;
							var data = data;
							if(data.error == "false"){
								$("#answerErrors").css("display", "none")
								$('#securityQuestionWindow').jqm();
								$("#actualQuestion").html(data.loginQuestion);
								document.getElementById('login').value=data.eMail;
								document.getElementById('pwd').value=data.pwd;
								$('#securityQuestionWindow').jqmShow();
								$("#securityAnswerModal").val("").focus();
								return false;
							} else {
									if(data.answerError == "TRUE"){
										$("#answerErrors ul").html("<li>"+ data.errors +"</li>")
									    $("#answerErrors, #answerErrors ul").show()
										$("#securityAnswerModal").val("").focus();
										//return false;

									}	else if (data.answerError == "FALSE"){
										if(data.errors == "You have attempted to login 3 times")
										{
											$("#loginErrors ul").html("<li>"+ "You have attempted to login 3 times. <a href='forgot_password.jsp'>Click Here</a> to have your password e-mailed to you, and then try again" +"</li>")
										}
										else if(data.errors == "You have attempted to login 4 times")
										{
											$("#loginErrors ul").html("<li>"+ "You have attempted to login 4 times.<a href='forgot_password.jsp'>Click Here</a> to have your password e-mailed to you, and then try again. If you fail to login successfully, you'll be temporarily locked out." +"</li>")
										}
										else
										{
											$("#loginErrors ul").html("<li>"+ data.errors +"</li>")
										}
										    $("#loginErrors, #loginErrors ul").show();
										//return false;
									}
								else{
									window.location=data.loginSuccessURL;
									return false;
								}
							}


						},
						error: function(responce){
							alert("There was an issue while trying to log in, please try again in a few minutes or contact customer service");
							pendingRequest = false;
						}
					});
				}


				return false;
			}
		});


		$("#checkOutLoginForm").bind("submit", function(){
			//test that the login form is valid, then continue on processing the form
			if($("form#checkOutLoginForm").valid()){
				/* form IS valid */
				if(pendingRequest != true){
					pendingRequest = true;
					action = $(this).attr("action");
					method = $(this).attr("method");
					var data = new Array;
					$("form#checkOutLoginForm input").each(function(){
						//collect form data
						var type = $(this).attr("type");
						if(type != "submit" && type != "reset" && type != "button"){
							var prop = $(this).attr("name");
							if(type == "checkbox"){
								var value = $(this).attr("checked");
							} else {
								var value = escape($(this).attr("value"))
							}
							data.push(prop + "=" + value);
						}
					})

					$.ajax({
						type: "POST",
						url: action,
						//dataType: json,
						data: $("form#checkOutLoginForm").serialize(),
						beforeSend: function(xhr) {
							xhr.setRequestHeader( "Accept", "text/json" );
	              		},

						success: function(data){
							pendingRequest = false;
							var data = data ;
							if(data.error == "false"){
								$("#answerErrors").css("display", "none")
								$('#securityQuestionWindow').jqm();
								$("#actualQuestion").html(data.loginQuestion);
								document.getElementById('login').value=data.eMail;
								document.getElementById('pwd').value=data.pwd;
								$('#securityQuestionWindow').jqmShow();
								$("#securityAnswerModal").val("").focus();

								return false;
							} else {
									if(data.answerError == "TRUE"){
										$("#answerErrors ul").html("<li>"+ data.errors +"</li>")
									    $("#answerErrors, #answerErrors ul").show()
										$("#securityAnswerModal").val("").focus();
										//return false;

									}	else if (data.answerError == "FALSE"){
										if(data.errors == "You have attempted to login 3 times")
										{
											$("#loginErrors ul").html("<li>"+ "You have attempted to login 3 times. <a href='forgot_password.jsp'>Click Here</a> to have your password e-mailed to you, and then try again" +"</li>")
										}
										else if(data.errors == "You have attempted to login 4 times")
										{
											$("#loginErrors ul").html("<li>"+ "You have attempted to login 4 times.<a href='forgot_password.jsp'>Click Here</a> to have your password e-mailed to you, and then try again. If you fail to login successfully, you'll be temporarily locked out." +"</li>")
										}
										else
										{
											$("#loginErrors ul").html("<li>"+ data.errors +"</li>")
										}
										    $("#loginErrors, #loginErrors ul").show();
										//return false;
									}
								else{
									window.location=data.loginSuccessURL;
									return false;
								}
							}


						},
						error: function(responce){
							alert("There was an issue while trying to log in, please try again in a few minutes or contact customer service");
							pendingRequest = false;
						}
					});
				}


				return false;
			}
		});


		$("#loginForm1").bind("submit", function(){
			//test that the login form is valid, then continue on processing the form

			if($("form#loginForm1").valid()){
				/* form IS valid */
				if(pendingRequest != true){
					$("#answerErrors ul li").remove();
					pendingRequest = true;
					action = $(this).attr("action");
					method = $(this).attr("method");

					$.ajax({
						type: "POST",
						url: action,
						//dataType: json,
						data: $("form#loginForm1").serialize(),
						beforeSend: function(xhr) {
							xhr.setRequestHeader( "Accept", "text/json" );
	              		},

						success: function(data, textStatus){
						pendingRequest = false;
	              			try {

		              			var data =  data;

								if(data.error == "true"){
										if(data.answerError == "TRUE"){
											$("#answerErrors ul").html("<li>"+ data.errors +"</li>");
										    $("#answerErrors, #answerErrors ul").show();
										}
								}else{
									 window.location=data.loginSuccessURL;
									return false;
								}
							}catch(e) {
								alert("There was an issue while trying to log in, please try again in a few minutes or contact customer service");
								return false;
							}
						},
						error: function(responce1){
							pendingRequest = false;
							//window.location='/myaccount/myinformation.jsp';
							alert("There was an issue while trying to log in, please try again in a few minutes or contact customer service");
						}
					});
				}
				return false;
			}
		});
/* ajax integration code */
		$("form#loginForm").validate({
			errorContainer: "#loginErrors",
			errorLabelContainer: "#loginErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				loginEmail: {
					required: true,
					email: true
				},
				loginPassword: {
					required: true
				}
			},
			messages: {
				 loginEmail: {
				   required: "Email address is required",
				   email: "Your email address must be in the format of name@domain.com"
				 },
				 loginPassword: {
				   required: "Password is required"
				 }
			}
		});


		$("form#checkOutLoginForm").validate({
			errorContainer: "#loginErrors",
			errorLabelContainer: "#loginErrors ul",
			// add rules to override defaults e.g., minlength
			rules: {
				loginEmail: {
					required: true,
					email: true
				},
				loginPassword: {
					required: true
				}
			},
			messages: {
				 loginEmail: {
				   required: "Email address is required",
				   email: "Your email address must be in the format of name@domain.com"
				 },
				 loginPassword: {
				   required: "Password is required"
				 }
			}
		});


		// Validates the Create Account Form
		$("form#accountCreate").validate({
			errorContainer: "#registerErrors",
			errorLabelContainer: "#registerErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				firstName: {
					required: true
				},
				lastName: {
					required: true
				},
				emailAddress: {
					required: true,
					email: true
				},
				confirmEmail: {
					required: true,
					email: true
					//equalTo: "#emailAddress"
				},
				password:{
					required: true
				},
				confirmPassword: {
					required: true,
					equalTo: "#password"
				},
				securityQuestion:{
					required: true
				},
				securityAnswer:{
					required: true
				},
				address1:{
					required:function(element){
							return $("#catalogSignup:checked").length > 0;
					}
				},
				city:{
					required:function(element){
							return $("#catalogSignup:checked").length > 0;
					}
				},
				country:{
					required:function(element){

						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="international");
					}
				},
				state:{
					required:function(element){
						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="domestic");
					}
				},
				province:{
					required:function(element){
						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="canada");
					}
				},
				postalCode:{
					required:function(element){
						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="canada");
					}
				},
				zipCode:{
					required:function(element){
						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="domestic");
					}
				},
				otherCountry:{
					required:function(element){
						return ($("#catalogSignup:checked").length > 0 && $("#addressLocation:filled").val()=="international" && $("#indicateCountry:filled").val()=="XX");
					}
				}
			},
			messages: {

				 firstName:{
					required: "Please provide your first name"
				 },
				 lastName:{
					required: "Please provide your last name"
				 },
				 emailAddress: {
				   required: "Please provide a valid email address ",
				   email: "Your email address must be in the format of name@domain.com"
				 },
				 confirmEmail: {
				   required: "Please provide a valid confirmed email address",
				   email: "Your email address must be in the format of name@domain.com"
				   //equalTo: "Your email addresses do not match"
				 },
				 password:{
					required: "Please provide a valid password for your account"
				 },
				 confirmPassword:{
					required: "Please re-enter your password in the confirm password field",
					equalTo: "Confirmation of password does not match with password provided"
				 },
				 securityQuestion:{
					required: "Please select a security question"
				 },
				 securityAnswer:{
					required: "Please provide a valid security answer"
				 },
				 address1:{
					required: "Please provide a value for address line #1"
				 },
				 city:{
					required: "Please provide a value for city"
				 },
				 country:{
					required: "Please select a country"
				 },
				 state:{
					required: "Please select a state"
				 },
				 province:{
					required: "Please select a province"
				 },
				 postalCode:{
					required: "Please provide a Postal code"
				 },
				 zipCode:{
					required: "Please provide a Zip code"
				 },
				 otherCountry:{
					required: "Please provide an Other country"
				 }
			}
		});


		/* End Create Account Page Functions */




	} else if( $("body#myInformation").length > 0){

		$("form#updateContact").validate({
			errorContainer:"#formErrors",
			errorLabelContainer:"#formErrors ul",
			wrapper: "li",
			rules:{
				emailAddress:{
					required:true,
					email: true
				},
				confirmEmail:{
					required:true,
					email: true,
					equalTo:"#emailAddress"
				}
			},
			messages:{
				emailAddress:{
					required:"You must enter an email address"
				},
				confirmEmail:{
					required:"You must confirm your email address",
					equalTo:"Both email addresses must match"
				}
			}
		});

		$("form#changePassword").validate({
			errorContainer: "#passwordErrors",
			errorLabelContainer: "#passwordErrors ul",
			wrapper: "li",
			rules:{
				presentPassword:{
					required: true
				},
				newPassword:{
					required:true
				},
				confirmPassword:{
					required: true,
					equalTo: "#newPassword"
				}
			},
			messages:{
				confirmPassword:{
					required: "You must enter your old password again",
					equalTo:"Your new passwords must match"
				}
			}
		});

		$("form#changeQuestion").validate({
			errorContainer: "#securityErrors",
			errorLabelContainer: "#securityErrors ul",
			wrapper: "li",
			rules:{
				secretAnswer:{
					required: true
				}
			}
		});


		/* My Account Page Functions */

		$("#myInformation form.updateInfo").css("display", "none");

		// When an Edit Button is Clicked close any other open edit panels,
		// remove the edit class, add the disabled class and add the open class
		// to the edit form, then open the edit form.
		$(".editMyInformation").click(function(){

			var currentClass = $(this).attr("class");

			if (currentClass != "disabled"){
				$(".disabled").removeClass("disabled").addClass("editMyInformation");
				$(this).addClass("disabled").removeClass("editMyInformation");
				$(".editOpened").slideUp('fast').removeClass("editOpened");
				$(this).parent().siblings("form").slideDown(250).addClass("editOpened");
				$("#myInformation .buttonStyle1").show();
			}
		});

		// When the Cancel button is clicked close the edit form, remove the disabled
		// class from the edit button then add the editable class.
		$("#myInformation .buttonStyle1").click(function(){
			$(this).hide();
			$(this).parent().slideUp('normal').removeClass("editOpened");
			$(".disabled").removeClass("disabled").addClass("editMyInformation");


			// TODO: this is not working.
			$("#myInformation .disabled")
		});



	}else if( $("body#myCommunication").length > 0){

		/* My Communication validation */
		$("form#commmunicationForm").validate({
					errorContainer: "#formErrors",
					errorLabelContainer: "#formErrors ul",
					wrapper: "li",
				rules: {
				firstName: {
					required: true
				},
				lastName: {
					required: true
				},
				address1:{
					required:true
				},
				city:{
					required:true
				},
				country:{
					required:function(element){

						return ($("#addressLocation:filled").val()=="international");
					}
				},
				state:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				province:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				postalCode:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				zip:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				otherCountry:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="international" && $("#indicateCountry:filled").val()=="XX");
					}

				}
			},
			messages: {
				 firstName:{
					required: "Please provide your first name"
				 },
				 lastName:{
					required: "Please provide your last name"
				 },
				 address1:{
					required: "Please provide a value for address line #1"
				 },
				 city:{
					required: "Please provide a value for city"
				 },
				 country:{
					required: "Please select a country"
				 },
				 state:{
					required: "Please select a state"
				 },
				 province:{
					required: "Please select a province"
				 },
				 postalCode:{
					required: "Please provide a Postal code"
				 },
				 zip:{
					required: "Please provide a Zip code"
				 },
				 otherCountry:{
					required: "Please provide an Other country"
				 }
			}
		});
		/* END My Communication validation */

	}else if( $("body#myWallet").length > 0){

		$(".editForm").each(function(){
			var errorContainerName = "errors" + Math.round(Math.random()*10000);
			$(this).children(".errorDescription").attr("id", errorContainerName)
			$(this).validate({
				errorContainer: "#" + errorContainerName,
				errorLabelContainer: "#" + errorContainerName + " ul",
				wrapper: "li"
			})
		})


		/* My Wallet Page Functions */

		//Hide all the edit forms on page.
		$("#myWallet form.formWrapper").css("display", "none");

		//Initialize the Modal Confirm Delete Window
		$("#confirmDelete").jqm();

		//When a user clicks on the delete link prevent the follow. Open the modal and copy the href value from the clicked delete to the Confirm Delete button in the modal.
		$(".deleteButton").click(function(){
			var toDelete = $(this).attr('href');
			$(".buttonStyle2").attr("href", toDelete);

			$("#confirmDelete").jqmShow();
		return false
		});

		//Indicate a close button for the modal window
		$(".closeButton").click(function(){
			$("#confirmDelete, #confirmDelete .buttonStyle1").jqmHide();
		});

		//Indicate another close button for the modal window.  Prevent the follow
		$("#confirmDelete .buttonStyle1").click(function(){
			$("#confirmDelete").jqmHide();
		return false;
		});

		//When an Edit Button is Clicked close any other open edit panels, remove the edit class, add the disabled class and add the open class to the edit form, then open the edit form.
		$(".editMyInformation").click(function(){

			var currentClass = $(this).attr("class");

			if (currentClass != "disabled"){
				$(".disabled").removeClass("disabled").addClass("editMyInformation");
				$(this).addClass("disabled").removeClass("editMyInformation");
				$(".editOpened").slideUp('fast').removeClass("editOpened");
				$(this).parent().parent().parent().parent().next().children().children().slideDown('normal').addClass("editOpened");
			}
		});

		//When the Cancel button is clicked close the edit form, remove the disabled class from the edit button then add the editable class.
		$("#myWallet table .buttonStyle1").click(function(){
			$(this).parent().slideUp('normal').removeClass("editOpened");
			$(".disabled").removeClass("disabled").addClass("editMyInformation");
		});




	} else if($("body#chargeApplication").length > 0){




		/* Charge Application Page Functions */

		$("form[name=chargeAccessApplication]").validate({
			errorContainer: "#applicationErrors",
			errorLabelContainer: "#applicationErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				chargeNumber: {
					required: true
				},
				lastName: {
					required: true
				},
				firstName: {
					required: true
				},
				address1: {
					required: true
				},
				address2:{
					required: true
				},
				city: {
					required: true
				},
				indicateState: {
					required: true
				},
				zip: {
					required: true
				},
				ssn: {
					required: true
				}

			},
			messages: {
				 chargeNumber: {
				   required: "charge number custom"
				 }
				 // more custom messages
			}
		});





	} else if( $("body#addressBook").length > 0){






		/* Address Book Page Functions */

		$(".addressForm").each(function(){
			var errorContainerName = "errors" + Math.round(Math.random()*10000);
			$(this).children(".errorDescription").attr("id", errorContainerName)
			$(this).validate({
				errorContainer: "#" + errorContainerName,
				errorLabelContainer: "#" + errorContainerName + " ul",
				wrapper: "li"
			})
		})


		//Hide all the edit forms on page.
		$("form.formWrapper").css("display", "none");

		//Initialize the Modal Confirm Delete Window
		$("#confirmDelete").jqm();

		//When a user clicks on the delete link prevent the follow. Open the modal and copy the href value from the clicked delete to the Confirm Delete button in the modal.
		$(".deleteButton").click(function(){
			var toDelete = $(this).attr('href');
			$(".buttonStyle2").attr("href", toDelete);

			$("#confirmDelete").jqmShow();
		return false
		});

		//Indicate a close button for the modal window
		$(".closeButton").click(function(){
			$("#confirmDelete, #confirmDelete .buttonStyle1").jqmHide();
		});

		//Indicate another close button for the modal window.  Prevent the follow
		$("#confirmDelete .buttonStyle1").click(function(){
			$("#confirmDelete").jqmHide();
		return false;
		});

		//When an Edit Button is Clicked close any other open edit panels, remove the edit class, add the disabled class and add the open class to the edit form, then open the edit form.
		$(".editMyInformation").click(function(){

			var currentClass = $(this).attr("class");
			//console.log(currentClass);

			if (currentClass != "disabled"){
				$(".disabled").removeClass("disabled").addClass("editMyInformation");
				$(this).addClass("disabled").removeClass("editMyInformation");
				$(".editOpened").slideUp('fast').removeClass("editOpened");
				$(this).parent().parent().siblings('.formWrapper').slideDown('normal').addClass("editOpened");
			}

		});

		//When the Cancel button is clicked close the edit form, remove the disabled class from the edit button then add the editable class.
		$(".formWrapper .buttonStyle1").click(function(){
			$(this).parent().slideUp('normal').removeClass("editOpened");
			$(".disabled").removeClass("disabled").addClass("editMyInformation");
		});

	} else if( $("body#addAddress").length > 0){

		/*Add Address Page Functions */
		// Validates the addAddressForm Form
		$("form#addAddressForm").validate({
			errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				nickName:{
					required:true
				},
				firstName: {
					required: true
				},
				lastName: {
					required: true
				},
				address1:{
					required:true
				},
				city:{
					required:true
				},
				country:{
					required:function(element){

						return ($("#addressLocation:filled").val()=="international");
					}
				},
				state:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				province:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				postalCode:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				zip:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				otherCountry:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="international" && $("#indicateCountry:filled").val()=="XX");
					}

				}
			},
			messages: {
				nickName:{
					required: "Please provide a nickname for your address"
				},
				 firstName:{
					required: "Please provide your first name"
				 },
				 lastName:{
					required: "Please provide your last name"
				 },
				 address1:{
					required: "Please provide a value for address line #1"
				 },
				 city:{
					required: "Please provide a value for city"
				 },
				 country:{
					required: "Please select a country"
				 },
				 state:{
					required: "Please select a state"
				 },
				 province:{
					required: "Please select a province"
				 },
				 postalCode:{
					required: "Please provide a Postal code"
				 },
				 zip:{
					required: "Please provide a Zip code"
				 },
				 otherCountry:{
					required: "Please provide an Other country"
				 }
			}
		});


		// resets the form
		/*
		$(".formWrapper .buttonStyle1").attr({type: 'reset'}).click(function(){
			$("#addAddressForm")[0].reset();
			$("#formErrors").hide();
			$("#contentWrapper .errorInput img.errorFlag").remove();
			return false;
		});
		*/


	} else if( $("body#addCard").length > 0){



		/*Add Card Page Functions */

		$("form#addCardForm").validate({
			errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				nickName:{
					required:true
				},
				firstName: {
					required: true
				},
				lastName: {
					required: true
				},
				cardNumber: {
					required: function(element){
						return ($("#cardType:filled").val()!="talbotsCharge");
					}
				},
				address1:{
					required:true
				},
				city:{
					required:true
				},
				country:{
					required:function(element){

						return ($("#addressLocation:filled").val()=="international");
					}
				},
				state:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				province:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				postalCode:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="canada");
					}
				},
				zip:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="domestic");
					}
				},
				otherCountry:{
					required:function(element){
						return ($("#addressLocation:filled").val()=="international" && $("#indicateCountry:filled").val()=="XX");
					}

				}
			},
			messages: {
				nickName:{
					required: "Please provide a nickname for your address"
				},
				 firstName:{
					required: "Please provide your first name"
				 },
				 lastName:{
					required: "Please provide your last name"
				 },
				 cardNumber:{
					required: "Please provide a credit card number"
				 },
				 address1:{
					required: "Please provide a value for address line #1"
				 },
				 city:{
					required: "Please provide a value for city"
				 },
				 country:{
					required: "Please select a country"
				 },
				 state:{
					required: "Please select a state"
				 },
				 province:{
					required: "Please select a province"
				 },
				 postalCode:{
					required: "Please provide a Postal code"
				 },
				 zip:{
					required: "Please provide a Zip code"
				 },
				 otherCountry:{
					required: "Please provide an Other country"
				 }
			}
		})




	} else if( $("body#chargeCardApplication").length > 0){



		/*Charge Application Page Functions */

		$("#chargeApplicationForm").validate();


	} else if( $("body#awardsHome").length > 0 && !$("body").hasClass("platinum")){

		/*Charge Application Page Functions */
		$("#addAddressForm").validate({errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			rules: {
			},
			messages: {
			}
		});

	} else if($("body").hasClass("loyaltyChargeApp") && $("body").hasClass("platinum")) {

		$("#addAddressForm").validate({
			errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			rules: {
			accept:{
					required:true
				},
				firstName: {
					required: true
				},
				lastName: {
					required: true
				},
				address1:{
					required:true
				},
				city:{
					required:true
				},
				state:{
					required:true
				},
				zip:{
					required:true
				},
				ssn:{
					required:true
				},
				ssn_2:{
					required:true
				},
				ssn_3:{
					required:true
				},
				annualIncome:{
					required:true
				},
				dob_1:{
					required:true
				},
				dob_2:{
					required:true
				},
				dob_3:{
					required:true
				}
				
			},
			messages: {
				 firstName:{
					required: "Please provide your first name"
				 },
				 lastName:{
					required: "Please provide your last name"
				 },
				 address1:{
					required: "Please provide a value for address line #1"
				 },
				 city:{
					required: "Please provide a value for city"
				 },
				 state:{
					required: "Please select a state"
				 },
				 zip:{
					required: "Please provide a Zip code"
				 },
				  accept:{
					required: "<b>Please check the Terms and Conditions to continue</b>"
				 },
				 ssn:{
					required:"Please provide the first three digits of your SSN."
				},
				ssn_2:{
					required:"Please provide the middle two digits of your SSN."
				},
				ssn_3:{
					required:"Please provide the last four digits of your SSN."
				},
				annualIncome:{
					required:"Please provide annual income."
				},
				dob_1:{
					required:"Please provide the month of your birth."
				},
				dob_2:{
					required:"Please provide the day of your birth."
				},
				dob_3:{
					required:"Please provide the year of your birth."
				}
				
			}
		})

		$('#ssn').autotab({ target: 'ssn_2', format: 'numeric' });
		$('#ssn_2').autotab({ target: 'ssn_3', format: 'numeric', previous: 'ssn' });
		$('#ssn_3').autotab({ previous: 'ssn_2', format: 'numeric' });


	} else if ($("body#findaStore").length > 0) {


		/*Find In Store Page Functions */

		$("body").click(function(e){
			var target = e.target;

			if($(target).hasClass("directionButton")){
				var offset = $(target).offset();
				var address = $(target).attr("storeNum");

				$("#desiredAddress").attr("value", address);

				$("#directions").css({
					display:"block",
					left:offset.left + 60,
					top:offset.top - 25
				});
				return false;
			}
		});

		$(".closeButton").click(function(){
			$("#directions").css("display", "none");

		});


	} else if( $("body#forgotPasswordPage").length > 0){



		/*Forgot Password Page Functions */

		$("#forgotForm").validate({
			errorContainer: "#loginErrors",
			errorLabelContainer: "#loginErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				forgottenEmail: {
					required: true,
					email: true
				}
			},
			messages: {
				 forgottenEmail: {
				   required: "We need your email address to login",
				   email: "Your email address must be in the format of name@domain.com"
				 }
			}
		});

	} else if($("body#orderHistory").length > 0){
		//Adds a Country field if a user selects International as a radio button.

		var domForm = $("#domesticForm").validate({
			errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				orderNumber: {
					required: true
				},
				zipCode: {
					required: true
				},
				lastName: {
					required: true
				}
			},
			messages: {
				 orderNumber: {
				   required: "Order Number required"
				 },
				 zipCode: {
				   required: "Zip Code required"
				 },
				 lastName: {
				   required: "Last Name required"
				 }
			}
		});
		var intForm = $("#internationalForm").validate({
			errorContainer: "#formErrors",
			errorLabelContainer: "#formErrors ul",
			wrapper: "li",
			// add rules to override defaults e.g., minlength
			rules: {
				orderNumber2: {
					required: true
				},
				selectGroup3: {
					required: true
				},
				lastName2: {
					required: true
				}
			},
			messages: {
				 orderNumber2: {
				   required: "Order Number required"
				 },
				 selectGroup3: {
				   required: "Country Name required"
				 },
				 lastName2: {
				   required: "Last Name required"
				 }
			}
		});
		$("input[name='orderType']").click(
			function(){
				if ($("input[name='orderType']:checked").val() == 1){
					intForm.resetForm();
					$("#formErrors  ul li").remove();
					$("#formErrors").css("display","none");
					$("#internationalForm .errorInput").removeClass("errorInput");
					$("#internationalForm .errorFlag").remove();
					$("#domesticForm").show();
					$("#internationalForm").hide();
				}
				else if ($("input[name='orderType']:checked").val() == 2) {
					domForm.resetForm();
					$("#formErrors ul li").remove();
					$("#formErrors").css("display","none");
					$("#domesticForm .errorInput").removeClass("errorInput");
					$("#domesticForm .errorFlag").remove();
					$("#internationalForm").show();
					$("#domesticForm").hide();
				}
				return true;
		});

		if ($("input[name=orderType]:checked").val() == "1"){
			$("#domesticForm").show();
			$("#internationalForm").hide();
		}else{
			$("#internationalForm").show();
			if($("#indicateCountry").val() == "XX"){
				$("#l_otherCountry").show();
			}

			$("#domesticForm").hide();
		}



		$("#orderHistory #indicateCountry").change(function(){
			if ($(this).val() == "XX"){
				$("#l_otherCountry").show();
			}else if ($(this).val() != "XX"){
				$("#l_otherCountry").hide();
			}
		});



	}

	// JS PAGE MODULARIZATION OVER. PLACE ANY GLOBAL MY ACCOUNT JS HERE


	// RANDOM JS, TODO, PUT THIS IN THE PROPER PLACE???


	// THIS FUNCTION LOOKS FOR A SELECT WITH A CLASS OF 'regionSelector'
	// IT NEEDS TO BE PROVIDED A FEW JQUERY LABEL ELEMETNS.
	// WHEN INTERACTED WITH IT WILL DECIDE WHICH LOCATIONAL ELEMNTS NEED
	// TO BE RENDERED ON THE PAGE AND REMOVE THE ONES THAT DONT

	var dataContainer = [];
	$(".regionSelector").each(function(){
		gatherData = function(select){
			var container = $(select).parent().parent();
			var nodes ={
				country: {
					obj: $(container).children("label.countryField"),
					html: $(container).children("label.countryField").html()
				},
				zip: {
					obj: $(container).children("label.zipField"),
					html: $(container).children("label.zipField").html()
				},
				city:{
					obj: $(container).children("label.cityField"),
					html: $(container).children("label.cityField").html()
				},
				state: {
					obj: $(container).children("label.stateField"),
					html: $(container).children("label.stateField").html()
				},
				province: {
					obj: $(container).children("label.provinceField"),
					html: $(container).children("label.provinceField").html()
				},
				postalcode: {
					obj: $(container).children("label.postalcodeField"),
					html: $(container).children("label.postalcodeField").html()
				},
				address3: {
					obj: $(container).children("label.address3"),
					html: $(container).children("label.address3").html()
				},
				address4: {
					obj: $(container).children("label.address4"),
					html: $(container).children("label.address4").html()
				},
				otherCountry: {
					obj: $(container).children("label.otherCountryField"),
					html: $(container).children("label.otherCountryField").html()
				}
			};
			return nodes
		}
		var randID = "rs_" + Math.floor(Math.random() * 1000000)
		var data = gatherData($(this))
		if($(this).attr("longdesc") == null){
			$(this).attr("longdesc", randID)
		}
		dataContainer.push({
			id: $(this).attr("longdesc"),
			data: data
		})
		$(this).changeLocation(data);


	});
	$.fn.updateRegion = function(scope){
		var longdesc = $(scope).attr("longdesc");
		var fetchData = function(){
			for(i=0; i <= dataContainer.length; i++){
				if(longdesc == dataContainer[i].id){
					return dataContainer[i].data;
					break;
				}
			}
		}
		$(scope).changeLocation(fetchData());

	}
	$(".regionSelector").change(function(){
		var longdesc = $(this).attr("longdesc");
		var fetchData = function(){
			for(i=0; i <= dataContainer.length; i++){
				if(longdesc == dataContainer[i].id){
					return dataContainer[i].data;
					break;
				}
			}
		}
		$(this).changeLocation(fetchData());
	});




	$(".indicateCountry").change(function(){
		var el = $(this).parent().parent().children(".otherCountryField").get(0)
		if ($(this).val() == "XX"){
			$(el).removeClass("hidden");
		}else if ($(this).val() != "XX"){
			$(el).addClass("hidden");
		}

		$('#dateOfBirth').autotab({ target: 'dateOfBirth_2', maxlength: 2});
		$('#dateOfBirth_2').autotab({ target: 'dateOfBirth_3', previous: 'dateOfBirth', maxlength: 2 });
		$('#dateOfBirth_3').autotab({ previous:'dateOfBirth_2', maxlength: 4});

	});



	// Other country text field for region selector for account pages
	$("#otherCountry").blur(function(){
		if(!$(this).hasClass("noblur")){
			var value = $("#otherCountry").val();
			if (value.toLowerCase() == "canada")  {
				$('#addressLocation').attr('value','canada');
				$('#addressLocation').changeLocation();
				$('#indicateCountry').attr('value','');
				$('#otherCountry').attr('value','');
			}else if (value.toLowerCase() == "mexico"){
				var otherCountryName = $(this).val();
				$("label.address3").hide();
				$("label.address4").hide();
				$('#indicateCountry').attr('value','MX');
				$(".otherCountryField").hide("normal").children().val("");
			}else {
				$("label.address3").show();
				$("label.address4").show();
			}
		}
	});



	// loyalty dashboard tab section
	$('.history tbody tr:odd').addClass('odd');

	$('.history dt').click(function(){
		$('.history tbody tr:odd').addClass('odd');

		if($(this).hasClass('selected') === false){
			$(this).addClass('selected').siblings().removeClass('selected').end().next().addClass('selected');
		}
	});



	$(".printCard").click(function (){
		var url = "loyalty_awardConfirmPrint.jsp"
		superPopup({
			url:url,
			type:"_blank"
		})

	return false;
	});



// END ON READY
});







