// Functions for Shop Front End
// Version 1.3 - Includes Voucher Code Validation

function stopRKey(evt) {	//Stop user pressing Enter - prevents form submission on press of Enter key
   var evt = (evt) ? evt : ((event) ? event : null);
   var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
   if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}



function showSubCategories(catId) {
	//Shows/Hides any Sub Categories on the category navigation
	var subCatRows = document.getElementsByTagName("ul");
	var matchString = "cat_" + catId + "_";	//Include Category and subcategory if appropriate
	var folderName = "folder_"  + catId;
	for(i=0; i<subCatRows.length; i++){ 
		if(subCatRows[i].id.substr(0,matchString.length) == matchString) {	//Check if start of ul id matches folder clicked
			if(document.getElementById(subCatRows[i].id).style.display=="none") {
				if(subCatRows[i].id.indexOf("p_")<0 || subCatRows[i].id.substr(0,matchString.length+2) == matchString+"p_") {	//Don't display product rows for SUB Categories
					document.getElementById(subCatRows[i].id).style.display="";
					//document.getElementById(folderName).src="../images/icons/folder_closeme.gif";
				}
			} else {
				document.getElementById(subCatRows[i].id).style.display="none";
				//document.getElementById(folderName).src="../images/icons/folder_openme.gif";
			}
		}
	}
}





//Functions for Product Info Page

function validateOrderLevel(intQuantity)	{
	var minOrderLevel = parseInt(document.getElementById("minorderlevel").value);
	var maxOrderLevel = parseInt(document.getElementById("maxorderlevel").value);
	var intStockLevel = parseInt(document.getElementById("productstocklevel").value);

	if(intQuantity==null || intQuantity=="") {
		document.getElementById("quantity").value = minOrderLevel;
		return false;
	}
	
	if(intQuantity<minOrderLevel) {
		alert("Please Note: the minimum order level for this product is " + minOrderLevel + " unit" + (minOrderLevel>1?"s.":"."));
		document.getElementById("quantity").value = minOrderLevel;
		return false;
	}

	if(intQuantity>maxOrderLevel && maxOrderLevel>0) {
		alert("Please Note: the maximum order level for this product is " + maxOrderLevel + (maxOrderLevel>1?"s.":"."));
		document.getElementById("quantity").value = maxOrderLevel;
		return false;
	}
	
	if(intQuantity>intStockLevel) {
		if(intStockLevel == 0) {
			alert("Sorry, this item is currently out of stock. Please call us and we can advise you when it will be available again.");
		} else {
			alert("Sorry, we only have " + intStockLevel + " of this item in stock at the moment.");
		}
		document.getElementById("quantity").value = intStockLevel;
		return false;
	}
	
	return true;
	
}


function recalculateCost()	{
	// id|+x=|cost|+x=|weight|description
	var allOptions = document.getElementsByTagName("select");	//All Drop Downs (DDs)
	var standardPrice = document.getElementById("standardprice").value;
	var quantity = document.getElementById("quantity").value;
	var standardWeight = document.getElementById("productweight").value;
	var totalPrice = standardPrice;
	var totalWeight = standardWeight;
	var attribsSelected = "";
	for (ixDDs=0; ixDDs<allOptions.length; ixDDs++){ 
		var newPrice = totalPrice;	
		if(allOptions[ixDDs].className=="productAttributeValues") {
			var newPrice = totalPrice;	
			var newWeight = totalWeight;
			var strDDValue = allOptions[ixDDs].value;
			//var attribsSelected = attribsSelected + (attribsSelected?"_":"") + strDDValue;
			if(strDDValue!="") {
				arrAttribParts = new Array();
				arrAttribParts = strDDValue.split("|");
				//Check for change in price
				intAttribId = arrAttribParts[0];
				if(arrAttribParts[2]==0) {/*No change in price*/}
				else if(arrAttribParts[1]=="+") {newPrice=eval(newPrice)+eval(arrAttribParts[2]);}
				else if(arrAttribParts[1]=="x") {newPrice=newPrice*eval(arrAttribParts[2]);}
				else if(arrAttribParts[1]=="=") {newPrice=eval(arrAttribParts[2]);}
				else {alert(arrAttribParts[1] +  " not recognised in recalculateCost()");}
				newPrice = show2dp(newPrice);
				totalPrice = newPrice;
				
				//Check for change in weight
				if(arrAttribParts[4]==0) {/*No change in weight*/}
				else if(arrAttribParts[3]=="+") {newWeight=eval(newWeight)+eval(arrAttribParts[4]);}
				else if(arrAttribParts[3]=="x") {newWeight=newWeight*eval(arrAttribParts[4]);}
				else if(arrAttribParts[3]=="=") {newWeight=eval(arrAttribParts[4]);}
				else {alert(arrAttribParts[1] +  " not recognised in recalculateCost()");}
				newWeight = show2dp(newWeight);
				totalWeight = newWeight;
				
				attribsSelected = attribsSelected + (attribsSelected?"_":"") + intAttribId;
			}
			
			document.getElementById("totalprice").value = newPrice;
			document.getElementById("totalweight").value = newWeight;
		}
	}
	
	totalPrice = totalPrice * quantity;
	totalPrice = show2dp(totalPrice);
	totalWeight = totalWeight * quantity;
	totalWeight = show2dp(totalWeight);
	document.getElementById("totalprice").value = totalPrice;
	document.getElementById("totalPriceDisplay").innerHTML = totalPrice;
	document.getElementById("totalweight").value = totalWeight;
	//alert(totalPrice);
	if(arrStockLevels[attribsSelected]>=0) {
		//alert(arrStockLevels[attribsSelected]);
		if(arrStockLevels[attribsSelected]==0) {
			alert("Sorry, this option is currently out of stock. Please call us and we can advise you when it will be available again.");
			//document.getElementById('quantity').value = 0;
		}
		document.getElementById('productstocklevel').value = arrStockLevels[attribsSelected];
	}
}

