// Pop-up for help modal
$(document).ready(function() {
	//turn off caching
	$.ajaxSetup({ cache: false });

	//closes modal window when mouse clicks outside modal
	$('.ui-widget-overlay').live('click', function() { $('div[class*=ui-dialog-content]').dialog('close'); } );

	$('<div class="fieldErrorArrow"></div>').insertBefore('.formfield ul, .formfieldcus ul');
	$("#directionsgo").click(
		function() {
			$("#directions").submit();
		}
	);

	
	$('.starting').click(
		function() {
			if ($.trim($(this).val()) == 'Enter your starting address') { 
				$(this).val('');
			}
		}
	);

	$('.starting').blur(
		function() {
			if ($.trim($(this).val()) == '') { 
				$(this).val('Enter your starting address');
			}
		}
	);
	
	$('.emailoffers').click(
		function() {
			if ($.trim($(this).val()) == 'Email address') { 
				$(this).val('');
			}
		}
	);

	$('.emailoffers').blur(
		function() {
			if ($.trim($(this).val()) == '') { 
				$(this).val('Email address');
			}
		}
	);
	
	$('.emailoffers').keypress(function(e) {
		if(e.keyCode == 13) {
  			tryOffers();
  		}
	});
	
	$('.ending').click(
		function() {
			if ($.trim($(this).val()) == 'Enter your ending address') { 
				$(this).val('');
			}
		}
	);

	$('.ending').blur(
		function() {
			if ($.trim($(this).val()) == '') { 
				$(this).val('Enter your ending address');
			}
		}
	);
	
	$("#deletePatientErrorModal").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});
	
	$("#forgotPasswordInputModal").dialog(
		{
			autoOpen: false,
			title: "Forgot Your Email?",
			modal: true,
			draggable: false,
			resizable: false,
			zIndex: 10010
		}
	);

	$("#forgotPasswordSuccessModal").dialog(
		{
			autoOpen: false,
			title: "Thank You!",
			modal: true,
			draggable: false,
			resizable: false,
			zIndex: 10011,
			close: function() {
				$("#forgotPasswordInputModal").dialog('close');
			}
		}
	);
	
	$("#forgotPasswordErrorModal").dialog(
		{
			autoOpen: false,
			title: "Error",
			modal: true,
			draggable: false,
			resizable: false,
			zIndex: 10011
		}
	);
	
	$("#forgotPassword #continue").click(
		function() {
			var emailexpr = /.*?@.+?\..+/;
		
			var errors = false;
			if ($.trim($("#forgotEmail").val()) == '') {
				showError('forgotEmail', 'Please enter your e-mail address.');
				errors = true;
			}
			else if (!emailexpr.test($.trim($("#forgotEmail").val()))) {
				showError('forgotEmail', 'Please enter a valid e-mail address.');
				errors = true;
			}
			else {
				hideError('forgotEmail');
			}
			
			if (!errors) {
				$.ajax(
					{
						url: "/to/eappointments/forgotPassword.action",
						data: $("#forgotPassword").serialize(),
						dataType: "json",
						async: false,
						type: "POST",
						success: function(data) {
							if (data.success == false) {
								$("#forgotPasswordErrorModal").dialog('open');
							}
							else {
								$("#forgotPasswordSuccessModal").dialog('open');
							}
						}
					}
				);
			}
			
			return false;
		}
	);
	
	$("#forgotPasswordLink").click(
		function() {
			$("#forgotPasswordInputModal").dialog('open');
		}
	);

	
	$('#help').click(function() {
		$('#helpDiv').dialog({
			autoOpen: true,
			title: 'Help',
			height: 400,
			width: 550,
			modal: true,
			draggable: false,
			resizable: false
		});
	});
	
	$("#changeEmail #cancel").click(
		function() {
			return false;
		}
	);


	$("#changePassword #cancel").click(
		function() {
			return false;
		}
	);
	
	$("#change-email-dialog").dialog({
		autoOpen: false,
		modal: true,
		width: 500,
		height: 360,
		draggable: false,
		resizable: false
	});
	
	$("#change-password-dialog").dialog({
		autoOpen: false,
		modal: true,
		width: 500,
		height: 360,
		draggable: false,
		resizable: false
	});
	

	$("#changeemail-button").click(
		function() {
			$("#change-email-dialog").dialog('open');
		}
	);
	
	$("#changepassword-button").click(
		function() {
			$("#change-password-dialog").dialog('open');
		}
	);

	$("#offers-success").dialog({
		autoOpen: false,
		title: "Success",
		modal: true,
		draggable: false,
		resizable: false
	});
	
	$("#offers-error").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});
	
	$("#changePassword").submit(function(){return false;});
		
	$("#18years-error").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});
	
	$("#email-error").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});

	$("#changePasswordSuccess").dialog({
		autoOpen: false,
		title: "Password Changed",
		modal: true,
		draggable: false,
		resizable: false,
		close: function () {
			window.location = '/to/eappointments/editProfile.action';
		}
	});
	
	$("#changePasswordError").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});
	
	$("#sweepstakes-error").dialog({
		autoOpen: false,
		title: "Error",
		modal: true,
		draggable: false,
		resizable: false
	});
		
	$("#emailoffersgo").click(tryOffers);
	$("#sweepstakesSubmit").click(tryRegister);

	
	// product carousel
	$('.component-carousel-4').each(function(){
	 	var self = $(this);	
		if (self.find('li.product').length > 1){
			self.tileCarousel({
				viewportDelta: -40
			});
			$('body').data(this.id, self);
		};
	});
});

