var myMonthYearCode = "0510";

var itemsInBasketSoFar = 0;


//alert("Sorry - Web site closed please phone if you would like to place an order");



function navigate2(pageAddress) {
	pageAddress = pageAddress + ".html";
	top.location.href = pageAddress;
}



	



function viewBasket() {
	top.location.href = "shopping_basket.html";
}




var postageTotalForNextPage = 0;




// tests for cookies enabled
var cookieEnabled = false;
if (typeof document.cookie == "string") {
	if (document.cookie.length == 0) {
		setCookie("ctfctest", "hello");
		var joanallenctestRead = getCookie("ctfctest");
		if (joanallenctestRead == "hello") {
			cookieEnabled = true;
		}
		else {
			cookieEnabled = false;
		}
	}
	else {
		cookieEnabled = true;
	}
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1) {
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return getCookieVal(j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return "";
}

function setCookie(name, value) {
	var exp = new Date(); // to fix bug with Safari
	exp.setTime(exp.getTime() + 995000000);
	var expires = true;
	var path = false;
	var domain = false;
	var secure = false;

	document.cookie = name + "=" + escape (value) +
		((expires) ? "; expires=" + exp.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}

function deleteCookie(name,path,domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";

	}
}


function cookiesNotOnMessage() {
	alert("Your web browser is not accepting cookies which are necessary for our e-commerce system.  Please either enable cookies or order via our Sales Hotline");

}


function knockOffSomeDecPlaces(expr, decplaces) {	
	var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces));
	while (str.length <= decplaces) { str = "0" + str; }
	var decpoint = str.length - decplaces
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}	



function fillBasketDiv(extraToAdd) { // extraToAdd will be 0 or a number
	var basketTotal = getCookie("ctfTotal");
	if (basketTotal == "") {
		basketTotal = 0;
	}
	else {
		basketTotal = parseFloat(basketTotal);
	}
	basketTotal += parseFloat(extraToAdd);
	basketTotal = knockOffSomeDecPlaces(basketTotal, 2);
	setCookie("ctfTotal", basketTotal);
	var basketHTML = "";
	if ( basketTotal > 0 ) {
		basketHTML += '<p><button onclick="viewBasket()">View Basket</button></p><p class="amount"><a href="shopping_basket.html"><img src="images\/basketlogoflash.gif" alt="Click to view your shopping basket" \/></a>&nbsp;: &pound;' + basketTotal + '</p>';
	}
	else {
		basketHTML += '<p><img src="images\/basketlogo.gif" alt="*" \/>&nbsp;: &pound;0.00</p>';

	}
	document.getElementById("basket").innerHTML = basketHTML;
}


function addItemToBasketArray(itemNumber) {
	var basketArray = getCookie("ctfBasketItems");
	var eitmStr = "EITM";
	if (basketArray == "") { //no items yet
		eitmStr = ""; // don't want on first item
	}
	basketArrayStr = new String(basketArray);
	basketArrayStr += eitmStr;
	basketArrayStr += itemNumber;
	setCookie("ctfBasketItems", basketArrayStr);
}








function addToBasket(locPrice, locItemNo) {
	if (cookieEnabled == false) {
		cookiesNotOnMessage();
	}
	else {
		addItemToBasketArray(locItemNo);		
		fillBasketDiv(parseFloat(locPrice)); // adds to Total etc
		alert("This item has been added to your basket. Please click on View Basket when you are ready to check out.")							
	}
}
 





function getSearchAsArray() {
	var theResults = new Array()
	var input = unescape(location.search.substr(1))
	if (input) {
		var srchArray = input.split("&")
		var tempArray = new Array()
		for (var i = 0; i < srchArray.length; i++) {
			tempArray = srchArray[i].split("=")
			var varForKeyForArray = "'" + tempArray[0] + "'";
			theResults[varForKeyForArray] = tempArray[1]
		}
	}
	return theResults
}



/////////////////////// SHOPPING BASKET PAGE //////////////////





