﻿var pageReady = false
var n
var qtyArr = new Array(n)
var totArr = new Array(n)
var DescColl = new Array(n)
var CostColl = new Array(n)
var total = 0
var DWSub = 0
var HDDWSub = 0
var TWSub = 0
var deliverySupplement = 0

function checkifReady() {
	if ((document.forms) && (document.images)) {
		pageReady = true
	}
	else {
		i=i+1
		if ( i<10 ) { setTimeout("checkifReady()",1000) }
	}
}


function format(n) {			// Function formats number into corrrect currency formmat
	n = Math.round(100*n)/100
	if (n==Math.floor(n)) { n = n+".00" }
	else { 
		if (10*n==Math.floor(10*n)) { n = n+"0" }
		else  { n = n+"" }
	}
	return n
}




function countN() {				// counts number of items on order form
	if (pageReady) {
		var i = 1
		while (eval("document.orderForm.Qty"+i)) {
			i=i+1
		}
		return i
	}
	else { 
		return 0
	}
}


function initialise() {		// set arrays
	if (descArr.length!=countN()) { alert("priclist and web page have different number of items") }
	for (var i=1;i<countN();i++) {
		qtyArr[i] = 0			// initialise quantity arrays
		totArr[i] = 0			// initialise total arrays
		var formInput = eval("document.orderForm.Qty"+i)
		formInput.value = 0		// initialise Qty input boxes
		formInput = eval("document.orderForm.tot"+i)
		formInput.value = 0		// initialise tot input boxes
		formInput = eval("document.orderForm.Desc"+i)
		formInput.value = descArr[i]
		document.getElementById("desc"+i).innerHTML = descArr[i]
		document.getElementById("cost"+i).innerHTML = format(costArr[i])
		document.getElementById("qnty"+i).innerHTML = "&nbsp;"
		document.getElementById("totl"+i).innerHTML = "&nbsp;"
		
		
	}
	document.getElementById("DWsub").innerHTML = "&nbsp;"
	document.getElementById("HDDWsub").innerHTML = "&nbsp;"
	document.getElementById("TWsub").innerHTML = "&nbsp;"
	document.getElementById("grandTot").innerHTML = "&nbsp;"
	document.getElementById("totText").innerHTML = "&nbsp;"
	document.orderForm.DWsubTotal.value = 0
	document.orderForm.HDDWsubTotal.value = 0
	document.orderForm.TWsubTotal.value = 0
	document.orderForm.grandTotal.value = 0
	document.orderForm.deliverySupp.value = 0
}


function click(i) {		// add quantities to qty input boxes
						// build order summary
	var formInput = eval("document.orderForm.Qty"+i)
	qtyArr[i] = qtyArr[i] + 1								// increment quantity
	formInput.value = qtyArr[i]								// update hidden qty value
	document.getElementById("qnty"+i).innerHTML = qtyArr[i]	// update qty span tyle
	formInput = eval("document.orderForm.tot"+i)
	formInput.value = format(qtyArr[i]*costArr[i])			// update hidden item total
	document.getElementById("totl"+i).innerHTML = formInput.value	// update item total span style
	if (i<3) {
		DWSub = DWSub + costArr[i]
		document.orderForm.DWsubTotal.value = format(DWSub)
		document.getElementById("DWsub").innerHTML = format(DWSub)
		document.getElementById("DWsub").style.textDecoration = "underline"
	}
	else {
		if (i>4) {
			TWSub = TWSub + costArr[i]
			document.orderForm.TWsubTotal.value = format(TWSub)
			document.getElementById("TWsub").innerHTML = format(TWSub)
			document.getElementById("TWsub").style.textDecoration = "underline"
		}
		else {
			HDDWSub = HDDWSub + costArr[i]
			document.orderForm.HDDWsubTotal.value = format(HDDWSub)
			document.getElementById("HDDWsub").innerHTML = format(HDDWSub)
			document.getElementById("HDDWsub").style.textDecoration = "underline"
		}
	}
	total = total + costArr[i]
	document.orderForm.grandTotal.value = format(total)
	document.getElementById("grandTot").innerHTML = format(total)
	document.getElementById("grandTot").style.textDecoration = "underline"
	document.getElementById("grandTot").style.fontWeight = "bold"
	document.getElementById("totText").innerHTML = "Total: "

}


