function validateLoginForm(f) {

	if (f.username.value == '' || f.password.value == '') {
		alert("Please enter your username and password.");
		if (f.username.value == '') {
			f.username.focus();
		} else {
			f.password.focus();
		}
		return false;
	}

	f.submit();

	return false;
}

function submitLogin(f) {
	if (f.username.value == '' || f.password.value == '') {
		alert("Please enter your username and password to login.");
	} else {
		f.formAction.value = 'doLogin';
		f.action = '/login.php';
		f.submit();
	}
}

function updatePasswordField(e) {
	if (e.name == 'passwordDummy') {
		e.style.display = 'none';
		e.form.password.style.display = '';
		e.form.password.value = '';
		e.form.password.focus();
	} else if (e.name == 'password' && e.value == '') {
		e.style.display = 'none';
		e.form.passwordDummy.style.display = '';
	} else {
		return false;
	}
}

function validateChangePassword(f) {
	if (f.currentPassword.value == '' || f.newPassword.value == '' || f.newPassword2.value == '') {
		alert("Please complete all fields.");
		return false;
	}

	if (f.newPassword.value != f.newPassword2.value) {
		alert("New password & confirmation value do not match. Please check.");
		return false;
	} else if (f.newPassword.value.length < 5) {
		alert("Your password must be at least 5 characters long.");
		return false;
	}

	f.submit();
	return true;
}

function numeralsOnly(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}
	return true;
}

function addLoadEvent(func) {
	var oldOnLoad = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldOnLoad();
			func();
		}
	}
}

function updateProductPricing(f) {
	var r = f.productTypeSelect;
	for (var i = 0; i < r.length; i++) {
		if (r[i].checked) {
			document.getElementById('salePriceHolder').innerHTML = r[i].getAttribute('salePrice');
			document.getElementById('retailPriceHolder').innerHTML = r[i].getAttribute('retailPrice');
		}
	}
}

function editShoppingBasket() {
	$('checkoutForm').formAction.value = 'editBasket';
	$('checkoutForm').submit();
	return false;
}

function removeBasketItem(id) {
	if (confirm('Are you sure you want to remove this item from your shopping basket?')) {
		$('itemQuantity_' + id).value = 0;
		updateShoppingBasket();
	}
}

function proceedToCheckout() {
	$('shoppingBasketForm').formAction.value = 'checkout';
	$('shoppingBasketForm').submit();
	return false;
}

function validateCheckoutForm(f) {
	
	if ($('checkoutForm').deliverToBilling.checked) {
		var requiredFields = new Array("billEmail", "billFirstName", "billLastName",
			"billAddr1", "billAddr3", "billPostCode", "billTelephone", "CardNumber", 
			"CardType", "CardHolder", "CV2", "ExpiryDateMonth", "ExpiryDateYear");	
	} else {
		var requiredFields = new Array("billEmail", "billFirstName", "billLastName",
			"billAddr1", "billAddr3", "billPostCode", "billTelephone", "shipEmail", "shipFirstName", "shipLastName",
			"shipAddr1", "shipAddr3", "shipPostCode", "shipTelephone", "CardNumber", 
			"CardType", "CardHolder", "CV2", "ExpiryDateMonth", "ExpiryDateYear");
	}
		
	if ($('billCountry').getValue() == 'US') {
		requiredFields[requiredFields.length] = 'billAddr4';
	}
	if ($('shipCountry').getValue() == 'US') {
		if ($('deliverToBilling').checked) {
			
		} else {
			requiredFields[requiredFields.length] = 'shipAddr4';
		}
	}
	
	var v = new wizbitFormValidator(f);
	v.errorClass = 'borderError';
	v.standardClass = 'border';
	v.validate(requiredFields);
	if (!v.formIsValid) {
		alert("Please correct the highlighted fields.");
		return false;
	}
	
	if (!f.tcAccept.checked) {
		alert("Please tick the box to confirm you have read and accepted our terms and conditions.");
		return false;
	}
	
	f.formAction.value = 'processPayment';
	f.submitButton.value = 'Please Wait...';
	f.submitButton.disabled = true;
	f.submit();
}

function updateCheckoutAddress4(quiet) {
	var shipCountry = $('shipCountry').getValue();
	var billCountry = $('billCountry').getValue();
	
	if (billCountry == 'US') {
		$('billAddr4').style.width = '30px';
		$('billAddr4').maxLength = 2;
		if ($('billAddr4').getValue().length > 2) {
			$('billAddr4').value = '';
			alert("Please ensure you enter your 2 character state abbreviation in the 'County/State' field.");
		}
	} else {
		$('billAddr4').style.width = '200px';
		$('billAddr4').maxLength = 50;
	}
	
	if (shipCountry == 'US' || (billCountry == 'US' && $('deliveryToBilling').checked)) {
		$('shipAddr4').style.width = '30px';
		$('shipAddr4').maxLength = 2;
		if ($('shipAddr4').getValue().length > 2) {
			$('shipAddr4').value = '';
			alert("Please ensure you enter your 2 character state abbreviation in the 'County/State' field.");
		}
	} else {
		$('shipAddr4').style.width = '200px';
		$('shipAddr4').maxLength = 50;
	}
}