function validateChangePassword() {
	var errors = false;
	var currentPasswordErrors = false;
	
	if ($.trim($("#currentPassword").val()) == '') {
		showError('currentPassword', 'Please enter your current password.');
		errors = true;
		currentPasswordErrors = true;
	}
	else {
		hideError('currentPassword');
	}

	if ($.trim($("#newPassword").val()) == '') {
		showError('newPassword', 'Please enter your new password.');
		errors = true;
	}
	else {
		hideError('newPassword');
	}

	if ($.trim($("#confirmPassword").val()) == '') {
		showError('confirmPassword', 'Please confirm your new password.');
		errors = true;
	}
	else if ($.trim($("#confirmPassword").val()) != $.trim($("#newPassword").val())) {
		hideError('confirmPassword');
		showError('confirmPassword', 'The passwords you entered do not match.');
		errors = true;
	}
	else {
		hideError('confirmPassword');
	}
	
	if (!currentPasswordErrors) {
		$.ajax(
			{
				url: "/to/eappointments/verifyCredentials.action",
				data: {
					email: $(".getemail").first().html(),
					password: $("#currentPassword").val()
				},
				dataType: "json",
				async: false,
				type: "POST",
				success: function(data) {
					if (data.success == false) {
						showError('currentPassword', 'Your current password is not correct.');
						errors = true;
					}
				}
			}
		);
		
	}
	
	if (errors == false) {
		$.ajax(
			{
				url: "/to/eappointments/changePassword.action",
				data: $("#changePassword").serialize(),
				dataType: "json",
				async: false,
				type: "POST",
				success: function(data) {
					if (data.success == false) {
						$("#changePasswordFailure").dialog('open');
					}
					else {
						$("#change-password-dialog").dialog('close');
						$("#changePasswordSuccess").dialog('open');
					}
				}
			}
		);
		
		return false;
	}
	
	return !errors;
}

function validateChangeEmail() {

		var errors = false;
		var emailexpr = /.*?@.+?\..+/;
		
		if ($.trim($("#currentEmailAddress").val()) == '') {
			showError('currentEmailAddress', 'Please enter your current e-mail address.');
			errors = true;
			currentPasswordErrors = true;
		}
		else {
			hideError('currentEmailAddress');
		}

		if ($.trim($("#newEmailAddress").val()) == '') {
			showError('newEmailAddress', 'Please enter your new e-mail address.');
			errors = true;
		}
		else if (!emailexpr.test($.trim($("#newEmailAddress").val()))) {
			showError('newEmailAddress', 'Please enter a valid e-mail address.');
			errors = true;
		}
		else {
			hideError('newEmailAddress');
		}

		if ($.trim($("#confirmEmailAddress").val()) == '') {
			showError('confirmEmailAddress', 'Please confirm your new e-mail address.');
			errors = true;
		}
		else if ($.trim($("#confirmEmailAddress").val()) != $.trim($("#newEmailAddress").val())) {
			hideError('confirmEmailAddress');
			showError('confirmEmailAddress', 'The email addresses you entered do not match.');
			errors = true;
		}
		
		else {
			hideError('confirmEmailAddress');
		}
		
		if (!errors) {
			$("#currentEmailAddress").removeAttr('disabled');
		}
		
		return !errors;

}