// ** BEGIN GLOBAL ADJUSTMENTS ** //
// Order form columns and rows specifications
// **Column titles CANNOT CONTAIN PERIODS
var columnHeads = "Qty,Description,Total, , ".split(",");
var columnWidths = "3,40,7".split(",");
var numberOfRows = itemsInBasketSoFar;
// data entry row math

 

function makeTitleRow() {
	var titleRow = '<tr>';
	for (var i = 0; i < columnHeads.length; i++) {
titleRow += '<th>' + columnHeads[i] + '</th>';
	}
	titleRow += '</tr>';
	return titleRow;
}



function makeOneRow(rowNum) {
	var oneRow = '<tr>';
	for (var i = 0; i < ( columnHeads.length - 2) ; i++) {
oneRow += '<td><input class="textfield" type="text" size="' + 
	columnWidths[i] + '" name="' + columnHeads[i] + 
	'" /></td>';
	}
	oneRow += '<td></td>';
	oneRow += '<td><button class="standard" onClick="removeAnItem(' + rowNum + ')">Remove</button></td>';
	oneRow += '</tr>';
	oneRow += '<tr><td>&nbsp;</td><td><input class="textfield" type="text" size="40" name="DescCont1" /></td><td colspan="' + (columnHeads.length - 2) + '">&nbsp;</td></tr>';
	oneRow += '<tr><td>&nbsp;</td><td><input class="textfield" type="text" size="40" name="DescCont2" /></td><td colspan="' + (columnHeads.length - 2) + '">&nbsp;</td></tr>';
	return oneRow
}



function initialiseBasket() { 
		var newHTML2 = "";
		var basketArrayRaw = getCookie("ctfBasketItems");
		if (basketArrayRaw == "") { //no items yet
			newHTML2 += '<p>You have not added anything to your shopping basket yet.</p>';
			newHTML2 += '<p class="buttons"><button class="standard" onClick="keepShopping()">Continue shopping ...</button></p>';
		}
		else { // there are items
			var str = new String(basketArrayRaw);
			var re = /EITM/;
			if ( str.indexOf("EITM") == -1) {
				arrayOfItems[0] = str;
				itemsInBasketSoFar = 1;
			}
			else {
				arrayOfItems = str.split(re);
				itemsInBasketSoFar = arrayOfItems.length;
			}
			newHTML2 += '<form onsubmit="return false"><table class="checkout">';
			newHTML2 += makeTitleRow();
			// order form entry rows
			numberOfRows = itemsInBasketSoFar; //updates
			for (var i = 0; i < numberOfRows; i++) {
				newHTML2 += makeOneRow(i);
			}

			newHTML2 += '<tr><td colspan="5">&nbsp;</td></tr>'; 
			newHTML2 += '<tr><td></td>'; 
			newHTML2 += '<td id="postageTotal">Delivery to a UK address *</td>';
			newHTML2 +=	'<td><input type="text" class="textfield" size="7" name="totalpost" /></td><td colspan="2">&nbsp;</td></tr>';

			newHTML2 += '<tr><td colspan="5">&nbsp;</td></tr>'; 
			newHTML2 += '<tr><td colspan="1"></td>'; 
			newHTML2 += '<td class="grandTotal" colspan="1">Total (VAT is not applicable&nbsp;&nbsp; &pound;</td>';
			newHTML2 +=	'<td><input type="text" class="textfield" size="7" name="total" /></td><td colspan="2">&nbsp;</td></tr>';
			newHTML2 +=	'</table></form>';
		}

		window.document.getElementById("theform").innerHTML = newHTML2;
}




var highOrLow = "high";