function validateAddToCart()	{
	if(validateOrderLevel(document.getElementById("quantity").value)==false) {return false;}
	recalculateCost();
	var allOptions = document.getElementsByTagName("select");
	for (i=0; i<allOptions.length; i++){ 
		if(allOptions[i].value=="") {
			alert("Please select an option for '" + allOptions[i].title + "'");
			allOptions[i].focus();
			return false;
		}
	}
	
	if(parseInt(document.getElementById("quantity").value)==0) {
		alert("Please enter the quantity");
		document.getElementById("quantity").focus();
		return false;
	}

	return true;
}


// Shopping Cart Page //
// ------------------ //
function validateVoucher(bolNotify)	{	//Requires md5.js to be present
	document.getElementById("vouchercode").value = document.getElementById("vouchercode").value.toUpperCase();
	var strVoucher = document.getElementById("vouchercode").value;
	strVoucher = md5(strVoucher.toUpperCase());
	var curStdCost = document.getElementById("cartItemsTotal").value;
	var curPostCost = document.getElementById("cartPostageCost").value;
	//var intNumLetters = document.getElementById("numletters").value;
	var bolIsValid = 0;
	var curDiscountValue = 0;
	var vMinSpend = 0;

	if(document.getElementById("vouchercode").value=="") {	//If no Voucher Code, use standard prices
		document.getElementById("cartVoucherCodeLine").style.display="none";	//Hide discount row
		document.getElementById("cartTotal").innerHTML = show2dp(eval(curStdCost) + eval(curPostCost));	
		if(document.getElementById("btnShop")) {	//Not on confirmation page
			document.getElementById("btnShop").href="category.php?vc=n";
			document.getElementById("btnPay").href="customer_details.php?vc=n";
		}
		return true;
	}
	
	for(ixV=0;ixV<vouchers.length;ixV++)	{
		vInfo = vouchers[ixV].split("|");
		vName = vInfo[0];
		
		if(vName == strVoucher) {
			strVoucherDetails = vouchers[ixV];	//Store details of this voucher to save to database
			vDiscountPC = vInfo[1];
			vDiscountAmt = vInfo[2];
			vMinSpend = vInfo[3];

			if (eval(curStdCost)>=eval(vMinSpend)) {	//Only apply if greater thann or equal to minimum spend
				var bolIsValid = 1;
				if(vDiscountPC>0) {
					curDiscountValue = show2dp(curStdCost * (vDiscountPC / 100));
					curDiscountValue = show2dp(curDiscountValue);	//Showing Decimal Places sometimes doesn't work first time!
				} else if (vDiscountAmt > 0) {
					curDiscountValue = vDiscountAmt;
				}
			}
		}
	}
	
	if(bolIsValid) {
		var newTotal = show2dp(eval(curStdCost) - eval(curDiscountValue) + eval(curPostCost));
		document.getElementById("cartDiscountAmount").innerHTML = curDiscountValue;
		if(document.getElementById("voucherdiscount")) {document.getElementById("voucherdiscount").value=curDiscountValue;}
		if(document.getElementById("voucherdetails")) {document.getElementById("voucherdetails").value=strVoucherDetails;}
		document.getElementById("cartVoucherCodeLine").style.display="";	//Show discount row
		document.getElementById("cartTotal").innerHTML = newTotal;
		if(document.getElementById("btnPay")) {	//Not on confirmation page
			document.getElementById("btnShop").href="category.php?vc="+document.getElementById("vouchercode").value;
			document.getElementById("btnPay").href="customer_details.php?vc="+document.getElementById("vouchercode").value;
		}
		return true;
	} else {
		if(bolNotify) {	//Only alert if required
			if (eval(curStdCost)<eval(vMinSpend)) {
				alert("Sorry, the Voucher Code entered is subject to a minimum spend of " + currencySymbol + vMinSpend + " which has not been reached.");
			} else {
				alert("Sorry, the Voucher Code entered is not valid or has expired.");
			}
		}
		document.getElementById("vouchercode").value = "";
		if(document.getElementById("vouchercode_final")) {document.getElementById("vouchercode_final").value = "";}	//On Order Confirmation Page
		document.getElementById("cartVoucherCodeLine").style.display="none";	//Hide discount row
		//document.getElementById("cartSubTotal").innerHTML = show2dp(curStdCost);		
		document.getElementById("cartTotal").innerHTML = show2dp(eval(curStdCost) + eval(curPostCost));
		document.getElementById("vouchercode").focus();
		if(document.getElementById("btnPay")) {	//Not on confirmation page
			document.getElementById("btnShop").href="category.php?vc=n";
			document.getElementById("btnPay").href="customer_details.php?vc=n";
		}
		return false;
	}
}