function validateStep3() {
	hideError('usingInsurance');
	if ($("#usingInsuranceYes:checked").val() == null && $("#usingInsuranceNo:checked").val() == null) {
		showError('usingInsurance','Please say whether or not you are using insurance.');
		return false;
	}
	
	return true;
}

function populatePatient(patient) {	
	if (patient.value==null || patient.value == ""){
		var patId = patient;
		}
	else {
		var patId = patient.value;
	}
	
	$.getJSON("getPatient.action?patientId=" + patId, function(json) {
		if (json[0].patient.id != null) {
			$("#selectPatient").val(patId);
			$("#patientId").val(json[0].patient.id);
			$("#firstName").val(json[0].patient.firstName);
			$("#lastName").val(json[0].patient.lastName);
			$("#address").val(json[0].patient.address);
			if (json[0].patient.address2 != null) {
				$("#address2").val(json[0].patient.address2);
			}
			$("#city").val(json[0].patient.city);
			$("#postalCode").val(json[0].patient.postalCode);
			$("#phone").val(json[0].patient.phone);
			if (json[0].patient.altPhone != null) {
				$("#altPhone").val(json[0].patient.altPhone);
			}
			$("#state").val(json[0].patient.state);
			$("#country").val(json[0].patient.country);
			if(json[0].patient.dobMonth < 9) {
				$("#dobMonth").val("0"+(json[0].patient.dobMonth+1));
			} else {
				$("#dobMonth").val(json[0].patient.dobMonth+1);
			}
			
			if(json[0].patient.dobDay < 10) {
				$("#dobDay").val("0"+json[0].patient.dobDay);
			} else {
				$("#dobDay").val(json[0].patient.dobDay);
			}
			
			$("#dobYear").val(json[0].patient.dobYear);
			
			if (json[0].patient.medInsCarrier == null) { 
				$("#medInsCarrier").val("");
			} else { 
				$("#medInsCarrier").val(json[0].patient.medInsCarrier);
			} 
			
			if (json[0].patient.medInsGroup == null) { 
				$("#medInsGroup").val("");
			} else { 
				$("#medInsGroup").val(json[0].patient.medInsGroup);
			} 
	
			if (json[0].patient.medInsPolicy == null) { 
				$("#medInsPolicy").val("");
			} else { 
				$("#medInsPolicy").val(json[0].patient.medInsPolicy);		
			} 
			
			if (json[0].patient.visionInsCarrier == null) { 
				$("#visionInsCarrier").val("");
			} else { 
				$("#visionInsCarrier").val(json[0].patient.visionInsCarrier);
			} 
	
			if (json[0].patient.visionInsGroup == null) { 
				$("#visionInsGroup").val("");
			} else { 
				$("#visionInsGroup").val(json[0].patient.visionInsGroup);
			} 
	
			if (json[0].patient.visionInsPolicy == null) { 
				$("#visionInsPolicy").val("");
			} else { 
				$("#visionInsPolicy").val(json[0].patient.visionInsPolicy);
			} 
		
		} else {
			$("#firstName").val("");
			$("#lastName").val("");
			$("#address").val("");
			$("#address2").val("");
			$("#city").val("");
			$("#postalCode").val("");
			$("#phone").val("");
			$("#altPhone").val("");
			document.getElementById('state').selectedIndex = 0;
			document.getElementById('country').selectedIndex = 0;
			document.getElementById('dobMonth').selectedIndex = 0;
			document.getElementById('dobDay').selectedIndex = 0;
			document.getElementById('dobYear').selectedIndex = 0;
			$("#medInsCarrier").val("");
			$("#medInsGroup").val("");
			$("#medInsPolicy").val("");
			$("#visionInsCarrier").val("");
			$("#visionInsGroup").val("");
			$("#visionInsPolicy").val("");
			$("#patientId").val("");
		}

		if ( (json[0].patient.medInsCarrier != null && json[0].patient.medInsCarrier != '') ||
			     (json[0].patient.medInsGroup != null && json[0].patient.medInsGroup != '') || 
			     (json[0].patient.medInsPolicy != null && json[0].patient.medInsPolicy != '') || 
			     (json[0].patient.visionInsCarrier != null && json[0].patient.visionInsCarrier != '') || 
			     (json[0].patient.visionInsGroup != null && json[0].patient.visionInsGroup != '') || 
			     (json[0].patient.visionInsPolicy != null && json[0].patient.visionInsPolicy != '') ) {
			//using or has prefilled insurance info    
			document.getElementById('usingInsuranceYes').checked=true;
			$("#insuranceInfo").show();
		} else {		
			document.getElementById('usingInsuranceNo').checked=true;
			$("#insuranceInfo").hide();
		}
		
		if ($("#usingInsuranceYes:checked").val() == null && $("#usingInsuranceNo:checked").val() == null) {
			showError('usingInsurance','Please say whether or not you are using insurance.');
		}

	});

}//end function