function TWclick(i) {	// transfer TW Grid qtys to installation qty 
	var formInput = eval("document.orderForm.Qty"+i)
	var tot = 0
	var value = 0
	for (var j=5;j<10;j++) {
		if ( document.orderForm.Qty+j != "NaN") {
			value = 1*eval("document.orderForm.Qty"+j+".value")
			tot = tot + value
		}
	}
	if (eval(formInput.value) != tot ) {
		formInput.value = tot									// TW grid qtys
		document.getElementById("qnty"+i).innerHTML = formInput.value	// update item total span style		
		formInput = eval("document.orderForm.tot"+i)
		formInput.value = format(tot*costArr[i])				// update hidden item total
		TWSub = TWSub + costArr[i]								// increment subtotal
		total = total + costArr[i]								// increment total
		document.getElementById("totl"+i).innerHTML = formInput.value	// update item total span style
		document.orderForm.TWsubTotal.value = format(TWSub)
		document.getElementById("TWsub").innerHTML = format(TWSub)
		document.getElementById("TWsub").style.textDecoration = "underline"
		document.orderForm.grandTotal.value = format(total)
		document.getElementById("grandTot").innerHTML = format(total)
		document.getElementById("grandTot").style.textDecoration = "underline"
		document.getElementById("grandTot").style.fontWeight = "bold"
		document.getElementById("totText").innerHTML = "Approximate Total:<span class='super'>2</span> "

	}
}


function DWClear() {	// clear DW grid values
	var formInput
	for (var j=1;j<3;j++) {
		formInput = eval("document.orderForm.Qty"+j)
		formInput.value=0
		qtyArr[j] = 0
		document.getElementById("qnty"+j).innerHTML = "&nbsp;"
		document.getElementById("totl"+j).innerHTML = "&nbsp;"
	}
	total = total - document.orderForm.DWsubTotal.value
	DWSub = 0
	document.orderForm.DWsubTotal.value = 0
	document.getElementById("DWsub").innerHTML = "&nbsp;"
	document.getElementById("DWsub").style.textDecoration = "none"
	if (total==0) {
		document.orderForm.grandTotal.value = 0
		document.getElementById("totText").innerHTML = "&nbsp;"
		document.getElementById("grandTot").innerHTML = "&nbsp;"
		document.getElementById("grandTot").style.textDecoration = "none"
		document.getElementById("grandTot").style.fontWeight = "normal"
	}
	else {
		document.orderForm.grandTotal.value = total
		document.getElementById("grandTot").innerHTML = format(total)
		document.getElementById("grandTot").style.textDecoration = "underline"
		document.getElementById("grandTot").style.fontWeight = "bold"
	}
}

function HDDWClear() {	// clear HDDW grid values
	for (var j=3;j<5;j++) {
		formInput = eval("document.orderForm.Qty"+j)
		formInput.value=0
		qtyArr[j] = 0
		document.getElementById("qnty"+j).innerHTML = "&nbsp;"
		document.getElementById("totl"+j).innerHTML = "&nbsp;"
	}
	total = total - document.orderForm.HDDWsubTotal.value
	HDDWSub = 0
	document.orderForm.HDDWsubTotal.value = 0
	document.getElementById("HDDWsub").innerHTML = "&nbsp;"
	document.getElementById("HDDWsub").style.textDecoration = "none"
	if (total==0) {
		document.orderForm.grandTotal.value = 0
		document.getElementById("totText").innerHTML = "&nbsp;"
		document.getElementById("grandTot").innerHTML = "&nbsp;"
		document.getElementById("grandTot").style.textDecoration = "none"
		document.getElementById("grandTot").style.fontWeight = "normal"
	}
	else {
		document.orderForm.grandTotal.value = total
		document.getElementById("grandTot").innerHTML = format(total)
		document.getElementById("grandTot").style.textDecoration = "underline"
		document.getElementById("grandTot").style.fontWeight = "bold"
	}
}

function TWClear() {	// clear TWDW grid values
	var formInput
	for (var j=5;j<12;j++) {
		formInput = eval("document.orderForm.Qty"+j)
		formInput.value=0
		qtyArr[j] = 0
		document.getElementById("qnty"+j).innerHTML = "&nbsp;"
		document.getElementById("totl"+j).innerHTML = "&nbsp;"
	}
	total = total - document.orderForm.TWsubTotal.value
	TWSub = 0
	document.orderForm.TWsubTotal.value = 0
	document.getElementById("TWsub").innerHTML = "&nbsp;"
	document.getElementById("TWsub").style.textDecoration = "none"
	if (total==0) {
		document.orderForm.grandTotal.value = 0
		document.getElementById("totText").innerHTML = "&nbsp;"
		document.getElementById("grandTot").innerHTML = "&nbsp;"
		document.getElementById("grandTot").style.textDecoration = "none"
		document.getElementById("grandTot").style.fontWeight = "normal"
	}
	else {
		document.orderForm.grandTotal.value = total
		document.getElementById("grandTot").innerHTML = format(total)
		document.getElementById("grandTot").style.textDecoration = "underline"
		document.getElementById("grandTot").style.fontWeight = "bold"
	}
}

