documentReady("addContactUsForm");
documentReady("addContactUsFormStyling");
documentReady("setupTabIndexes");
documentReady("addRequiredFieldClasses");
documentReady("addContactFormValidation");
documentReady("stateChangeListener");

var submitButtonLike = "input[id$='contactUsSubmit']";
var addressFieldLabels = new Array();
addressFieldLabels[0] = "Guide to Retirement";
addressFieldLabels[1] = "Information Pack";
addressFieldLabels[2] = "Brochure";
addressFieldLabels[3] = "More Information";
addressFieldLabels[4] = "Newsletter";
addressFieldLabels[4] = "DVD";

var c_nameField = "[id$='contactUs_NameField']";
var c_lastNameField = "[id$='contactUs_LastNameField']";
var c_emailField = "[id$='contactUs_EmailField']";
var c_phoneField = "[id$='contactUs_PhoneField']";
var c_addressField = "[id$='contactUs_AddressField']";
var c_suburbField = "[id$='contactUs_SuburbField']";
var c_stateField = "[id$='contactUs_StateField']";
var c_countryField = "[id$='contactUs_CountryField']";
var c_postcodeField = "[id$='contactUs_PostcodeField']";
var c_enquiryField = "[id$='contactUs_EnquiryField']";
var c_checkEmailField = "[id$='contactUs_ContactFields_0']";
var c_checkPhoneField = "[id$='contactUs_ContactFields_1']";
var c_checkMailField = "[id$='contactUs_ContactFields_2']";

 
 
/** Add actions to the country and state drop downs so that they can respond 
 *  To changes. Most importantly if a country and state other than that in aus
 *  is selected we need to remove the requirement for a postcode
 */
 function stateChangeListener()
 {
 	$(c_countryField).change(function(){
			stateChangeChecker();
		return true;
	});
	
 	$(c_stateField).change(function(){
			stateChangeChecker();
		return true;
	});
 }
 
  /** If Other is selected in the State or Country postcode is not required
  * 
  */
 function stateChangeChecker()
 {
	if($(c_countryField).attr('value') != "Australia" || $(c_stateField).attr('value') == "Other")
	{
		if(isAddressValidationRequired())
			makeFieldNotRequired(c_postcodeField);
	}else if(isAddressValidationRequired())
	{
		makeFieldRequired(c_postcodeField);
	}
 }
 
 
 
 /** Function used just to add styling when needed
  * 
  */
 function addContactUsFormStyling()
 {
 	$(c_nameField).parent().parent().addClass("clearfix");
 }
 
 
 /** Mail validation function
  *  Adds a listener to the submit button
  *  If valid allows server request for Post to continue
  * 
  */
 function addContactFormValidation(){
 	
	$(submitButtonLike).click(
		function()
	    {
			 var validForm = validFormContact();
			 if(validForm)
			 {
				removeContactUsForm();
		 		trackEventClick(siteArea + " Contact Us", "Submit Button", "");
			 }	
			 return validForm;
		}
	);
	
	// The default contact method will be email
	makeFieldRequired(c_emailField);
	$(c_checkEmailField).attr("checked", "checked");	
	
	isPhoneOrEmailRequired(); // on some forms the phone and email is required
 }
 
 function addRequiredFieldClasses()
 {
	addressFieldCheck();
	radioButtonCheck();
	
	// Loop over all the form fields
	$("input[type='text'][id*='ctl00_field']").each(
		 function( intIndex ){
			// Get the fields label
			var textItem = $(this).parent().parent().children("label");
			if(textItem.text().indexOf("*") > -1)
			{
				$(this).addClass("required") // This class makes Jquery validate force the field to be required
				$(this).addClass("contactUs"); // This class will be used by The talk to Us form
				// It allows the Talk to us form to filter out the contact us fields
				// during its validation
			}
		 }
	 );
 }
 
 /** Returns a boolean value indicating if
  * The address fields should be required
  * They are requried if certain checkboxes are checked or the prefered contact method radio buttons are active
  * Used by addressFieldCheck()
  */
function isAddressValidationRequired()
{
	var required = false;
	for (var i=0; i<addressFieldLabels.length; i++) 
	{
		var oneAddressCheckBoxActive = false;
		var label = addressFieldLabels[i];
		if(getCheckBoxByLabel(label) != null)
		{
			if (isCheckBoxActive(label))
				required = true;
		}		
	}
	if($(c_checkMailField).attr("checked"))
		required = true;
	
	return required;
}