function clearStep3InsuranceInformation() { 
	//clears the insurance fields on step3 if radio button value is 'no'
	var noInsurance = $("#usingInsuranceNo").attr('checked');

	if (noInsurance) { 
		$("#medInsCarrier").val("");
		$("#medInsGroup").val("");
		$("#medInsPolicy").val("");
		$("#visionInsCarrier").val("");
		$("#visionInsGroup").val("");
		$("#visionInsPolicy").val("");		
	}//end if
	
	return true;
}

function tryOffers() {
	var emailexpr = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

	if ($("#18yrs_checkbox:checked").val() == null) {
		$("#18years-error").dialog("open");
		return false;
	}
	
	if(!emailexpr.test($("#emailoffers input[type=text]").val())) {
		$("#email-error").dialog("open");
		return false;
	}
	
	$.getJSON(
		"/webapp/wcs/stores/servlet/UserRegistrationAdd" + "?" + $(".offerForm").serialize(),
		function(data) {
			var alreadyexists = /.+?already exists.+/i;

			if (data.success == "true" || alreadyexists.test(data.messageKey)) {
				$("#offers-success").dialog("open");
				$('.emailoffers').val('Email address');
				$("#18yrs_checkbox").attr('checked', false);
			    
			}
			else {
				$("#offers-error").dialog("open");
			}
	
	        sendEmailSubOmnitureEvent();
			return false;
		}
	);
	
	return false;
}

function tryRegister() {
	var errorFields = "";
	var errorFree = true;
		
	var field1String = $("input:radio[name='wear']:checked").val() + "|" 
					+ $("#where").val() + "|" 
					+ $("#needs").val() + "|" 
					+ $("#purchased").val() + "|" 
					+ $("#redcard").val();
			
	$("#userfield1").val(field1String);
	
	if($("#sszipCode").val() == "") {
		$("#sszipCode").focus();
		errorFields = "Zip code is required\n" + errorFields;
		errorFree = false;
	}

	if($("#ssstate").val() == "") {
		$("#ssstate").focus();
		errorFields = "State is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#sscity").val() == "") {
		$("#sscity").focus();
		errorFields = "City is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#ssaddress1").val() == "") {
		$("#ssaddress1").focus();
		errorFields = "Address is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#ssphone1").val() == "") {
		$("#ssphone1").focus();
		errorFields = "Phone is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#sslogonIdVerify").val() == "") {
		$("#sslogonIdVerify").focus();
		errorFields = "Email confirmation is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#sslogonId").val() == "") {
		$("#sslogonId").focus();
		errorFields = "Email is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#sslogonId").val() != $("#sslogonIdVerify").val()) {
		$("#sslogonId").focus();
		errorFields = "Email addresses must match\n" + errorFields;
		errorFree = false;
	}
	
	if($("#sslastName").val() == "") {
		$("#sslastName").focus();
		errorFields = "Last name is required\n" + errorFields;
		errorFree = false;
	}
	
	if($("#ssfirstName").val() == "") {
		$("#ssfirstName").focus();
		errorFields = "First name is required\n" + errorFields;
		errorFree = false;
	}
	
	if(!$("#ssage").attr("checked")) {
		$("#ssage").focus();
		errorFields = "You must be at least 18 years of age to enter\n" + errorFields;
		errorFree = false;
	}
	
	if(!$("#ssTerms").attr("checked")) {
		$("#ssTerms").focus();
		errorFields = "You must accept the terms before entering\n" + errorFields;
		errorFree = false;
	}

	if(errorFree) {
		$.getJSON(
			"/webapp/wcs/stores/servlet/UserRegistrationAdd" + "?" + $(".sweepstakesform").serialize(),
			function(data) {
				var alreadyexists = /.+?already exists.+/i;
	
				if (data.success == "true" || alreadyexists.test(data.messageKey)) {
					var url = window.location.href;    
					var param = url.split('?')[1];
					window.location.href = "sweepstakes-thankyou.jsp?" + param;  
				}
				else {
					$("#sweepstakes-error").dialog('open');
				}
				return false;
			}
		);
	} else {
		alert(errorFields);
	}
	
	return false;
}


