$(document).ready(function() {
	
	if(typeof (signedIn) != "undefined") {
		
		if(signedIn == 1) {
			
			if($("#reg-terms")) {
				registerField("input[name='reg-usage']", "radio");
				registerField("#reg-terms", "terms");
			}
			
		}

    }
	
	
	
});

//FIELD FOCUS
function initFields(thisContainer) {
	
	$(thisContainer + " :input").unbind("focus");
	$(thisContainer + " :input").unbind("blur");

	$(thisContainer + " :input").focus(
		function() {

		    if (typeof (leaveFieldDefaults) == "undefined") {

		        //Clear default content
		        if ($(this).attr("value") == $(this)[0].defaultValue) {
		            $(this).attr("value", "");
		        }

		    }
		    $(thisContainer + " :input").css("color", "#fff");

		    //Show hint
		    showHint(this);

		}
	);
	
	//FIELD BLUR
	$(thisContainer + " :input").blur(
		function() {
			
			//Hide hint
			hideHint(this)
			
			//Validate content
			if($(this).hasClass("req")) {
				validateField(this);
			}
			
		}
	);
	
}

//REGISTER REQUIRED FIELDS
function registerField(thisField, additionalClass) {
	
	if(!additionalClass) {
		additionalClass = "";
	}
	
	$(thisField).addClass("req " + additionalClass);
	
}

function deRegisterField(thisField, additionalClass) {
	
	$(thisField).removeClass("req");
	
	if(additionalClass) {
		$(thisField).removeClass(additionalClass);
	}
	
}

//HINT FUNCTIONS
function showHint(thisField) {
	
	if($(thisField).siblings(".hint").is(":hidden")) {
		$(thisField).siblings(".hint").fadeIn(300);
	}
	
}

function hideHint(thisField) {
	
	if($(thisField).siblings(".hint").is(":visible")) {
		//$(thisField).siblings(".hint").fadeOut(300);
		$(thisField).siblings(".hint").hide();
	}
	
}

//SUBMIT INIT
function submitInit(thisButton) {
	
	$(thisButton).addClass("disabled");
	if($(thisButton).next(".loader").length < 1) {
		$(thisButton).after("<span class=\"loader\"></span>");
	}
	// can't disable these - they are NOT submitted if disabled
	// set readonly and change CSS instead
	//$(":input").attr("disabled", "disabled");
	$(":input").css("color", "#777");
	$(".server-error").remove();
	validationResult = 1;
	
}

//SUBMIT RESET
function submitReset(thisButton, flush) {
	
	if(thisButton) {
		$(thisButton).removeClass("disabled");
		$(thisButton).next(".loader").remove();
	} else {
		$("a.pill").removeClass("disabled");
		$(".loader").remove();
	}
	
	//$(":input").attr("disabled", "");
	$(":input").css("color", "#fff");
	
	if(flush) {
		
		$(":input").each(
			function() {
				
				$(this).attr("value", $(this)[0].defaultValue);
				
			}
		);
		
	}
	
}

//FIELD VALIDATION
function validateForm(thisForm) {
	
	$(thisForm + " :input").each(
		function() {
			
			if($(this).hasClass("req")) {
				validateField(this);
			}
			
		}
	);

	//validationResult = 1;	
}