function Titlise(Sentence) {	// converts 1st character of the words in a sentence to upper case

	var spPos=0
	var size = Sentence.length
	Sentence=Sentence.toLowerCase()

	if (size>0) {
		while (Sentence.slice(0,1)==" ") {			//Strip leading spaces
			Sentence = Sentence.substr(1,size-1)
			size = Sentence.length
		}  
		while(Sentence.slice(size-1,size)==" ") {	// Strip trailing spaces
			Sentence = Sentence.substr(0,size-1)
			size = Sentence.length
		}

		if (Sentence.indexOf(" ",spPos)==-1) {							// only one word in sentence
			Sentence=Sentence.charAt(0).toUpperCase()+Sentence.slice(1,size)
		}
		else {
			while ( spPos!=-1) {
				spPos = Sentence.indexOf(" ",spPos+1)
				Sentence=Sentence.slice(0,spPos+1)+Sentence.charAt(spPos+1).toUpperCase()+Sentence.slice(spPos+2,size)
			} // end while
		} // end else
	} // end if (size>0)
	return Sentence
} // end function

function isTelephone(v) {
	var nGoodChars = 0
	var nPoints = 0
	var len = v.length
	var goodChar = new Array(" ","0","1","2","3","4","5","6","7","8","9","+")


	for (var i = 0;i<len;i++) {						// loop through each character in input string
		if (i>0) {									// seach string for "+" characters
			if( v.charAt(i) == goodChar[11]) {
			  	return false						// plus  only in 1st position
			}
		}
	}

	for (var i = 0;i<len;i++) {						// loop through each character in input string
		for (var j = 0;j<12;j++) {					// loop though good character
			if( v.charAt(i) == goodChar[j]) {		// found numeral or space
				nGoodChars = nGoodChars + 1			// count good characters
			}
		}
	}

	if (nGoodChars<len) {
		return false
	}

	return true
}

function findHTML(phrase) {
	if (phrase.indexOf("<",0) > -1) { 
		return true
	}
	if (phrase.indexOf(">",0) > -1) {
		 return true
	}
	if (phrase.indexOf("&#60;",0) > -1) {
		return true
	}	
	if (phrase.indexOf("&#62;",0) > -1) {
		return true
	}	
	if (phrase.indexOf("&lt;",0) > -1) {
		return true
	}
	if (phrase.indexOf("&gt;",0) > -1) {
		return true
	}
	return false
}

function Trim(phrase) {	// Strips leading and trailing spaces
	var Sp=" "
	var size = phrase.length
	while (phrase.slice(0,1)==Sp) {					// Strip leading spaces
		phrase = phrase.substr(1,size-1)
		size = phrase.length
	}  
	while(phrase.slice(size-1,size)==Sp) {			// Strip trailing spaces
		phrase = phrase.substr(0,size-1)
		size = phrase.length
	}
	return phrase
}