// Customer Details Page //
// --------------------- //
function setBillingSameAsCustomer(bolIsSame) {
	if(	bolIsSame == true) {
		var fullName = document.getElementById("customertitle").value + " " + document.getElementById("customerfirstname").value + " " + document.getElementById("customerlastname").value;
		document.getElementById("payername").value = fullName;
		if(document.getElementById("companyname") && document.getElementById("payercompanyname")) {
			document.getElementById("payercompanyname").value = document.getElementById("companyname").value
		}
		document.getElementById("payeraddress1").value = document.getElementById("address1").value;
		document.getElementById("payeraddress2").value = document.getElementById("address2").value;
		document.getElementById("payeraddress3").value = document.getElementById("address3").value;
		document.getElementById("payeraddress4").value = document.getElementById("address4").value;
		document.getElementById("payercountry").value = document.getElementById("country").value;
		document.getElementById("payerpostcode").value = document.getElementById("postcode").value;
	}
}

function untickBillingSame() {
	document.getElementById("payerascustomer").checked=false;
}


function setDeliverySameAsCustomer(bolIsSame) {
	if(bolIsSame == true) {
		
		//Check Delivery Location OK
		var strDelCountry = document.getElementById("country").value;
		var strAllowedCountries = document.getElementById("candeliverto").value;
		document.getElementById("deliveryascustomer").disabled=false;
		document.getElementById("lblDelCountry").className="formLabel";
		
		if(strAllowedCountries.indexOf(strDelCountry) ==-1) {
			document.getElementById("deliveryascustomer").checked=false;
			document.getElementById("deliveryascustomer").disabled=true;
			document.getElementById("deliverycountry").value= "";
			document.getElementById("lblDelCountry").className="formLabel errorLabel";
			return false;
			//alert("Sorry, we are unable to deliver to your selected country at this time.");
			//return false;
		}

		
		
		var fullName = document.getElementById("customertitle").value + " " + document.getElementById("customerfirstname").value + " " + document.getElementById("customerlastname").value;
		document.getElementById("deliveryname").value = trimAll(fullName);	//trimAll in includes/generic_funcs.js
		if(document.getElementById("companyname") && document.getElementById("deliverycompanyname")) {
			document.getElementById("deliverycompanyname").value = document.getElementById("companyname").value
		}
		document.getElementById("deliveryaddress1").value = document.getElementById("address1").value;
		document.getElementById("deliveryaddress2").value = document.getElementById("address2").value;
		document.getElementById("deliveryaddress3").value = document.getElementById("address3").value;
		document.getElementById("deliveryaddress4").value = document.getElementById("address4").value;
		document.getElementById("deliverycountry").value = document.getElementById("country").value;
		document.getElementById("deliverypostcode").value = document.getElementById("postcode").value;
	}
}

function untickDeliverySame() {
	document.getElementById("deliveryascustomer").checked=false;
	document.getElementById("deliveryascustomer").disabled=false;
	document.getElementById("lblDelCountry").className="formLabel";	//Remove error formatting on delivery country if applicable
}


function checkUpdate()	{
	if(document.getElementById("payerascustomer").checked==true) {setBillingSameAsCustomer(true)}
	if(document.getElementById("deliveryascustomer").checked==true) {setDeliverySameAsCustomer(true)}
}


function validateOtherInput() {
	//Check passwords for NEW customers only
	if(parseInt(document.getElementById("customerurn").value)==0 || document.getElementById("password").value.length>0) {
		if(document.getElementById("password").value.length<6) {
			alert("Your password must contain at least 6 characters");	
			return false;
		}
		
		//Assumes Password and Confirmation password have been checked for values using form validator
		if(document.getElementById("password").value!=document.getElementById("password2").value) {
			alert("Your password and confirmation passwords do not match. Please re-enter them");
			document.getElementById("password").value="";
			document.getElementById("password").focus();
			document.getElementById("password2").value="";
			
			return false;			
		}
	}
		
	//Check Delivery Location OK
	var strDelCountry = document.getElementById("deliverycountry").value;
	var strAllowedCountries = document.getElementById("candeliverto").value;
	
	if(strAllowedCountries.indexOf(strDelCountry) ==-1) {
		alert("Sorry, we are unable to deliver to your selected country at this time.");
		document.getElementById("deliverycountry").value="GB";
		return false;
	}
	
	
	//Check Ts and Cs box ticked
	if(document.getElementById("tandcread").checked == false) {
		document.getElementById("tandcread").focus();
		alert("Please tick the box to state that you have read and understood our terms and conditions");
		return false;
	}

}
