documentReady("addContactUsForm");
documentReady("addContactUsFormStyling");
documentReady("setupTabIndexes");
documentReady("addRequiredFieldClasses");
documentReady("addContactFormValidation");
documentReady("stateChangeListener");

var submitButtonLike = "div.scfSubmitButtonBorder input";
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_titleField = "[id$='field_BCBB78C0E32140A6BE258F45115D9309'],[id$='field_51FD85DD47BA445B97CDF267D5D0983B']";
var c_nameField = "[id$='field_2C0082AADE4E4B8F91C96F15D987B339'],[id$='field_7ADB1ED4D2004402A3A5023F5D556B93']";
var c_lastNameField = "[id$='field_55D44DA1D884425585485CC3B5ACA9A4'],[id$='field_608150B990FE4F0C816A24ED2EA02414']";
var c_emailField = "[id$='field_442CA0EC9E0A458BBFA1B9A424F910FC'],[id$='field_A0C4B918CA5049F2A7A9B67DEAD8CBDB']";
var c_phoneField = "[id$='field_599B2F8B81CF40BCBE604D1EE088BF58'],[id$='field_DE4458C24CFC4E4E958C9F9D7537B078']";
var c_addressField = "[id$='field_3A6E368DA0004E55913C3BCF3FB594E9'],[id$='field_12620D0522B84E268A9AB14739727C7F']";
var c_suburbField = "[id$='field_9D634DA6E7304416A2AAF0B2B3C7909E'],[id$='field_1C3AAE62F5C94D41BEEF8E2A066217E9']";
var c_stateField = "[id$='field_8605E26CE90C424BB766B65ECC2E46D1'],[id$='field_077B90944FF9472192D8E43324ADCB82']";
var c_countryField = "[id$='field_27C8667FF65F41BFAF6E23036F3ABFEB'],[id$='field_AB766BF852F3405FA204482F0BD3DD2F']";
var c_postcodeField = "[id$='field_B98118EF01494D20861B223EE5B0979B'],[id$='field_3CEF1723FFC347539DF24030478811F0']";
var c_enquiryField = "[id$='field_4DF464CFCC3D4025A42DC24BCDACAAA7'],[id$='field_78BC578758164E6B8EAF0C8FED795FA8']";
var c_checkEmailField = "[id$='contactUs_ContactFields_0'] input";
var c_checkPhoneField = "[id$='contactUs_ContactFields_1'] input";
var c_checkMailField = "[id$='contactUs_ContactFields_2'] input";
var c_hearAboutUs = "[id$='field_A62F78314205403197C0B18F90ACD4C7'],[id$='field_4927B22ECA8C45CBAF682F4EB9A8498F']";

 
 
