// JavaScript Document

// Show multiple inputs on step 1 of home for buildings and contents
function setCoverInputs() {
	var policy_type = document.getElementById("policy_type").options[document.getElementById("policy_type").selectedIndex].value
	var b_Input = document.getElementById("b_Input")
	var c_Input = document.getElementById("c_Input")
	var b_label = document.getElementById("b_label")
	var c_label = document.getElementById("c_label")
	
	if (policy_type == "Building and Contents") {
		b_Input.style.display = "";
		b_label.style.display = "";
		c_Input.style.display = "";
		c_label.style.display = "";
	}
	
	if (policy_type == "Building") {
		b_Input.style.display = "";
		b_label.style.display = "none";
		c_Input.style.display = "none";
		c_label.style.display = "none";
	}
	
	if (policy_type == "Contents") {
		b_Input.style.display = "none";
		b_label.style.display = "none";
		c_Input.style.display = "";
		c_label.style.display = "none";
	}
}

// Shows an input box if someone selects "Other" as their occupation
function showOther(selectFieldName, otherContainerName, otherFieldName) {
	if (document.getElementById(selectFieldName).options[document.getElementById(selectFieldName).selectedIndex].value == "Other") {
		if (document.getElementById(otherContainerName).style.display == "none") {
			document.getElementById(otherContainerName).style.display = ""
			document.getElementById(otherFieldName).value = ""
		} else {
			document.getElementById(otherContainerName).style.display = "none"
		}
	} else {
		document.getElementById(otherContainerName).style.display = "none"
	}
}

// Show or hide joint applicant details
function showJoint() {
	var joint = document.getElementById("joint").selectedIndex
	var jointDetails = document.getElementById("jointDetails")
	
	if (joint == 1) {
		jointDetails.style.display = ""
	} else {
		jointDetails.style.display = "none"
	}
}

// Checks to see if a string is numeric (commas and dots are allowed)
function IsNumeric(sText) {
   	var ValidChars = "0123456789,.";
   	var Char;
 
   	for (i = 0; i < sText.length; i++) { 
      	Char = sText.charAt(i); 
      	if (ValidChars.indexOf(Char) == -1) {
        	return false;
    	}
    }
	return true;
}

// Checks if string is a valid phone number
function IsPhone(strng) {
	//strip out acceptable non-numeric characters
	var strippedStrng = strng.replace(/[\(\)\.\-\ ]/g, '');

	// If first character is a + then replace with 00
	var stripped = strippedStrng.replace(/\+/g, '00');
	
	// Check its an integer
	if (isNaN(parseInt(stripped))) {
   		return false;
	}
	
	var i;
	
	// loop through string to check there is no number recurring 7 times in a row
	for (i = 0; i < (stripped.length - 6); i++) {
		var j;
		var subStr2 = "1234567"
		for (j = 0; j <= 9; j++) {
			var subStr = j+''+j+''+j+''+j+''+j+''+j+''+j
			if (stripped.substring(i, i+7) == subStr || stripped.substring(i, i+7) == subStr2) {				
				return false	
			}
		}
	}
	
	// loop through characters and check start is 00, 01, 02, 03, 05, 07 or 08	
    for (i = 0; i < stripped.length; i++) {
		var c = stripped.charAt(i);
		// 1st character must be a 0
		if (i == 0) {
			if (c != 0) {
				return false
			}
		}
		// 2nd character must be a 1		
		if (i == 1) {
			var num2 = c
			if (c != 0 && c != 1 && c != 2 && c != 3 && c != 5 && c != 7 && c != 8) {
				return false
			}
		}
		// 3rd character can not be a 0 if 2nd is
		if (i == 2) {
			if (c == 0 && num2 == 0) {
				return false	
			}
		}
    }	

	// Check greater than 10 characters
	if (!(stripped.length >= 10)) {
		return false;
	}
	return true;
}

// Strip the spaces from a string
function stripSpaces(str) {
	  var spaces = str.length;
	  for(var x = 1; x<spaces; ++x){
	   str = str.replace(" ", "");   
	 }
	 return str;
}

// Checks if string is a valid email
function IsEmail (email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   	if(reg.test(email) == false) {
    	return false;
   	}
	return true;
}