/** Main Function that looks at the Prefered Contact Method
 *  and Request checboxes. If any of these are active it sets the address fields to true
 *  The main other purpose of this function is to add action listeners to the checkboxes
 *  and radiobuttons.
 */
function addressFieldCheck()
{
	for (var i = 0; i < addressFieldLabels.length; i++) 
	{
		var label = addressFieldLabels[i];
		if (getCheckBoxByLabel(label) != null) 
		{
			if (isCheckBoxActive(label)) // If when the page loads the guide to retirement is already checked
				addressFieldsRequired();
			
			// Otherwise add a listener so that when this value changes
			// The address fields changes as well
			getCheckBoxByLabel(label).unbind();
			getCheckBoxByLabel(label).click(function(){
			
				if (isAddressValidationRequired()) 
					addressFieldsRequired();
				else 
					addressFieldsNotRequired();
				
				$("label.error").hide();
				
				return true;
			});
		}
	}	
}

/**
 *  Main purpose of function is to add event listeners to the radio buttons
 */
function radioButtonCheck()
{
	$(c_checkMailField).unbind();
	$(c_checkMailField).click(function(){
		
		addressFieldsRequired();
		
		makeFieldNotRequired(c_phoneField);	
		makeFieldNotRequired(c_emailField);	
		
		isPhoneOrEmailRequired();
		
		return true;
	});
	$(c_checkPhoneField).unbind();
	$(c_checkPhoneField).click(function(){
		
		if(!isAddressValidationRequired())
			addressFieldsNotRequired();
	
		makeFieldRequired(c_phoneField);	
	
		makeFieldNotRequired(c_emailField);	
			
		return true;
	});
	$(c_checkEmailField).unbind();
	$(c_checkEmailField).click(function(){
		
		if(!isAddressValidationRequired())
			addressFieldsNotRequired();
		
		makeFieldNotRequired(c_phoneField);	
		
		makeFieldRequired(c_emailField);	
				
		return true;
	});
}
 
 function addressFieldsRequired()
 {
 	makeFieldRequired(c_addressField);
 	makeFieldRequired(c_suburbField);
 	makeFieldRequired(c_stateField);
 	makeFieldRequired(c_countryField);
 	makeFieldRequired(c_postcodeField);
	
	stateChangeChecker(); // Need to check for states and countries other then australia
 }
 
 function addressFieldsNotRequired()
 {
 	makeFieldNotRequired(c_addressField);
 	makeFieldNotRequired(c_suburbField);
 	makeFieldNotRequired(c_stateField);
 	makeFieldNotRequired(c_countryField);
 	makeFieldNotRequired(c_postcodeField);
 }
 
 function makeFieldRequired(field)
 {
	$(field).addClass("required");
	var textItem = $(field).parent().parent().children("label:last");
	if(!($(textItem).text().indexOf("*") > -1))
		textItem.text($(textItem).text() + "*");
 } 
 
  function makeFieldNotRequired(field)
  {
	$(field).removeClass("required");
	var textItem = $(field).parent().parent().children("label:last");
	if($(textItem).text().indexOf("*") > -1)
		textItem.text($(textItem).text().replace("*",""));
  } 
  
 function isCheckBoxActive(label)
 {
	var guideToRetirment = getCheckBoxByLabel(label);
	if(guideToRetirment.is(':checked'))
		return true;	
	return false;
 }
 
 function getCheckBoxByLabel(labelValue)
 {
	return getSiblingByLabel(labelValue, "checkbox");
 }
 
 function getSiblingByLabel(labelValue, type)
 {
	var myItem = null;
	$("input[type='"+type+"'][id*='ctl00_field']").each(
		 function( intIndex ){
			var textItem = $(this).siblings("label");
			if(textItem.text() == labelValue)
			{
				myItem = $(this);
			}
		 }
	 );
	 return myItem;
 }
 
function validFormContact()
{
	 var validator = $("#contactUsForm").validate(
	 {ignore: "[class*='Validation']"}
	 );
	 
 	 contactUsValidationRules();
	 
	 var valid = validator.form();
	 return valid;	
}