function validateField(thisField) {
	
	var additionalClass = $(thisField).attr("class").substr(4);
	var fieldValue = $(thisField).attr("value");
	
	switch(additionalClass) {
		
		case "email":
			var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			
			if(!emailFilter.test(fieldValue)) {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "terms":
			
			if($(thisField).parent().children("input.terms:checked").length < 1) { //IE has problems with thisField :checked
				addError(thisField, $(thisField).next("label"));
			} else {
				removeError(thisField, $(thisField).next("label"));
			}
			
			break;
			
		case "select":
			
			if($(thisField).attr("value") == "default") {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "radio":
			
			var radioGroup = $(thisField).attr("name");
			
			if($("input[name='" + radioGroup + "']:checked").length < 1) { //IE has problems with thisField :checked
				addError(thisField, $(thisField).parents("ul").prev("h3"));
			} else {
				removeError(thisField, $(thisField).parents("ul").prevAll("h3"));
			}
			
			break;
			
		case "postcode":
			
			if($(thisField).attr("value").length > 8 || $(thisField).attr("value") == "") {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "password":
			
			checkPasswordMatch();
			
			break;
			
		default:
			if(!fieldValue) {
				addError(thisField);
			} else {
				removeError(thisField);
			}
		
	}
	
}

//ERROR FEEDBACK
function addError(thisField, thisObject) {
	
	if(thisObject) {
		
		if($(thisObject).next(".error").length < 1) {
			$(thisObject).after("<span class=\"error\"></span>");
		}
		
	} else {
		
		if($(thisField).next(".error").length < 1) {
			$(thisField).after("<span class=\"error\"></span>");
		}
		
	}
	
	validationResult = 0;
	
}

function removeError(thisField, thisObject) {
	
	if(thisObject) {
		$(thisObject).next(".error").remove();
	} else if(thisField) {
		$(thisField).next(".error").remove();
	} else {
		$(".error").remove();
	}
	
}

//TELL A FRIEND BUTTON INIT
function tellfriendButtonInit() {
	
	$("#ovl-tell-friend .send").unbind("click");
	$("#ovl-tell-friend table :input").unbind("keypress");
	
	//SIGN IN CLICK
	$("#ovl-tell-friend .send").click(
		function() {


	
		    tellfriendButtonSubmit();



		    return false;

		}
	);
	
	//ENTER PRESS
	$("#ovl-tell-friend table :input").keypress(
		function(e) {
			
			if(e.which == 13) {
				
				tellfriendButtonSubmit();
				
			}
			
		}
	);
	
}

function tellfriendButtonSubmit() {
	
	thisObject = "#ovl-tell-friend .send";
	
	if(!$(thisObject).hasClass("disabled")) {

	
		//Validate content
		submitInit(thisObject);
		
		var targetForm = "#ovl-tell-friend .form"; //Set target form if button resides outside form container

		if(!targetForm) {
			var targetForm = $(thisObject).parent().find(".form");
		}


		validateForm(targetForm);

		//Response okay
		if(validationResult != 0) {


		    var name = $("#taf-name").val();
		    var email = $("#taf-email").val();
		    var friendName = $("#taf-f-name").val();
		    var friendEmail = $("#taf-f-email").val();

		    $.post(siteRoot + "ajax/ReferFriends.ashx",
				{
				    name: name,
				    email: email,
				    friendName: friendName,
				    friendEmail: friendEmail

				}, function(data) {

				    if (data == "Success") {

				        completeTellFriend(friendEmail);
				    } else {

				        errorTellFriend();
				        submitReset();
				    
				    }


				});

			
		} else {
			
			submitReset();
			
		}
		
	}
	
	return false;

}
function errorTellFriend(emailAddress) {
    //$("#ovl-tell-friend .intro, #ovl-tell-friend table, #ovl-tell-friend .links").hide();

    $("#ovl-tell-friend .content table.form").before("<p class=\"server-error\">We are sorry, an error occured. Please try back later.</p>");
	
    //closeOverlay();
    //tellanotherButtonInit();

}

function completeTellFriend(emailAddress) {
	$("#ovl-tell-friend .intro, #ovl-tell-friend table, #ovl-tell-friend .links").hide();
	
	$("#ovl-tell-friend .content").append("<p class=\"success\">Thank you. Your message has been sent to:<br /><strong>"+emailAddress+"</strong></p><ul class=\"links alt\"><li><a class=\"pill send-another\" href=\"#content\">Send Another</a></li><li class=\"cancel\"><a href=\"#content\">Close</a></li></ul>");
	
	closeOverlay();
	tellanotherButtonInit();
	
}

function tellanotherButtonInit() {
	
	$("#ovl-tell-friend .send-another").unbind("click");
	
	//SIGN IN CLICK
	$("#ovl-tell-friend .send-another").click(
		function() {
			
			$("#ovl-tell-friend .success, #ovl-tell-friend .links.alt").remove();			
			$("#ovl-tell-friend .intro, #ovl-tell-friend table, #ovl-tell-friend .links").show();
			
			submitReset();
			tellfriendButtonInit();
			
			return false;
			
		}
	);
	
}

//CONTACT FORM BUTTON INIT
function contactButtonInit() {
	
	$("#ovl-contact .send").unbind("click");
	$("#ovl-contact table :input").unbind("keypress");
	
	//SIGN IN CLICK
	$("#ovl-contact .send").click(
		function() {
			
			contactButtonSubmit();
			
			return false;
			
		}
	);
	
	//ENTER PRESS
	$("#ovl-contact table :input").keypress(
		function(e) {
			
			if(e.which == 13) {
				
				contactButtonSubmit();
				
			}
			
		}
	);
	
}

function contactButtonSubmit() {
	
	thisObject = "#ovl-contact .send";
	
	if(!$(thisObject).hasClass("disabled")) {
		
		//Validate content
		submitInit(thisObject);
		
		var targetForm = "#ovl-contact .form"; //Set target form if button resides outside form container
		
		if(!targetForm) {
			var targetForm = $(thisObject).parent().siblings(".form");
		}
		
		validateForm(targetForm);
		
		//Response okay
		if(validationResult != 0) {
			
			//alert("Move along...");
			completeContact();
			
		} else {
			
			submitReset();
			
		}
		
	}
	
	return false;
	
}

function completeContact() {
    if(validationResult != 0) {
            var messageType;
            var messageType_checked = $("#cnt-query-1").is(":checked");
            if (messageType_checked) {
                messageType = "Customer Service";
            }
            else 
                messageType = "Technical";
            //alert(messageType);
            
			$.post(siteRoot + "ajax/ContactUs.ashx",
				{
					title: $("#cnt-title").val(),
					firstName: $("#cnt-firstname").val(),
					lastName: $("#cnt-lastname").val(),
					email: $("#cnt-email").val(),
					message: $("#cnt-message").val(), 
					messageType : messageType
				},
				function(data) {
				//alert(data);
				    if (data == "Success")
				    {
				        $("#ovl-contact .intro, #ovl-contact .form-items, #ovl-contact table, #ovl-contact .links").hide();
	                    $("#ovl-contact .content").append("<p class=\"success\">Thank you. Your message has been sent</p><h2 class=\"rem\">What happens next?</h2><p class=\"rem\">Our customer service team will deal with your enquiry as soon as possible.</p><h2 class=\"rem\">What do you want to do now?</h2><ul class=\"rem\"><li class=\"cancel\"><a href=\"#content\">Go back to the Alert website</a></li><li class=\"send-another\"><a href=\"#content\">Send another message</a></li></ul>");
                    	
	                    closeOverlay();
	                    sendanotherButtonInit();
				    }
				}
			);
	}
	
}

function sendanotherButtonInit() {
	
	$("#ovl-contact .send-another a").unbind("click");
	
	//SIGN IN CLICK
	$("#ovl-contact .send-another a").click(
		function() {
			
			$("#ovl-contact .success, #ovl-contact .rem").remove();			
			$("#ovl-contact .intro, #ovl-contact .form-items, #ovl-contact table, #ovl-contact .links").show();
			
			submitReset();
			contactButtonInit();
			
			return false;
			
		}
	);
	
}

function checkPasswordMatch() {
	
	var pass1 = $("#reg-password-1").val();
	var pass2 = $("#reg-password-2").val();
	
	if(pass1 != pass2 || pass1 == "") {
		return addError("input.password");
	} else {
		return removeError("input.password");
	}
	
}