// Checks if string is a valid postcode and returns it in valid format if necessary
function IsPcode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) { document.getElementById("pcode").value = postCode; return true; } else return false;
}

// Checks if string is a valid date
function validateDate(fld) {
    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    if ((fld.match(RegExPattern)) && (fld!='')) {
		return true
    } else {
        return false
    } 
}

// Strip the commas from a string
function stripCommas(str) {
	  var strng = str.length;
	  for(var x = 1; x < strng; ++x){
	   str = str.replace(",", "");   
	 }
	 return str;
}

// Strip the . from a string
function stripFullstops(str) {
	  var strng = str.length;
	  for(var x = 1; x < strng; ++x){
	   str = str.replace(".", "");   
	 }
	 return str;
}

// Checks PPI Quick Quote Form
function calcQuickQuote(input, event) {
	var benefitReq = document.getElementById('benefitReq').value
	var error = "";
	if (!IsNumeric(benefitReq)) {
		alert("You can only input numeric values")	
		error = "Y"
	}
	benefitReq = stripCommas(benefitReq)
	benefitReq = stripFullstops(benefitReq)
	if (benefitReq > 20000) {
		alert("Maximum monthy benefit is 20000 pounds")
		error = "Y"
	}
	
	if (error != "Y") {
		benefitReq = benefitReq/100
		
		// Set Vars
		var ourComRate = 0.20 // Our Commission Rate (%) - B3 on spreadsheet
		var comRate = 0.4 // Their Commission Rate - B4
		
		// Fixed 12 month benefit prices per £100
		var fixasun = 3.9 // B9
		var fixasu30 = 3.63 // B10
		var fixasu60 = 3.37 // B11	
		var fixasn = 2.34 // C9
		var fixas30 = 2.18 // C10
		var fixas60 = 2.02 // C11
		var fixun = 2.34 // D9
		var fixu30 = 2.18 // D10
		var fixu60 = 2.02 // D11
	
		// Vars above minus IPT
		var fixasunNoIPT = (fixasun/1.05).toFixed(2) // B15
		var fixasu30NoIPT = (fixasu30/1.05).toFixed(2) // B16
		var fixasu60NoIPT = (fixasu60/1.05).toFixed(2) // B17	
		var fixasnNoIPT = (fixasn/1.05).toFixed(2) // C15
		var fixas30NoIPT = (fixas30/1.05).toFixed(2) // C16
		var fixas60NoIPT = (fixas60/1.05).toFixed(2) // C17
		var fixunNoIPT = (fixun/1.05).toFixed(2) // D15
		var fixu30NoIPT = (fixu30/1.05).toFixed(2) // D16
		var fixu60NoIPT = (fixu60/1.05).toFixed(2) // D17
	
		// Vars above net of commission 
		var fixasunNetCom = (fixasunNoIPT - (fixasunNoIPT * comRate)).toFixed(2) // B21
		var fixasu30NetCom = (fixasu30NoIPT - (fixasu30NoIPT * comRate)).toFixed(2) // B22
		var fixasu60NetCom = (fixasu60NoIPT - (fixasu60NoIPT * comRate)).toFixed(2) // B23	
		var fixasnNetCom = (fixasnNoIPT - (fixasnNoIPT * comRate)).toFixed(2) // C21
		var fixas30NetCom = (fixas30NoIPT - (fixas30NoIPT * comRate)).toFixed(2) // C22
		var fixas60NetCom = (fixas60NoIPT - (fixas60NoIPT * comRate)).toFixed(2) // C23
		var fixunNetCom = (fixunNoIPT - (fixunNoIPT * comRate)).toFixed(2) // D23
		var fixu30NetCom = (fixu30NoIPT - (fixu30NoIPT * comRate)).toFixed(2) // D23
		var fixu60NetCom = (fixu60NoIPT - (fixu60NoIPT * comRate)).toFixed(2) // D23
	
		var asun = (((1+(ourComRate/(1-ourComRate)))*fixasunNetCom)*1.05)*benefitReq
		document.getElementById('asun').innerHTML = "&pound;" + asun.toFixed(2)
		var asu30 = (((1+(ourComRate/(1-ourComRate)))*fixasu30NetCom)*1.05)*benefitReq
		document.getElementById('asu30').innerHTML = "&pound;" + asu30.toFixed(2)
		var asu60 = (((1+(ourComRate/(1-ourComRate)))*fixasu60NetCom)*1.05)*benefitReq
		document.getElementById('asu60').innerHTML = "&pound;" + asu60.toFixed(2)
		
		var asn = (((1+(ourComRate/(1-ourComRate)))*fixasnNetCom)*1.05)*benefitReq
		document.getElementById('asn').innerHTML = "&pound;" + asn.toFixed(2)
		var as30 = (((1+(ourComRate/(1-ourComRate)))*fixas30NetCom)*1.05)*benefitReq
		document.getElementById('as30').innerHTML = "&pound;" + as30.toFixed(2)
		var as60 = (((1+(ourComRate/(1-ourComRate)))*fixas60NetCom)*1.05)*benefitReq
		document.getElementById('as60').innerHTML = "&pound;" + as60.toFixed(2)
		
		var un = (((1+(ourComRate/(1-ourComRate)))*fixunNetCom)*1.05)*benefitReq
		document.getElementById('un').innerHTML = "&pound;" + un.toFixed(2)
		var u30 = (((1+(ourComRate/(1-ourComRate)))*fixu30NetCom)*1.05)*benefitReq
		document.getElementById('u30').innerHTML = "&pound;" + u30.toFixed(2)
		var u60 = (((1+(ourComRate/(1-ourComRate)))*fixu60NetCom)*1.05)*benefitReq
		document.getElementById('u60').innerHTML = "&pound;" + u60.toFixed(2)
	}
}