function updateCheckoutCountry() {
	$('checkoutForm').formAction.value = 'updateCheckout';
	$('checkoutForm').submit();
}

function setUKDeliveryAddress() {
	$('shoppingBasketForm').formAction.value = 'setUKDelivery';
	$('shoppingBasketForm').submit();
	return false;
}

function setDeliveryOption(s) {
	var url = '/checkout?formAction=setDeliveryOption&id=';
	url += s.options[s.selectedIndex].value;
	document.location.href = url;
}

function saveRefreshCheckout(f) {
	f.formAction.value = 'saveData';
	f.submit();
}

function setDeliverToBilling() {
	var f = $('checkoutForm');
	if (f.deliverToBilling.checked) {
		new Effect.SlideUp('deliveryDetailsTable');	
	} else {
		new Effect.SlideDown('deliveryDetailsTable');
	}
	if ($('billCountry').getValue() != $('shipCountry').getValue()) {
		updateCheckoutCountry();
	}
}

function validateRegistrationForm(f) {
	var errorState = 0;
	var requiredFields = new Array("userEmail", "userFirstName", "userLastName", "password1", "password2");
		
	var v = new wizbitFormValidator(f);
	v.errorClass = 'borderError';
	v.standardClass = 'border';
	v.validate(requiredFields);
	if (!v.formIsValid) {
		alert("Please correct the highlighted fields.");
		return false;
	}

	if (f.password1.value != f.password2.value) {
		alert("Your password entries do not match!");
		return false;
	} else if (f.password1.value.length < 4) {
		alert("Please ensure your password is at least 4 characters long.");
		return false;
	}
	
	f.formAction.value = 'processRegistration';
	f.submit();
}

function validateUserData(f) {
	var errorState = 0;
	var requiredFields = new Array("userEmail", "userFirstName", "userLastName",
		"userAddr1", "userAddr3", "userPostCode");
	
	var v = new wizbitFormValidator(f);
	v.errorClass = 'borderError';
	v.standardClass = 'border';
	v.validate(requiredFields);
	
	if (!v.formIsValid) {
		alert("Please complete the highlighted fields.");
		return false;
	}
	
	f.formAction.value = 'updateUserData';
	f.submit();
}

function validateChangePassword(f) {
	if (f.currentPassword.value == '' || f.newPassword.value == '' || f.newPassword2.value == '') {
		alert("Please complete all fields.");
		return false;
	}

	if (f.newPassword.value != f.newPassword2.value) {
		alert("New password & confirmation value do not match. Please check.");
		return false;
	} else if (f.newPassword.value.length < 5) {
		alert("Your password must be at least 5 characters long.");
		return false;
	}

	f.submit();
	return true;
}

function addProductToCart(f) {
	if (!f.productTypeSelect) {
		alert("This product is currently unavailable.");
		return false;
	}
	
	var found = false;
	
	if (f.productTypeSelect.length) {
		for (var i = 0; i < f.productTypeSelect.length; i++) {
			if (f.productTypeSelect[i].checked) {
				found = true;
			}
		}
	} else {
		if (f.productTypeSelect.checked) found = true;
	}
	
	if (!found) {
		alert("Please select a product option to continue.");
		return false;
	}
	
	if (f.itemQuantity.value == '' || f.itemQuantity.value < 1 || isNaN(f.itemQuantity.value)) {
		alert("Please enter a numerical quantity between 1 and 50.");
		return false;
	} else if (f.itemQuantity.value > 50) {
		alert("Please contact us to order more than 50 items.");
		return false;
	}
	
	f.formAction.value = 'addToCart';
	f.submit();
}

function deleteBasketItem(id) {
	if (!document.getElementById('basketQty_' + id) || !document.getElementById('shoppingBasketForm')) {
		alert("Sorry, an error occurred.\n\nPlease try refreshing the page.");
		return false;
	}
	
	document.getElementById('basketQty_' + id).value = 0;
	var f = document.getElementById('shoppingBasketForm');
	f.formAction.value = 'updateBasket';
	
	f.submit();
}

function updateShoppingBasket() {
	var f = $('shoppingBasketForm');
	
	if (!f) {
		alert("Sorry, an error occurred.\n\nPlease try refreshing the page.");
		return false;
	}
	
	f.formAction.value = 'updateBasket';
	f.submit();
	
	return false;
}

function switchProductImage(imageID, type, width, height) {
	var im = document.getElementById('mainProductImage');
	if (!im) return false;
	
	if (!type) var type = 'productImageID';
	if (!height) var height = 280;
	if (!width) var width = 210;
	
	var src = '/getImage?' + type + '=' + imageID + '&width=' + width + '&height=' + height;
	
	im.setAttribute('src', src);
	im.setAttribute('imageID', imageID);
	im.onclick = function(){viewLargeImage(type, imageID);};
}