function contactUsValidationRules()
{
	$(c_emailField).rules("add", {
	 	email: true,
		messages: {
	 		required: "Email address is required.",
			email: "Please Enter a valid email."
	 	}
	});
	$(c_phoneField).rules("add", {
		 	minlength: 8,
			maxlength: 15,
			phone: true,
			messages: 
			{
			 	phone: "Phone number appears invalid.",
				digits: "Please enter only numbers."
			}
	});
	$(c_postcodeField).rules("add", {
		 	digits: true,
		    minlength: 3,
		    maxlength: 4,
			messages: 
			{
				digits: "Please enter only numbers."
			}
	});
} 
 
function isPhoneOrEmailRequired()
{
	if(getParam("lID") == 8)
	{
		// By Default .. if no others are selected .. make email required
		if($(c_checkPhoneField).not(':checked') && $(c_checkEmailField).not(':checked'))
			makeFieldRequired(c_emailField);
	}
}

function setupTabIndexes()
{
	$(c_nameField).attr("tabindex", "1");
	$(c_lastNameField).attr("tabindex", "2");
	$(c_emailField).attr("tabindex", "3");
	$(c_phoneField).attr("tabindex", "4");
	$(c_addressField).attr("tabindex", "5");
	$(c_suburbField).attr("tabindex", "6");
	$(c_stateField).attr("tabindex", "7");
	$(c_countryField).attr("tabindex", "8");
	$(c_postcodeField).attr("tabindex", "9");
	$(c_enquiryField).attr("tabindex", "10");
	$(c_checkEmailField).attr("tabindex", "11");
	$(c_checkPhoneField).attr("tabindex", "12");
	$(c_checkMailField).attr("tabindex", "13");
	
	var count = 14; 
	var queryString = "input[type='checkbox'][id*='ctl00_field']";
	$(queryString).each(
		 function( intIndex ){
			$(this).attr("tabindex", ""+count);
			count++;
		 }
	 );
	 $(".submitEnquiry").attr("tabindex", ""+count);
}


/* when the page is loaded we inject a temporary form around the contact us area
 * This simplifies validation by restricting it to fields contained within the form
 * once the field is validated by Jquery Validate we remove the form and process the submission
 */

var contactUsFormHolder = "#contactUsFormHolder";
function addContactUsForm()
{
	var tempHolder = $(contactUsFormHolder).html();
	var newForm = "<form id='contactUsForm'></form>";
	$(contactUsFormHolder).html(newForm);
	$("#contactUsForm").html(tempHolder);
}

function removeContactUsForm(){
	var x_name = $(c_nameField).attr("value");
	var x_lastName = $(c_lastNameField).attr("value");
	var x_email = $(c_emailField).attr("value");
	var x_phone = $(c_phoneField).attr("value");
	var x_address = $(c_addressField).attr("value");
	var x_suburb = $(c_suburbField).attr("value");
	var x_state = $(c_stateField).attr("value");
	var x_country = $(c_countryField).attr("value");
	var x_postcode = $(c_postcodeField).attr("value");
	var x_enquiry = $(c_enquiryField).attr("value");
	var x_contactEmail = $(c_checkEmailField).attr("checked");
	var x_contactPhone = $(c_checkPhoneField).attr("checked");
	var x_contactMail = $(c_checkMailField).attr("checked");
	
	var checkboxes = new Array();
	
	var queryString = "input[type='checkbox'][id*='ctl00_field']";
	$(queryString).each(
		 function( intIndex ){
			checkboxes.push($(this).attr("checked"));
		 }
	 );
	
	var tempHolder = $("#contactUsForm").html();
	$(contactUsFormHolder).html(tempHolder);
	
	$(c_nameField).attr("value", x_name);
	$(c_lastNameField).attr("value", x_lastName);
	$(c_emailField).attr("value", x_email);
	$(c_phoneField).attr("value", x_phone);
	$(c_addressField).attr("value", x_address);
	$(c_suburbField).attr("value", x_suburb);
	$(c_stateField).attr("value", x_state);
	$(c_countryField).attr("value", x_country);
	$(c_postcodeField).attr("value", x_postcode);
	$(c_enquiryField).attr("value", x_enquiry);
	if (x_contactEmail) 
	{
		$(c_checkEmailField).attr("checked", "checked");
	}
	else if (x_contactPhone) 
	{
		$(c_checkPhoneField).attr("checked", "true");
	}else if (x_contactMail) 
	{
		$(c_checkMailField).attr("checked", "true");
	}
	
	$(queryString).each(
		 function( intIndex ){
			if(checkboxes[intIndex])
			{
				$(this).attr("checked", "checked");
			}else
			{
				$(this).attr("checked", "");
			}	
		 }
	);
	
}