function populateCheckoutVariablesArray(myReferrer) {
		var subTotal = 0;
		var postTotal = 6.50;
		if (itemsInBasketSoFar == 0) { ; } // do nothing
		else {
			var unitPriceWithVAT = 0;
			var mainDesc = "";
			var dC1 = "";
			var dC2 = "";
			if ( itemsInBasketSoFar == 1 ) { 
				var itemNo = parseInt(arrayOfItems[0]);
				var str = new String(arDet[itemNo])
				var re = /_sep_/
				var arrayOfItemFields = str.split(re)
	
				// can't have a detector and accessories - only 1 item
				unitPriceWithVAT = parseFloat(arrayOfItemFields[0]);

				postTotal = parseFloat(arrayOfItemFields[1]);
				mainDesc = arrayOfItemFields[2];;
				dC1 = arrayOfItemFields[3];
				dC2 = arrayOfItemFields[4];
				document.forms[0].Qty.value = "1";
				document.forms[0].Description.value = mainDesc;
				document.forms[0].DescCont1.value = dC1;
				document.forms[0].DescCont2.value = dC2;
				document.forms[0].Total.value = knockOffSomeDecPlaces(unitPriceWithVAT,2);
				subTotal += unitPriceWithVAT;
				// var withoutVAT = knockOffSomeDecPlaces(unitPriceWithVAT*0.86956,2);
				// document.forms[0].ExVAT.value = withoutVAT;
				// document.forms[0].VAT.value = knockOffSomeDecPlaces(unitPriceWithVAT - withoutVAT,2);
				document.forms[0].Qty.readOnly = true;
				document.forms[0].Description.readOnly = true;
				document.forms[0].DescCont1.readOnly = true;
				document.forms[0].DescCont2.readOnly = true;
				document.forms[0].Total.readOnly = true;
			}
			else {

				for (var i = 0; i < arrayOfItems.length; i++ ) { //an item at a time
					var itemNo = parseInt(arrayOfItems[i]);
					var str = new String(arDet[itemNo])
					var re = /_sep_/
					var arrayOfItemFields = str.split(re)



					var costRaw = new String(arrayOfItemFields[0]);
					re = /or/;
					var newCostArray = new Array();
					var costHigh = 0;
					var costLow = 0;
					var costFinal = 0;
					if ( costRaw.indexOf("or") != -1) {
						newCostArray = costRaw.split(re);
						costHigh = newCostArray[0];
						costLow = newCostArray[1];
						if (highOrLow == "low") {
							costFinal = parseFloat(costLow)
						}
						else {
							costFinal = parseFloat(costHigh)
						}
					}
					else {
						costFinal = parseFloat(arrayOfItemFields[0])
					}


					unitPriceWithVAT = parseFloat(costFinal);
					postTotal += parseFloat(arrayOfItemFields[1]);
					mainDesc = arrayOfItemFields[2];;
					dC1 = arrayOfItemFields[3];
					dC2 = arrayOfItemFields[4];
					document.forms[0].Qty[i].value = "1";
					document.forms[0].Description[i].value = mainDesc;
					document.forms[0].DescCont1[i].value = dC1;
					document.forms[0].DescCont2[i].value = dC2;	
					document.forms[0].Total[i].value = knockOffSomeDecPlaces(unitPriceWithVAT,2);
					subTotal += unitPriceWithVAT;
					//var withoutVAT = knockOffSomeDecPlaces(unitPriceWithVAT*0.86956,2);
					//document.forms[0].ExVAT[i].value = withoutVAT;
					//document.forms[0].VAT[i].value = knockOffSomeDecPlaces(unitPriceWithVAT - withoutVAT,2);
					document.forms[0].Qty[i].readOnly = true;
					document.forms[0].Description[i].readOnly = true;
					document.forms[0].DescCont1[i].readOnly = true;
					document.forms[0].DescCont2[i].readOnly = true;
					document.forms[0].Total[i].readOnly = true;
				}
			}
			if (postTotal > 6.50 ) {
				postTotal = 6.50;
			}
			if (subTotal > 999.99) {
				postTotal = 0;
				document.getElementById("postageTotal").innerHTML = "<strong>FREE DELIVERY</strong> to a Mainland UK address *";
			}

			postageTotalForNextPage = postTotal;
			subTotal += postTotal;

			// var postWithoutVAT = knockOffSomeDecPlaces(postTotal*0.86956,2);
	
			document.forms[0].totalpost.value = knockOffSomeDecPlaces(postTotal,2);
			if (postTotal > 0) {
				// document.forms[0].postexvat.value = postWithoutVAT;
				//document.forms[0].postvat.value = knockOffSomeDecPlaces(postTotal - postWithoutVAT,2);
			}
			else {
				//document.forms[0].postexvat.value = "0.00";
				//document.forms[0].postvat.value = "0.00";
			}

			//document.forms[0].postexvat.readOnly = true;
			document.forms[0].totalpost.readOnly = true;
			//document.forms[0].postvat.readOnly = true;

			document.forms[0].total.value = knockOffSomeDecPlaces(subTotal,2);
			document.forms[0].total.readOnly = true;

			var newHTML = ""
			if ( itemsInBasketSoFar > 2 ) { 
				newHTML += '<p class="buttons"><button class="checkout" onClick="checkOut()">';
				newHTML += 'Click to Check Out</button>&nbsp;&nbsp;&nbsp;';
				newHTML += '<button class="standard" onClick="keepShopping()">';
				newHTML += 'Keep Shopping</button>&nbsp;&nbsp;&nbsp;<button class="standard" onClick="window.print()">Print</button></p>';
			}

			newHTML += '<p id="nonuk1"><strong>* UK DELIVERIES ONLY:<br />Delivery charges are priced at &pound;6.50 per delivery<br />VAT does not apply to our products.</p>';



			document.getElementById("bottombit").innerHTML = newHTML;





			newHTML = '<p class="buttons"><button class="checkout" onClick="checkOut()">';
			newHTML += 'Click to Check Out</button>&nbsp;&nbsp;&nbsp;';
			newHTML += '<button class="standard" onClick="keepShopping()">';
			newHTML += 'Keep Shopping</button>&nbsp;&nbsp;&nbsp;<button class="standard" onClick="window.print()">Print</button></p>';
			
			if (myReferrer != "removeAnItem") { //causes crashing 5.5
				document.getElementById("topbit").innerHTML = newHTML;
			}
		}
		document.getElementById("baskettitle").innerHTML = "Shopping Basket";
		setCookie("ctfTotal", subTotal);
		if (myReferrer == "removeAnItem") { //only way to clear topbit div without crashing 5.5
			location.href="shopping_basket.html";
		}

} // END OF populateCheckoutVariablesArray