function validPC() {
	var pCode = document.orderForm.PC

	if (pCode.value == "") {						// post code is a required field
		alert('Please enter your post code. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
		pCode.focus()
		return false
	}

	pCode.value = pCode.value.toUpperCase()			// convert to uppercase
	pCode.value = Trim(pCode.value)					// write back to form field
	var size=pCode.value.length

	var validPCs = new Array(
		"AB","AL","B","BA","BB","BD","BH","BL","BN","BR","BS","BT","CA","CB",
		"CF","CH","CM","CO","CR","CT","CV","CW","DA","DD","DE","DG","DH",
		"DL","DN","DT","DY","E","EC","EH","EN","EX","FK","FY","G","GL","GU",
		"GY","HA","HD","HG","HP","HR","HS","HU","HX","IG","IM","IP","IV","JE",
		"KA","KT","KW","KY","L","LA","LD","LE","LL","LN","LS","LU","M","ME",
		"MK","ML","N","NE","NG","NN","NP","NR","NW","OL","OX","PA","PE","PH",
		"PL","PO","PR","RG","RH","RM","S","SA","SE","SG","SK","SL","SM","SN",
		"SO","SP","SR","SS","ST","SW","SY","TA","TD","TF","TN","TQ","TR","TS",
		"TW","UB","W","WA","WC","WD","WF","WN","WR","WS","WV","YO","ZE","EU","NO")

	var prefix = pCode.value.substr(0,2)			// aquire prefix

	var NBad = 0
	for (var i = 0;i<validPCs.length;i++) {			// count number of mismatches
		if ( prefix != validPCs[i] ) NBad = NBad + 1
	}
	if (NBad == validPCs.length) {
		alert('Invalid post code: \rWrong Prefix: '+prefix+' \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 		pCode.value=""
  		pCode.focus()
		return false
	}

	if ( (pCode.value!="EU") && (pCode.value!="NO") ) {	// allowable prefix

 		if (size < 6 || size > 8) {
			alert('Invalid post code: \rcode is the wrong length. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		if (!(isNaN(pCode.value.charAt(0)))) {				// leftmost character must be a letter
			alert('Invalid post code: \rcode cannot start with a number. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		if (isNaN(pCode.value.charAt(size-3))) {				// first character of inward code must be a number
			alert('Invalid post code: \r2nd part of the post code must start with a number. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		if (!(isNaN(pCode.value.charAt(size-2)))) {			// second character of inward code must be a letter
			alert('Invalid post code: \r2nd part of the post code must start with a number followed by two letters. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		if (!(isNaN(pCode.value.charAt(size-1)))) {			// third character of inward code must be a letter
			alert('Invalid post code: \r2nd part of the post code must start with a number followed by two letters. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		if (!(pCode.value.charAt(size-4) == " "))	{		// space in position length-3 rule
			alert('Invalid post code: \rcode has no space, or space is in the wrong position. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
		var count1 = pCode.value.indexOf(" ")
		var count2 = pCode.value.lastIndexOf(" ")
		if (count1 != count2) {							//only one space rule
			alert('Invalid post code: \rcode must have only one space between the 1st and 2nd parts. \rFor Non-UK orders enter "EU" or"Non-EU" as appropriate')
 			pCode.value=""
  			pCode.focus()
			return false
		}
	}
	
	return true											// postcode OK
}

function CalcdelSupp() {

	if (validPC()) {
		var pCode = document.orderForm.PC
		var prefix = pCode.value.substr(0,2)			// aquire prefix

		document.getElementById("totText").innterHTML = "Total: "
		document.getElementById("suppText").innerHTML = "Free Delivery: "
		document.getElementById("delSupp").innerHTML = "&nbsp;"

		var qtTW = 0			// trackway grid items occupy items 5 to 9
		for (var i=5;i<10;i++) {
			formObj = eval("document.orderForm.Qty"+i)
			qtTW = qtTW +  (1*formObj.value)
		}	
		var	gridQty = qtTW + document.orderForm.Qty1.value + document.orderForm.Qty3.value
		var fenceQty = document.orderForm.Qty2.value + document.orderForm.Qty2.value + document.orderForm.Qty10.value
		var qtDWHDDW = (1*document.orderForm.Qty1.value)+(1*document.orderForm.Qty3.value)

		var deliveryCase = ""
	
		if ((fenceQty>0) && (gridQty==0)) {
			deliveryCase = "fenceonly"
		}
		if ((qtTW>0) && (qtDWHDDW==0)){
			deliveryCase = "trackwayonly"
		}
		if ((qtTW==0) && (qtDWHDDW>0)){
			deliveryCase = "drivewayonly"
		}
		if ((qtTW>0) && (qtDWHDDW>0)){
			deliveryCase = "both"
		}
		if (deliveryCase == "fenceonly") {
			document.getElementById("totText").innerHTML = "Total exluding cost of fence delivery: "
			document.getElementById("suppText").innerHTML = "&nbsp;"
			document.getElementById("delSupp").innerHTML = "&nbsp;"
		}
		else {
			switch(prefix) {
				case "AB":
				case "IV":
				case "TR":
				case "HS":
				case "IM":
				case "JE":
				case "KW":
				case "ZE":
					document.getElementById("totText").innerHTML = "Total excluding cost of delivery: "
					document.getElementById("suppText").innerHTML = "&nbsp;"
					document.getElementById("delSupp").innerHTML = "&nbsp;"
					break
			}
		}
								
		if (total>0) {
			document.orderForm.grandTotal.value = format(total)
			document.getElementById("grandTot").innerHTML = format(total)
			document.getElementById("grandTot").style.textDecoration = "underline"
			document.getElementById("grandTot").style.fontWeight = "bold"
		}
	}
}




function checkOrder() {

	var name	= document.orderForm.N
	var email	= document.orderForm.E
	var add1	= document.orderForm.A1
	var add2	= document.orderForm.A2
	var add3	= document.orderForm.A3
	var add4	= document.orderForm.A4
	var pc		= document.orderForm.PC
	var tel		= document.orderForm.T
	var req		= document.orderForm.R
	
	var size
	
	if (name.value == "") {
		alert("Please enter your name")
		name.focus()
		return false
	}
	if (findHTML(name.value)) {
		alert("Markup not Permitted")
		name.value = ""
		name.focus()
		return false
	}
	name.value=Titlise(name.value)

	var em=email.value.toLowerCase()
	em=Trim(em)
	if (em == "") {
		alert("Please enter your email address")
		email.focus()
		return  false
	}
	var apos = "'"
	var badChars = new Array("/",";",":",",","<",">","&")

	for (var i = 0;i<badChars.length;i++) {
		if( em.indexOf(badChars[i],0) > -1) {
			alert("Invalid email address:\rBad character: "+badChars[i])
			email.focus()
			email.value=""
			return  false
		}
	}

	var atPos = em.indexOf("@",1)
	if (atPos == -1) {
		alert("Invalid email address:\rMissing "+apos+"at"+apos+" character: "+apos+"@"+apos)
		email.focus()
		email.value=""
		return  false
	}

	if (em.indexOf("@",atPos+1) > -1) {
		alert("Invalid email address:\rMore than one @ character")
			email.focus()
			email.value=""
			return  false
	}

	dotPos = em.indexOf(".",atPos)
	if (dotPos == -1) {
		alert("Invalid email address:\rMissing period: "+apos+"."+apos)
			email.focus()
			email.value=""
			return  false
	}

	if (dotPos+3 > em.length ) {
		alert("Invalid email address:\rThere should be at least 2 characters after the period: "+apos+"."+apos)
			email.focus()
			email.value=""
			return  false
	}
	
	var i = 1	// work backwards to focus on 1st missing entry
	if (add4.value != "") { i=i+1; add4.value=Titlise(add4.value) } else { add4.focus() }
	if (add3.value != "") { i=i+1; add3.value=Titlise(add3.value) } else { add3.focus() }
	if (add2.value != "") { i=i+1; add2.value=Titlise(add2.value) } else { add2.focus() }
	if (add1.value != "") { i=i+1; add1.value=Titlise(add1.value) } else { add1.focus() }
	if (i<3) { 
		alert("Please enter your full address")
		return false
	}
	
	if (!validPC()) { return false }

	if (tel.value == "") {
		alert("Please enter your contact number")
		tel.focus()
		return false
	}

	if (!isTelephone(tel.value)) {
		alert("Not a telephone number")
		tel.value = ""
		tel.focus()
		return false
	}

	if (findHTML(tel.value)) {
		alert("Markup not Permitted")
		tel.value = ""
		tel.focus()
		return false
	}


	var totNoItems = 0			// dont allow form submission if no items added to basket
	var formObj

	for (var i=1;i<12;i++) {
		formObj = eval("document.orderForm.Qty"+i)
		totNoItems = totNoItems + (1*formObj.value)
	}
	if ( totNoItems  == 0) {
		alert("No items ordered!")
		return false
	}
	
	var qtTW = 0			// trackway grid items occupy items 5 to 9
	for (var i=5;i<10;i++) {
		formObj = eval("document.orderForm.Qty"+i)
		qtTW = qtTW +  (1*formObj.value)
	}	
	var	gridQty = qtTW + document.orderForm.Qty1.value + document.orderForm.Qty3.value
	var fenceQty = document.orderForm.Qty2.value + document.orderForm.Qty2.value + document.orderForm.Qty10.value
	
	if ((fenceQty>0) && (gridQty==0)) {
		if ( confirm("You have ordered side fencing without a grid.\n is this OK?") ) {
			document.getElementById("totText").innerHTML = "Total, exluding cost of fence delivery: "
			document.getElementById("suppText").innerHTML = "&nbsp;"
			document.getElementById("delSupp").innerHTML = "&nbsp;"
		}
		else {
			return false
		}
	}


	var msg=Trim(req.value)
	size = msg.length
	if (size>0) {
		if (findHTML(msg)) {
			alert("Markup not Permitted")
			req.value = ""
			return false
		}
		msg=msg.charAt(0).toUpperCase()+msg.slice(1,size)		// Capitalise 1st word
		if (msg.charAt(size) != ".") { msg=msg+"."}				// Add full stop
		req.value=msg
	}
	
	CalcdelSupp() 												// recalc delivery supplement:												
	// prefilled postcodes, eg reloaded page will mean no onchange event; CalcdelSupp() not called
		
	document.orderForm.action = TEAdecrypt("!13!gõø½x-Qzs")			// Decryption function in tea_de.js
	return true	// Form OK
}