/** 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()
 {
 	jQuery(c_countryField).change(function(){
			stateChangeChecker();
		return true;
	});
	
 	jQuery(c_stateField).change(function(){
			stateChangeChecker();
		return true;
	});
 }
 
  /** If Other is selected in the State or Country postcode is not required
  * 
  */
 function stateChangeChecker()
 {
	if(jQuery(c_countryField).attr('value') != "Australia" || jQuery(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()
 {
 	jQuery(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(){
 	
	jQuery(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);
	makeFieldRequired(c_titleField);
	jQuery(c_checkEmailField).attr("checked", "checked");

	//Check if we are on the aged care contact us page.
	//If so, then make phone the default required field.
	if (location.href.toLowerCase().match(/\/agedcare\//))
	{
	    makeFieldNotRequired(c_emailField);
	    makeFieldRequired(c_phoneField);
	    jQuery(c_checkPhoneField).attr("checked", "checked");
	}
	
	isPhoneOrEmailRequired(); // on some forms the phone and email is required
 }
 
 function addRequiredFieldClasses()
 {
	addressFieldCheck();
	radioButtonCheck();
	
	// Loop over all the form fields
	jQuery("input[type='text'][id*='ctl00_field']").each(
		 function( intIndex ){
			// Get the fields label
			var textItem = jQuery(this).parent().parent().children("label");
			if(textItem.text().indexOf("*") > -1)
			{
				jQuery(this).addClass("required") // This class makes Jquery validate force the field to be required
				jQuery(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(jQuery(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();
				
				jQuery("label.error").hide();
				
				return true;
			});
		}
	}	
}

/**
 *  Main purpose of function is to add event listeners to the radio buttons
 */
function radioButtonCheck()
{
	jQuery(c_checkMailField).unbind();
	jQuery(c_checkMailField).click(function(){
		
		addressFieldsRequired();
		
		makeFieldNotRequired(c_phoneField);	
		makeFieldNotRequired(c_emailField);	
		
		isPhoneOrEmailRequired();
		
		return true;
	});
	jQuery(c_checkPhoneField).unbind();
	jQuery(c_checkPhoneField).click(function(){
		
		if(!isAddressValidationRequired())
			addressFieldsNotRequired();
	
		makeFieldRequired(c_phoneField);	
	
		makeFieldNotRequired(c_emailField);	
			
		return true;
	});
	jQuery(c_checkEmailField).unbind();
	jQuery(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)
 {
	jQuery(field).addClass("required");
	var textItem = jQuery(field).parent().parent().children("label:last");
	if(!(jQuery(textItem).text().indexOf("*") > -1))
		textItem.text(jQuery(textItem).text() + "*");
 } 
 
  function makeFieldNotRequired(field)
  {
	jQuery(field).removeClass("required");
	var textItem = jQuery(field).parent().parent().children("label:last");
	if(jQuery(textItem).text().indexOf("*") > -1)
		textItem.text(jQuery(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;
	jQuery("input[type='"+type+"'][id*='ctl00_field']").each(
		 function( intIndex ){
			var textItem = jQuery(this).siblings("label");
			if(textItem.text() == labelValue)
			{
				myItem = jQuery(this);
			}
		 }
	 );
	 return myItem;
 }
 
function validFormContact()
{
	 var validator = jQuery("#contactUsForm").validate(
	 {ignore: "[class*='Validation']"}
	 );
	 
 	 contactUsValidationRules();
	 
	 var valid = validator.form();
	 return valid;	
}

function contactUsValidationRules()
{
	jQuery(c_emailField).rules("add", {
	 	email: true,
		messages: {
	 		required: "Email address is required.",
			email: "Please Enter a valid email."
	 	}
	});
	jQuery(c_phoneField).rules("add", {
		 	minlength: 8,
			maxlength: 15,
			phone: true,
			messages: 
			{
			 	phone: "Phone number appears invalid.",
				digits: "Please enter only numbers."
			}
    });
	
	var maxPostCode = 4;
	var digits = true;
	if(jQuery(c_countryField).attr("value") == 'Other')
	{
	    digits = false;
	    maxPostCode = 12;
	}
	jQuery(c_postcodeField).rules("add", {
		 	digits: digits,
		    minlength: 3,
		    maxlength: maxPostCode,
			messages: 
			{
				digits: "Please enter only numbers."
			}
	});
} 
 
function isPhoneOrEmailRequired()
{
	if(getParam("lID") == 8)
	{
		// By Default .. if no others are selected .. make email required
		if(jQuery(c_checkPhoneField).not(':checked') && jQuery(c_checkEmailField).not(':checked'))
			makeFieldRequired(c_emailField);
	}
}

function setupTabIndexes()
{
    jQuery(c_titleField).attr("tabindex", "1");
	jQuery(c_nameField).attr("tabindex", "2");
	jQuery(c_lastNameField).attr("tabindex", "3");
	jQuery(c_phoneField).attr("tabindex", "4");
	jQuery(c_emailField).attr("tabindex", "5");
	jQuery(c_addressField).attr("tabindex", "6");
	jQuery(c_suburbField).attr("tabindex", "7");
	jQuery(c_stateField).attr("tabindex", "8");
	jQuery(c_countryField).attr("tabindex", "9");	
	jQuery(c_postcodeField).attr("tabindex", "10");
	jQuery(c_enquiryField).attr("tabindex", "11");
	jQuery(c_checkEmailField).attr("tabindex", "12");
	jQuery(c_checkPhoneField).attr("tabindex", "13");
	jQuery(c_checkMailField).attr("tabindex", "14");
	jQuery(c_hearAboutUs).attr("tabindex", "15");
	
	var count = 15; 
	var queryString = "input[type='checkbox'][id*='ctl00_field']";
	jQuery(queryString).each(
		 function( intIndex ){
			jQuery(this).attr("tabindex", ""+count);
			count++;
		 }
	 );
	 jQuery(".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 = "[id$='Div1']";
function addContactUsForm()
{
	var tempHolder = jQuery(contactUsFormHolder).html();
	var newForm = "<form id='contactUsForm'></form>";
	jQuery(contactUsFormHolder).html(newForm);
	jQuery("#contactUsForm").html(tempHolder);
}

function removeContactUsForm() {
    var x_title = jQuery(c_titleField).attr("value");
	var x_name = jQuery(c_nameField).attr("value");
	var x_lastName = jQuery(c_lastNameField).attr("value");
	var x_email = jQuery(c_emailField).attr("value");
	var x_phone = jQuery(c_phoneField).attr("value");
	var x_address = jQuery(c_addressField).attr("value");
	var x_suburb = jQuery(c_suburbField).attr("value");
	var x_state = jQuery(c_stateField).attr("value");
	var x_country = jQuery(c_countryField).attr("value");
	var x_postcode = jQuery(c_postcodeField).attr("value");
	var x_enquiry = jQuery(c_enquiryField).attr("value");
	var x_contactEmail = jQuery(c_checkEmailField).attr("checked");
	var x_contactPhone = jQuery(c_checkPhoneField).attr("checked");
	var x_contactMail = jQuery(c_checkMailField).attr("checked");
	var x_hearAboutUs = jQuery(c_hearAboutUs).attr("value");
	
	var checkboxes = new Array();
	
	var queryString = "input[type='checkbox'][id*='ctl00_field']";
	jQuery(queryString).each(
		 function( intIndex ){
			checkboxes.push(jQuery(this).attr("checked"));
		 }
	 );
	
	var tempHolder = jQuery("#contactUsForm").html();
	jQuery(contactUsFormHolder).html(tempHolder);

	jQuery(c_titleField).attr("value", x_title);
	jQuery(c_nameField).attr("value", x_name);
	jQuery(c_lastNameField).attr("value", x_lastName);
	jQuery(c_emailField).attr("value", x_email);
	jQuery(c_phoneField).attr("value", x_phone);
	jQuery(c_addressField).attr("value", x_address);
	jQuery(c_suburbField).attr("value", x_suburb);
	jQuery(c_stateField).attr("value", x_state);
	jQuery(c_countryField).attr("value", x_country);
	jQuery(c_postcodeField).attr("value", x_postcode);
	jQuery(c_enquiryField).attr("value", x_enquiry);
	jQuery(c_hearAboutUs).attr("value", x_hearAboutUs);
	
	if (x_contactEmail) 
	{
		jQuery(c_checkEmailField).attr("checked", "checked");
	}
	else if (x_contactPhone) 
	{
	    jQuery(c_checkPhoneField).attr("checked", "checked");
	}else if (x_contactMail) 
	{
	    jQuery(c_checkMailField).attr("checked", "checked");
	}
	
	jQuery(queryString).each(
		 function( intIndex ){
			if(checkboxes[intIndex])
			{
				jQuery(this).attr("checked", "checked");
			}else
			{
				jQuery(this).attr("checked", "");
			}	
		 }
	);
	
}