function removeAnItem(rowNumber) {
	itemsInBasketSoFar -= 1;
	var str = "";
	if ( itemsInBasketSoFar == 0 ) {
		document.getElementById("bottombit").innerHTML = "";
		str = "";
	}
	else { 
		str = ""; 
		for (var i = 0; i < arrayOfItems.length; i++) {
			if ( i != rowNumber ) { // i.e. skip the one we want to remove
				str += arrayOfItems[i];
				if ( rowNumber == (arrayOfItems.length - 1) && i == (arrayOfItems.length - 2) ) { ; } // if last row is being removed and this is row before last
				else if ( i != (arrayOfItems.length - 1) && arrayOfItems.length != 2 ) { str += "EITM"; } // don't append eitm to last item	
			}
		}
	}
	setCookie("ctfBasketItems", str);
	initialiseBasket();
	populateCheckoutVariablesArray('removeAnItem');
//	location.href="a_shopping_basket.html";
}




function keepShopping() {
	var arrayOfPagesVisited = new Array();
	var pageVisitedArray = getCookie("ctfPageHistory");
	if (pageVisitedArray == "") { //just in case 
		location.href = "shop-online.html";
	}
	else {
		var str = new String(pageVisitedArray);
		var re = /_/;
		if ( str.indexOf("_") == -1) {
		//	location.href = swopPageNoForUrl(str);
		location.href = "shop-online.html"; // we want to go to home page for this site
		}
		else {
			arrayOfPagesVisited = str.split(re);
			var lastPageVisited = arrayOfPagesVisited[arrayOfPagesVisited.length - 1]
			if (parseInt(lastPageVisited) > 0 && parseInt(lastPageVisited) < 200) { // pages that sell must be less than 200
				// location.href = swopPageNoForUrl(lastPageVisited);	
				location.href = "shop-online.html"; // we want to go to home page for this site

			}
			else { // non selling page
				location.href = "shop-online.html";
			}
		}
	}
}