// Checks start of Loans form
function checkLoanStart () {
	var loan_type = document.getElementById("loan_type").selectedIndex
	var loan_purpose = document.getElementById("loan_purpose").selectedIndex
	
	var msg = ""
	
	if(loan_type == 0){msg += "Please select a loan type\n"}
	if(loan_purpose == 0){msg += "Please select a purpose for your loan\n"}
	
	if (msg == "") {
		return true;
	} else {
		alert(msg)
		return false;
	}
}

// Checks start of Insurance form
function checkInsStart () {
	var ins_type = document.getElementById("ins_type").selectedIndex
	
	var msg = ""
	
	if(ins_type == 0){msg += "Please select the type of insurance you require\n"}
	
	if (msg == "") {
		return true;
	} else {
		alert(msg)
		return false;
	}
}

// Add an option to select box
function addOption(selectbox,text,value) {
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	document.getElementById(selectbox).options.add(optn);
}

// Change the menu on Question 2 on Re-Mortgage and startBox
function showQ2(type) {
	document.getElementById("Q2").options.length = 0
	
	addOption("Q2", "Please Select", "")
	addOption("Q2", "Unsure", "Unsure")
	addOption("Q2", "Fixed Rate", "Fixed Rate")
	addOption("Q2", "Flexible Mortgage", "Flexible Mortgage")
	if (type == "re-mortgage" || type == "home mover" || type == "buy to let" || type == "let-to-buy" || type == "overseas mortgage") {
		addOption("Q2", "Cash Back", "Cash Back")
		addOption("Q2", "Self-Certification", "Self-Certification")
		addOption("Q2", "Low Credit Rating", "Low Credit Rating")
		addOption("Q2", "100% Mortgage", "100% Mortgage")
	} else if (type == "first time buyer") {
		addOption("Q2", "Cash Back", "Cash Back")
		addOption("Q2", "Self-Certification", "Self-Certification")
		addOption("Q2", "Low Credit Rating", "Low Credit Rating")
		addOption("Q2", "100% Mortgage", "100% Mortgage")
		addOption("Q2", "Council Right To Buy", "Council Right To Buy")
	}
	if (type == "commercial") {
		addOption("Q2", "Low Credit Rating", "Low Credit Rating")
	}
	if (type == "new build mortgage") {
		addOption("Q2", "Self-Certification", "Self-Certification")
		addOption("Q2", "Low Credit Rating", "Low Credit Rating")
	}
	addOption("Q2", "Discounted Rate", "Discounted Rate")
	addOption("Q2", "Tracker Mortgage", "Tracker Mortgage")
	
	document.getElementById("Q2").disabled = ""	
}