function viewLargeImage(type, imageID) {
	var opt = 'status=no,scrollbars=no,resizable=yes,width=640,height=680,left=0,top=0';
	if (typeof imgWin != 'undefined') {
	    imgWin.close();
	}
	imgWin = window.open('', 'imgWin', opt);
	imgWin.document.write('<html><head><title>Product Image</title></head><body ');
	imgWin.document.write('style="background-color: #f1f0f5; border: 0px; margin: 0px;"><div ');
	imgWin.document.write('style="width: 100%; height: 100%; text-align: center; vertical-align: middle;">');
	imgWin.document.write('<img onmousedown="window.close();" src="/getImage?' + type + '=' + imageID + '&width=600" ');
	imgWin.document.write('alt="Product Image" /></div></body></html>');
}

function selectProductOption(s) {
	var opt = s.options[s.selectedIndex];
	var price = opt.getAttribute('optionPrice');
	var retailPrice = opt.getAttribute('optionRetailPrice');
	var salePrice = opt.getAttribute('optionSalePrice');
	
	if (!price) {
	    alert("Sorry, an error occurred. Please try refreshing the page.");
	    return false;
	}
	
	$('productOptionPrice').innerHTML = price;
		
	var upperPrice = price;
	var lowerPrice = price;
	
	$('retailPriceRow').style.display = 'none';
	if (retailPrice && retailPrice > 0) {
		if (retailPrice > price) {
			$('retailPriceRow').style.display = 'table-row';
		}
		$('retailPriceAmount').innerHTML = innerHTML = parseFloat(retailPrice).toFixed(2, 10);
		upperPrice = retailPrice;
	}
	if (salePrice && salePrice > 0) { 
		$('offerPriceRow').style.display = 'table-row';
		$('productSalePrice').innerHTML = innerHTML = parseFloat(salePrice).toFixed(2, 10);
		$('productOptionPrice').style.textDecoration = "line-through";
		lowerPrice = salePrice;
	}
	
	var saving = upperPrice - lowerPrice;
	
		if (saving > 0) {
			$('productSavingsAmount').innerHTML = parseFloat(saving).toFixed(2, 10);
			$('savingsRow').style.display = 'table-row';
		} else {
			$('productSavingsAmount').innerHTML = '';
			$('savingsRow').style.display = 'none';
		}
}

function validateVoucher() {
    if (!$('voucherCode')) {
        alert("Something has gone wrong. Please try refreshing the page.");
    } else if ($('voucherCode').getValue() == '') {
        alert("Please enter your voucher code.");
    } else {
        $('checkoutForm').formAction.value = 'validateVoucher';
        $('checkoutForm').submit();
    }
}

function showMainProductImage(productID, caption) {
	
	$('productImage').src = '/getImage/' + productID + '?width=340&height=340';
	pbSrc['productImage'] = new Image();
	pbSrc['productImage'].src = '/getImage/' + productID + '?width=500&height=500';
	
	if (!caption) {
		var caption = '';
	}
	
	$('productImage').setAttribute('pbCaption', caption);
}

function showAdditionalImage(id, caption) {
	if (!id) return false;
	
	$('productImage').src = '/getImage?productImageID=' + id + '&width=340&height=340';
	
	pbSrc['productImage'] = new Image();
	pbSrc['productImage'].src = '/getImage?productImageID=' + id + '&width=500&height=500';
	
	if (!caption) {
		var caption = '';
	}
	
	$('productImage').setAttribute('pbCaption', caption);
}

/**
 * Form validation functions
 *
 **/

wizbitFormValidator = function(f) {
	this.form = f;
}

wizbitFormValidator.prototype.form = null;
wizbitFormValidator.prototype.formIsValid = true;
wizbitFormValidator.prototype.highlightErrors = true;
wizbitFormValidator.prototype.errorClass = 'adminFormError';
wizbitFormValidator.prototype.standardClass = 'adminForm';

wizbitFormValidator.prototype.validate = function(req) {
	for (var i = 0; i < req.length; i++) {
		if (!this.form.elements[req[i]]) {
			alert('Field ' + req[i] + ' not found!');
			this.formIsValid = false;
			return false;
		}
		with (this.form.elements[req[i]]) {
			if (this.highlightErrors) {
				className = this.standardClass;
			}
			switch (tagName) {
				case 'INPUT':
					switch (type) {
						case 'text':
						case 'password':
							if (value == '') {
								this.formIsValid = false;
								if (this.highlightErrors) {
									className = this.errorClass;
								}
							}
							break;
					}
					break;
				case 'TEXTAREA':
					if (value == '') {
						this.formIsValid = false;
						if (this.highlightErrors) {
							className = this.errorClass;
						}
					}
					break;
				case 'SELECT':
					if (multiple) {
						var madeSelection = false;
						for (var j = 0; j < options.length; j++) {
							if (options[j].selected) {
								madeSelection = true;
							}
						}
						if (!madeSelection) {
							this.formIsValid = false;
							if (this.highlightErrors) {
								className = this.errorClass;
							}
						}
					} else {
						if (options[selectedIndex].value == '') {
							this.formIsValid = false;
							if (this.highlightErrors) {
								className = this.errorClass;
							}
						}
					}
					break;	
			}
		}
	}
}