function checkOut() {
	var myUrl = "a_prelloydsbank.html"; 
	location.href=myUrl; 

}

////////////////// END SHOPPING BASKET PAGE ////////////////////////





////////// A-PRELLOYDS /////





function setOrderNumber() {
	theOrderNo = Math.floor(Math.random() * 99999);
	if (isNaN(theOrderNo)) {
		var myToday = new Date();
		theOrderNo = myToday.getTime();
		theOrderNo -= 1007743980440;	
		theOrderNo = "DR" + myMonthYearCode + "N" + theOrderNo;
	}
}
 


function plusEqualsEtc(textString) {
	var re1 = /\+/gi
	var re2 = /=/gi
	var re3 = /&/gi
	str = new String(textString)
	str = str.replace(re1,"plusSign")
	str = str.replace(re2,"equalsSign")
	str = str.replace(re3,"amperSand")
	return str;
}


function plusEqualsEtc2(textString) {
	var re1 = /\+/gi
	var re2 = /=/gi
	var re3 = /&/gi
	var re4 = /\n/gi
	str = new String(textString)
	str = str.replace(re1,"plusSign")
	str = str.replace(re2,"equalsSign")
	str = str.replace(re3,"amperSand")
	str = str.replace(re4,"newLineSi")
	return str;
}


function checkEmail() {
	continueSubmit = "yes";
	var emailFault = "no";
	var myRegExp = / /gi
	str = new String(document.forms[0].deliveryEmail.value)
	str = str.replace(myRegExp,"")
	var myRegExp2 = /\./;
	var myRegExp3 = /\@/;
	var myRegExp4 = /\,/;
	var myRegExp5 = /www\./;
	if ( str.search(myRegExp4) != -1 ) {
		emailFault = "yes";
		alert("Your email address seems to be wrong");
	}
	else if ( str.search(myRegExp2) == -1 ) {
		emailFault = "yes";
		alert("Your email address seems to be wrong");
	}
	else if ( str.search(myRegExp3) == -1 ) {
		emailFault = "yes";
		alert("Your email address seems to be wrong");
	}
	else if ( str.search(myRegExp5) != -1 ) {
		emailFault = "yes";
		alert("Your email address seems to be wrong - it should not contain www. ");
	}
	if ( emailFault == "yes" ) {
		continueSubmit = "no";		
	}	
}



function checkAndSubmitCheckout() {
	checkEmail();

	if ( continueSubmit == "yes" ) {
		if ( document.forms[0].deliveryName.value == "" ) {
			alert("Please type your name into the form");
			continueSubmit = "no";
		}
	}

	if ( continueSubmit == "yes" ) {
		document.forms[0].theOrderNo.value = theOrderNo;
		var myRegExp50 = /sm1105/gi;
		str = new String(document.forms[0].saveCode.value)
		if ( str.search(myRegExp50) != -1 ) {
			alert("Your five percent discount has now been automatically applied")
			document.forms[0].totalInPounds.value = knockOffSomeDecPlaces(totalInPounds*0.95, 2);
		}
		else {
			document.forms[0].totalInPounds.value = totalInPounds;
		}
		document.forms[0].theVariables.value = plusEqualsEtc(theBasketArray);
		document.forms[0].deliveryName.value = plusEqualsEtc(document.forms[0].deliveryName.value);
		document.forms[0].deliveryPhone.value = plusEqualsEtc(document.forms[0].deliveryPhone.value);
		document.forms[0].deliveryEmail.value = plusEqualsEtc(document.forms[0].deliveryEmail.value);
		document.forms[0].saveCode.value = plusEqualsEtc2(document.forms[0].saveCode.value);
		document.forms[0].anyComments.value = plusEqualsEtc2(document.forms[0].anyComments.value);
		document.forms[0].action = "http://www.callthefarmer.co.uk/cgi-bin/a_prelloydsbank.pl";
		document.forms[0].submit();
	}
}






cookiesJsLoadedYet = "yes";



//// END A_PRELLOYDS /////