// Checks start of Re-Mortgage form
function checkMortStart() {
	var Q1 = document.getElementById("Q1").options[document.getElementById("Q1").selectedIndex].value
	var T_AMOUNT = document.getElementById("T_AMOUNT").value
	
	var msg = ""
	
	if(Q1 == ""){msg += "Please tell us what type of mortgage client you are.\n"}
	if (T_AMOUNT == "") { msg += "Please enter a valid Amount you require.\n"}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}

// Checks step 1 of Life form
function checkLifeStep1 () {
	var cover = document.getElementById("cover").selectedIndex
	var cover2 = document.getElementById("cover2").selectedIndex
	var policy_reason = document.getElementById("policy_reason").selectedIndex
	var amount = document.getElementById("amount").value
	var term = document.getElementById("term").selectedIndex
	
	var msg = ""
	
	if(cover == 0){msg += "Please select the cover you require\n"}
	if(cover2 == 0){msg += "Please select what you want\n"}
	if(policy_reason == 0){msg += "Please select the reason for taking out this policy\n"}
	if(amount == "" || !IsNumeric(amount)){msg += "Please enter a valid amount for the cover that you require.\n"}
	if(term == 0){msg += "Please select the policy term\n"}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}

// Checks step 2 of Life form
function checkLifeStep2 () {
	var gender = document.getElementById("gender").selectedIndex
	var	d_day = document.getElementById("d_day").options[document.getElementById("d_day").selectedIndex].value
	var	d_month = document.getElementById("d_month").options[document.getElementById("d_month").selectedIndex].value
	var	d_year = document.getElementById("d_year").options[document.getElementById("d_year").selectedIndex].value
	var smoked = document.getElementById("smoked").selectedIndex
	var occupation = document.getElementById("occupation").options[document.getElementById("occupation").selectedIndex].value
	if (occupation == "Other") {
		var occupation_o = document.getElementById("occupation_o").value
	}
	var joint = document.getElementById("joint").selectedIndex
	
	// If Joint application
	if (joint == 1) {
		var gender2 = document.getElementById("gender2").selectedIndex
		var	d_day2 = document.getElementById("d_day2").options[document.getElementById("d_day2").selectedIndex].value
		var	d_month2 = document.getElementById("d_month2").options[document.getElementById("d_month2").selectedIndex].value
		var	d_year2 = document.getElementById("d_year2").options[document.getElementById("d_year2").selectedIndex].value
		var smoked2 = document.getElementById("smoked2").selectedIndex
		var occupation2 = document.getElementById("occupation2").options[document.getElementById("occupation2").selectedIndex].value
		if (occupation2 == "Other") {
			var occupation_o2 = document.getElementById("occupation_o2").value
		}
	}
	
	var msg = ""
	
	if(gender == 0){msg += "Please select your gender\n"}
	if(!validateDate(d_month+"-"+d_day+"-"+d_year) || (d_day == 0 || d_month == 0 || d_year == 0)) {msg += "Please enter a valid Date of Birth\n"}
	if(smoked == 0){msg += "Please select whether you are a smoker\n"}
	if(occupation == "" || (occupation == "Other" && occupation_o == "")) {msg += "Please select/enter your occupation\n"}
	if(joint == 0){msg += "Please select whether this is a joint application\n"}
	
	// If Joint application
	if (joint == 1) {
		if(gender2 == 0){msg += "Please select your joint applicants gender\n"}
		if(!validateDate(d_month2+"-"+d_day2+"-"+d_year2) || (d_day2 == 0 || d_month2 == 0 || d_year2 == 0)) {msg += "Please enter a valid Date of Birth for the joint applicant\n"}
		if(occupation2 == "" || (occupation2 == "Other" && occupation_o2 == "")) {msg += "Please select/enter your joint applicants occupation\n"}
		if(smoked2 == 0){msg += "Please select whether your joint applicant is a smoker\n"}
	}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}