function openModal(id,modalHeight,modalWidth){
	$('div[id*=Error]').remove(); 
	
	// if the modal contains a product rotator, revert to the first tile
	var rotator = $('body').data(id + '-carousel');
	if (rotator != null){
		rotator.tileCarousel().data('tileCarousel').jumpToFrame(0);
	}

	// open the modal
	$('#'+id).dialog({
			autoOpen: true,
			height: modalHeight,
			width: modalWidth,
			modal: true,
			draggable: false,
			resizable: false
		});
}

function closeModal(divid){
	$('#'+divid).dialog('close');
}

function showError(fieldName, message) {
	var error = '<div id="' + fieldName + 'Error"><div class="fieldErrorArrow"></div><ul><li><span class="errorMessage">' + message +'</span></li></ul></div>';
	$("label[for='" + fieldName + "']").before(error);
}

function hideError(fieldName) {
	$("#" + fieldName + "Error").remove();
}

//validation for update/add patient modal
function validate_form(thisform) {
	var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
	var phonePattern = /^\d{10}$|^\d{3}-\d{3}-\d{4}$|^\(\d{3}\)\d{3}-\d{4}$/;
	var errors = false;

	$('div[id*=Error]').remove(); 

	with(thisform){
		if (firstName.value==null||firstName.value=="") {
			showError('firstName', 'Please enter your first name.');
			errors = true;
		}

		if (lastName.value==null||lastName.value=="") {
			showError('lastName', 'Please enter your last name.');
			errors = true;
		}

		if (address.value==null||address.value=="") {
			showError('address', 'Please enter your address.');
			errors = true;
		}

		if (city.value==null||city.value=="") {
			showError('city', 'Please enter your city.');
			errors = true;
		}

		if (state.value==null||state.value==""||state.value=="1") {
			showError('state', 'Please select your state.');
			errors = true;
		}

		if (postalCode.value==null||postalCode.value=="") {
			showError('postalCode', 'Please enter your zip code.');
			errors = true;
		}
		else if (zipCodePattern.test(postalCode.value)==false){
			showError('postalCode', 'Please enter a valid zip code.');
			errors = true;
		}
	
		if (phone.value==null||phone.value=="") {
			showError('phone', 'Please enter a valid phone number.');
			errors = true;
		}
		else if (phonePattern.test(phone.value)==false){
			showError('phone', 'Must be in the format ### - ### - #### or ##########.');
			errors = true;
		}
		if (altPhone.value!="") {
			if (phonePattern.test(altPhone.value)==false){
				showError('altPhone', 'Must be in the format ### - ### - #### or ##########.');
				errors = true;
			}
		}
		
		if (dobMonth.value==null||dobMonth.value=="") {
			showError('dobMonth,dobDay,dobYear', 'Please choose your Date of Birth.');
			errors = true;
		}

		if (dobDay.value==null||dobDay.value=="") {
			showError('dobMonth,dobDay,dobYear', 'Please choose your Date of Birth.');
			errors = true;
		}

		if (dobYear.value==null||dobYear.value=="") {
			showError('dobMonth,dobDay,dobYear', 'Please choose your Date of Birth.');
			errors = true;
		}
													
	return !errors;
	}
}

//contact us dropdown
function displaySignIn(){
	$("#signInDiv").show();
	$('#signIn').addClass("Hover");
	
	$("div#signInDiv").hover(
		function() {
		var hover = 'true';
		},
		function(){
		$("#signInDiv").hide();
		$('#signIn').removeClass("Hover");
		}
	);
}