// Checks step 3 of Life and Home form
function checkStep3 () {
	var title = document.getElementById("title").selectedIndex
	var fname = document.getElementById("fname").value
	var lname = document.getElementById("lname").value	
	var tel = document.getElementById("tel").value
	var mobile = document.getElementById("mobile").value
	var email = document.getElementById("email").value
	var addr1 = document.getElementById("addr1").value	
	var city = document.getElementById("city").value
	var pcode = document.getElementById("pcode").value
	
	var msg = ""
	
	if(title == 0){msg += "Please select your title\n"}
	if(fname == ""){msg += "Please enter your first name\n"}
	if(lname == ""){msg += "Please enter your surname\n"}
	if(!IsPhone(tel)){msg += "Please enter a valid telephone number\n"}
	if(mobile != "" && !IsPhone(mobile)){msg += "Please enter a valid mobile number\n"}
	if(email == "" || !IsEmail(email)){msg += "Please enter a valid email address\n"}
	if(addr1 == ""){msg += "Please enter the first line of your address\n"}
	if(city == ""){msg += "Please enter the city where you live\n"}
	if(!IsPcode(pcode)){msg += "Please enter a valid postcode\n"}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}

// Checks step 1 of Home form
function checkHomeStep1 () {
	var	policy_type = document.getElementById("policy_type").options[document.getElementById("policy_type").selectedIndex].value
	var policy_excess = document.getElementById("policy_excess").selectedIndex
	
	if (policy_type == "Building and Contents") {
		var policy_amount1 = document.getElementById("policy_amount1").value
		var policy_amount2 = document.getElementById("policy_amount2").value
	} else if (policy_type == "Building") {
		var policy_amount1 = document.getElementById("policy_amount1").value
	} else {
		var policy_amount2 = document.getElementById("policy_amount2").value
	}
	var	rdd = document.getElementById("rdd").options[document.getElementById("rdd").selectedIndex].value
	var	rmm = document.getElementById("rmm").options[document.getElementById("rmm").selectedIndex].value
	var	ryy = document.getElementById("ryy").options[document.getElementById("ryy").selectedIndex].value
	
	var msg = ""
	
	if (policy_type == "") {
			msg += "Please select what cover you require.\n"
	} else {
		if (policy_type == "Building and Contents") {
			if(policy_amount1 == "" || !IsNumeric(policy_amount1)){msg += "Please enter a valid amount for the buildings cover that you require.\n"}
			if(policy_amount2 == "" || !IsNumeric(policy_amount2)){msg += "Please enter a valid amount for the contents cover that you require.\n"}
		} else if (policy_type == "Building") {
			if(policy_amount1 == "" || !IsNumeric(policy_amount1)){msg += "Please enter a valid amount for the buildings cover that you require.\n"}
		} else {
			if(policy_amount2 == "" || !IsNumeric(policy_amount2)){msg += "Please enter a valid amount for the buildings cover that you require.\n"}
		}
	}
	if (policy_excess == "") {msg += "Please select what excess you require.\n"}
	if(!validateDate(rmm+"-"+rdd+"-"+ryy) || (rdd == 0 || rmm == 0 || ryy == 0)) {msg += "Please enter a valid start date\n"}	
	
	// Checks if date is before today
	var currentDate = new Date();
	if (ryy <= currentDate.getFullYear()) {
		if (rmm < currentDate.getMonth()+1) {
			msg += "Please enter a start date that is not before today\n"
		} else if (rmm == currentDate.getMonth()+1) {
			if (rdd < currentDate.getDate()) {
				msg += "Please enter a start date that is not before today\n"
			}
		}
	}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}

// Checks step 2 of Home form
function checkHomeStep2 () {
	var property_type = document.getElementById("property_type").selectedIndex
	var property_year = document.getElementById("property_year").selectedIndex
	var property_rooms = document.getElementById("property_rooms").selectedIndex
	var property_description = document.getElementById("property_description").selectedIndex
	
	var msg = ""
	
	if(property_type == 0){msg += "Please select your property type\n"}
	if(property_year == 0){msg += "Please select the approximate year your property was built\n"}
	if(property_rooms == 0){msg += "Please select the number of rooms in your property\n"}
	if(property_description == 0){msg += "Please select a property description\n"}
	
	if (msg == "") {
		return true
	} else {
		alert(msg)
		return false
	}
}
