/*
 +------------------------------------------------------------------------------+
 Project: Straightsell Standard Templates
 +------------------------------------------------------------------------------+
 COPYRIGHT 2007 - STRATEGIC ECOMMERCE
 +------------------------------------------------------------------------------+
 Description: documents/site.js
 Primary Javascript file.
 Functions are namespaced using "SEL" and functions are called using
 the syntax: SEL.functionName(params);
 +------------------------------------------------------------------------------+
 Author(s): Paul Johnson
 +------------------------------------------------------------------------------+
 */
var popUpWin = 0; // Initialise variable - used by the popUpWindow() function

var SEL = function() {
	return {

		// ===== General functions =====

		trim : function(s) {
			return s.replace(/^\s&#42;(\S&#42;(\s+\S+)&#42;)\s&#42;&#36;/,
					"&#36;1");
		},

		onlyNumbers : function(e) { // Allow only numbers to be entered into
									// text fields. Checks input as it is being
									// typed.
			var keynum;
			var keychar;
			var numcheck;

			if (window.event) // IE
			{
				keynum = e.keyCode;
			} else if (e.which) // Netscape/Firefox/Opera
			{
				keynum = e.which;
			}
			if (!keynum) {
				return true;
			}
			// alert(keynum);
			// if backspace - for firefox
			if (keynum == 8) {
				return true;
			}

			keychar = String.fromCharCode(keynum);

			if ((keychar >= "0") && (keychar <= "9")) {
				return true;
			} else {
				return false;
			}
		},

		popUpWindow : function(URLStr, left, top, width, height) {
			if (popUpWin) {
				if (!popUpWin.closed)
					popUpWin.close();
			}
			popUpWin = open(
					URLStr,
					'popUpWin',
					'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='
							+ width
							+ ',height='
							+ height
							+ ',left='
							+ left
							+ ', top='
							+ top
							+ ',screenX='
							+ left
							+ ',screenY='
							+ top + '');
		},

		// Contact, Registration, Request Info/Quote and Login forms.

		changeStates : function(form) { // Dynamically update the States entry
										// field based on the Country selected.
			var countryList = form.Country;
			var selectedCountry = countryList.options[countryList.selectedIndex].value;

			if (selectedCountry == "AU") {
				document.getElementById("StatesAU").style.display = "block";
				document.getElementById("StatesUS").style.display = "none";
				document.getElementById("StatesOther").style.display = "none";
			} else if (selectedCountry == "US") {
				document.getElementById("StatesAU").style.display = "none";
				document.getElementById("StatesUS").style.display = "block";
				document.getElementById("StatesOther").style.display = "none";
			} else {
				document.getElementById("StatesAU").style.display = "none";
				document.getElementById("StatesUS").style.display = "none";
				document.getElementById("StatesOther").style.display = "block";
			}
		},

		/*
		 * Contact Form validation. Also handles the Request Information and
		 * Request for Quote forms. Checks for a hidden field named "FormType"
		 * and sets the form introduction text and field data accordingly.
		 */
		checkContactForm : function() {
			var frm = document.getElementById("ContactForm");
			var vEmail = frm.ContactEmail.value;

			if (document.getElementById("StatesAU").style.display == "block") {
				var stateList = frm.StateAU;
				var selectedState = stateList.options[stateList.selectedIndex].value;
			} else if (document.getElementById("StatesUS").style.display == "block") {
				var stateList = frm.StateUS;
				var selectedState = stateList.options[stateList.selectedIndex].value;
			} else if (document.getElementById("StatesOther").style.display == "block") {
				var stateList = frm.StateOther;
				var selectedState = stateList.value;
			}

			if (SEL.trim(frm.ContactName.value) == "") {
				alert("Please enter a Contact Name.");
				frm.ContactName.focus();
				return false;
			} else if (SEL.trim(frm.ContactEmail.value) == "") {
				alert("Please enter an Email Address.");
				frm.ContactEmail.focus();
				return false;
			} else if ((SEL.trim(frm.ContactEmail.value) != "")
					&& (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
				alert("Please enter a valid Email Address (ie yourname@yourdomain.com)");
				frm.ContactEmail.focus();
				return false;
			} else {

				frm.State.value = selectedState;
				newline = "\n";
				space = " ";

				if (frm.FormType.value == "prodInfo") { // Request for Information
					var eContent = "A Request for Information Form has been submitted through your StraightSell website. Here are the details:"
							+ newline + newline;
					eContent += "Requested Product:" + space
							+ frm.TheProduct.value + newline + newline;
				} else if (frm.FormType.value == "prodQuote") { // Request for Quote
					var eContent = "A Request Quote has been submitted through your StraightSell website. Here are the details:"
							+ newline + newline;
					eContent += Products + newline;
					eContent += "==========================================================\n";
				} else { // Standard Contact
					var eContent = "A Contact form has been submitted through your StraightSell website. Here are the details:"
							+ newline + newline;
				}

				eContent += "Contact Name:" + space + frm.ContactName.value
						+ newline;
				eContent += "Email Address:" + space + frm.ContactEmail.value
						+ newline + newline;
				eContent += "Phone Number:" + space + frm.ContactPhone.value
						+ newline;
				eContent += "Address:" + space + frm.Address1.value + newline;
				eContent += "Address2:" + space + frm.Address2.value + newline;
				eContent += "City:" + space + frm.City.value + newline;
				eContent += "State:" + space + frm.State.value + newline;
				eContent += "Country:" + space
						+ frm.Country.options[frm.Country.selectedIndex].text
						+ newline;
				eContent += "Postcode:" + space + frm.Postcode.value + newline;
				if (frm.Comments.value == "Comments/Feedback") {
					frm.Comments.value = "";
				}
				eContent += "Comments:" + space + frm.Comments.value + newline;

				frm.EmailContent.value = eContent;
				frm.captcha.value = frm.captcha.value.toUpperCase();
				return true;
			}
		},

		checkRegForm : function() { // Registration Form validation.
			var frm = document.getElementById("AddUserForm");
			var vEmail = frm.AdminEmail.value;
			var vContactSource = frm.contactsource;
			var selectedContactSource = vContactSource.options[vContactSource.selectedIndex].value;

			if (document.getElementById("StatesAU").style.display == "block") {
				var stateList = frm.StateAU;
				var selectedState = stateList.options[stateList.selectedIndex].value;
			} else if (document.getElementById("StatesUS").style.display == "block") {
				var stateList = frm.StateUS;
				var selectedState = stateList.options[stateList.selectedIndex].value;
			} else if (document.getElementById("StatesOther").style.display == "block") {
				var stateList = frm.StateOther;
				var selectedState = stateList.value;
			}

			if (SEL.trim(frm.BuyerName.value) == "") {
				alert("Please enter a Company Name.");
				frm.BuyerName.focus();
				return false;
			} else if (SEL.trim(frm.AdminName.value) == "") {
				alert("Please enter your Full Name.");
				frm.AdminName.focus();
				return false;
			} else if (SEL.trim(frm.AdminEmail.value) == "") {
				alert("Please enter an Email Address.");
				frm.AdminEmail.focus();
				return false;
			} else if ((SEL.trim(frm.AdminEmail.value) != "")
					&& (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
				alert("Please enter a valid Email Address (ie yourname@yourdomain.com)");
				frm.AdminEmail.focus();
				return false;
			} else if (SEL.trim(frm.PostCode.value) == "") {
				alert("Please enter your PostCode.");
				frm.PostCode.focus();
				return false;
			} else if (SEL.trim(selectedState) == "") {
				alert("Please enter your State.");
				stateList.focus();
				return false;
			} else if (SEL.trim(frm.AdminPhone.value) == "") {
				alert("Please enter your Phone Number.");
				frm.AdminPhone.focus();
				return false;
			} else if (SEL.trim(frm.AdminUserName.value) == "") {
				alert("Please enter a Username.");
				frm.AdminUserName.focus();
				return false;
			} else if (frm.AdminPassword.value == "") {
				alert("Please enter a Password!");
				frm.AdminPassword.focus();
				return false;
			} else if (frm.RetypeAdminPassword.value == ""
					|| frm.AdminPassword.value != frm.RetypeAdminPassword.value) {
				alert("Password Mismatch - Please repeat the Password.");
				frm.AdminPassword.focus();
				return false;
			} else {
				frm.State.value = selectedState;
				frm.ContactSourceSelected.value = selectedContactSource;
				frm.captcha.value = frm.captcha.value.toUpperCase();
				return true;
			}
		},

		checkLoginForm : function(frm) { // Login Form validation
			if (frm.UserName.value == "" || frm.UserName.value == "Username") {
				alert("Please enter a UserName");
				frm.UserName.focus();
				return false;
			}
			if (frm.Password.value == "" || frm.Password.value == "Password") {
				alert("Please enter a Password.");
				frm.Password.focus();
				return false;
			}
			return true;
		},
		
		// Newsletter Signup Page (Signup "Panel" check below)
		checkSignup: function(){
        	var frm = document.getElementById("newsletterSignupForm");
        	var vEmail = frm.DefaultEmail.value;
        	var countryList = frm.Country;
            var selectedCountry = countryList.options[countryList.selectedIndex].value;
            var titleList = frm.Salutation;
            var selectedTitle = titleList.options[titleList.selectedIndex].value;
            
            if (selectedTitle == "") {
                alert("Please select a Title.");
                frm.Salutation.focus();
                return false;
            }
            if (frm.FirstName.value == "") {
                alert("Please enter your First Name");
                frm.FirstName.focus();
                return false;
            }
            if (frm.LastName.value == "") {
                alert("Please enter your Surname.");
                frm.LastName.focus();
                return false;
            }
            if (frm.DefaultEmail.value == "") {
                alert("Please enter an Email Address.");
                frm.DefaultEmail.focus();
                return false;
            }
        	if ((frm.DefaultEmail.value != "") && (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
                alert("Please enter a valid Email Address.");
                frm.DefaultEmail.focus();
                return false;
            }
    		if (selectedCountry == "") {
                alert("Please select a Country.");
                frm.Country.focus();
                return false;
            }
        	frm.elements["EmailAddressTo[0]"].value = frm.DefaultEmail.value;
            return true;
        },
        
        checkSignupPanel: function(){ // Newsletter Signup Panel
        	var frm = document.getElementById("newsletterSignupForm");
        	var vEmail = frm.DefaultEmail.value;
        	var countryList = frm.Country;
            var selectedCountry = countryList.options[countryList.selectedIndex].value;
            var titleList = frm.Salutation;
            var selectedTitle = titleList.options[titleList.selectedIndex].value;
            
            if (selectedTitle == "") {
                alert("Please select a Title.");
                frm.Salutation.focus();
                return false;
            }
            if (frm.FirstName.value == "" || frm.FirstName.value == "First Name") {
                alert("Please enter your First Name");
                frm.FirstName.focus();
                return false;
            }
            if (frm.LastName.value == "" || frm.LastName.value == "Last Name") {
                alert("Please enter your Last Name.");
                frm.LastName.focus();
                return false;
            }
            if (frm.DefaultEmail.value == "" || frm.DefaultEmail.value == "Email Address") {
                alert("Please enter an Email Address.");
                frm.DefaultEmail.focus();
                return false;
            }
        	if ((frm.DefaultEmail.value != "" && frm.DefaultEmail.value != "Email Address") && (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
                alert("Please enter a valid Email Address.");
                frm.DefaultEmail.focus();
                return false;
            }
    		if (selectedCountry == "") {
                alert("Please select a Country.");
                frm.Country.focus();
                return false;
            }
        	frm.elements["EmailAddressTo[0]"].value = frm.DefaultEmail.value;
            return true;
        },

		// Product List, Product Detail and Search functions

		checkSimpleSearch : function(frm, vURL) {
			if (frm.searchfilter.value == ""
					|| frm.searchfilter.value == "Search Products") {
				alert("Please enter a search term");
				frm.searchfilter.focus();
				frm.searchfilter.select();
				return false;
			}

			searchValue = frm.searchfilter.value;
			searchValue = searchValue.replace(/=/g, "_equals_");
			searchValue = searchValue.replace(/\//g, "_or_");
			searchValue = searchValue.replace(/&/g, "_and_");
			searchValue = searchValue.replace(/-/g, "_dash_");
			searchValue = searchValue.replace(/ /g, "-");
			searchValue = SEL.URLEncode(searchValue);

			location.href = vURL + searchValue + "/sf/pl.php?resetbrand=1";
			return false;
		},
		
		checkBrandSearch: function() {
			var frm = document.getElementById("BrandSearch");
			if(frm.brandfilter.value == "") {
				alert("Please select a Brand");
				frm.brandfilter.focus();
				return false;
			}
			return true;
		},
		checkSortBy: function() {
			var frm = document.getElementById("sortbyform");
			if(frm.sortbyfilter.value == "") {
				alert("Please select a value to sort by");
				frm.sortbyfilter.focus();
				return false;
			}
			frm.submit();
			return true;
		},

		URLEncode : function(clearString) {
			var output = '';
			var x = 0;
			clearString = clearString.toString();
			var regex = /(^[a-zA-Z0-9_.]*)/;

			while (x < clearString.length) {
				var match = regex.exec(clearString.substr(x));
				if (match != null && match.length > 1 && match[1] != '') {
					output += match[1];
					x += match[1].length;
				} else {
					if (clearString[x] == ' ')
						output += '+';
					else {
						var charCode = clearString.charCodeAt(x);
						var hexVal = charCode.toString(16);
						output += '%' + (hexVal.length < 2 ? '0' : '')
								+ hexVal.toUpperCase();
					}
					x++;
				}
			}
			return output;
		},

		paymentViewCart : function(vVHN) {
			if (confirm("Viewing or modifying your cart now will return you to the start of the order process.\n\nContinue?")) {
				window.location.href = vVHN
						+ "payments/pages/purchase_pages.php?ResetDeliveryAddress=1&Operation[0]=SetSessionVariable&Variable[ShowFullCart]=1";
			}
		},

		showFullCart: function(vVHN){ // Function to show/hide full cart
			if ($("#ajaxFullCart").css("display") == "none") {
				$.get( vVHN + 'product_list/widgets/ajax_show_fullcart.php?Operation[0]=SetSessionVariable&Variable[ShowFullCart]=1', function() {
					$("#ajaxFullCart").slideDown(500);
				});
			} else if ($("#ajaxFullCart").css("display") != "none") {
				$.get( vVHN + 'product_list/widgets/ajax_show_fullcart.php?Operation[0]=SetSessionVariable&Variable[ShowFullCart]=0', function() {
					$("#ajaxFullCart").slideUp(500);
				});
			}
		},
		
		setProductListStyle: function(vStyle) {
			var vURL = window.location.href;
			if (vURL.indexOf("?") != -1) { //URL has parameters
				var vURLArray = vURL.split('?');
				var vURL = vURLArray[0]; //URL without parameters
			}
			window.location.href = vURL + "?Operation[0]=SetSessionVariable&Variable[plStyle]=" + vStyle;
			return true;
		},
		
		updateOptionStockMsgPL: function(vProdNum,vProdCode,vCartFlag){ // Swap Stock Level and Price display based on selected Option
			var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vOptionSelect = "#productcodeSelect" + vProdNum;
			if(vProdCode != null) {
				var vSelectedOption = vProdCode;
				$(vOptionSelect).val(vProdCode);
			} else {
				var vSelectedOption = $(vOptionSelect).val();
			}
			if(vCartFlag == null) { // Skip this loop if refreshing after an Add to Cart
				var vStockMsgDiv = "#stockMessage_" + vProdNum;
				var vOptionCodeDiv = "#optionCode_" + vProdNum;
				var vOptionPriceDiv = "#optionPrice_" + vProdNum;
				var vOptionPriceCurrencyDiv = "#optionPriceCurrency_" + vProdNum; // For Currency Converter
				var vOptionPriceStockWrapper = "#optionPriceStockWrapper" + vProdNum;
				var vOptionPriceStockWrapperInner = "#optionPriceStockWrapperInner" + vProdNum;
				var vCartDiv = "#addToCartDiv" + vProdNum;
				var vProductPrintCodeDefaultDiv = "#productprintCodeDefault";
				var vProductPrintCodeOptionDiv = "#productprintCodeOption";
				var vProductPrintPriceDiv = "#productprintPrice";
				var vProductPrintSelectedDefaultDiv = "#productprintSelectedDefault";
				var vProductPrintSelectedOptionDiv = "#productprintSelectedOption";
				var vProductLinePriceWrapperDiv = "#productLinePriceWrapper" + vProdNum;

				if (vSelectedOption != "") {
					$(vOptionPriceStockWrapperInner).fadeIn(300, function() {
						var optionCodeField = "#optionCode_" + vProdNum + "_" + vSelectedOption;
						var optionSizeField = "#optionSize_" + vProdNum + "_" + vSelectedOption;
						var optionPriceField = "#optionPrice_" + vProdNum + "_" + vSelectedOption;
						var optionPriceCurrencyField = "#optionPriceCurrency_" + vProdNum + "_" + vSelectedOption;
						var optionStockLevelField = "#optionStockLevel_" + vProdNum + "_" + vSelectedOption;
						if ($(vProductLinePriceWrapperDiv).length) {
							$(vProductLinePriceWrapperDiv).css("display","block");
						}
						if ($(vOptionCodeDiv).length) {
							$(vOptionCodeDiv).html('<strong>Product Code:</strong><br />' + $(optionCodeField).val());
						}
						if ($(vProductLinePriceWrapperDiv).length) { // Remove Inc GST text for Line Style product list
							if ($(optionPriceField).val() == "Price On Application") {
								$(vOptionPriceDiv).html($(optionPriceField).val());
								$(vOptionPriceCurrencyDiv).html("&nbsp;");
							} else {
								$(vOptionPriceDiv).html($(optionPriceField).val());
								$(vOptionPriceCurrencyDiv).html($(optionPriceCurrencyField).val());
							}
						} else {
							if ($(optionPriceField).val() == "Price On Application") {
								$(vOptionPriceDiv).html($(optionPriceField).val());
								$(vOptionPriceCurrencyDiv).html("&nbsp;");
							} else {
								if ($("#pricesIncGST").val() == "1") {
									$(vOptionPriceDiv).html($(optionPriceField).val() + '<span class="productDetailPriceIncGST">(inc GST)</span>');
									if ($(optionPriceCurrencyField).val() != "") {
										$(vOptionPriceCurrencyDiv).html($(optionPriceCurrencyField).val() + '<span class="productDetailPriceCurrencyIncGST">(inc GST)</span>');
									} else {
										$(vOptionPriceCurrencyDiv).html("&nbsp;");
									}
								} else {
									$(vOptionPriceDiv).html($(optionPriceField).val() + '<span class="productDetailPriceExGST">(ex GST)</span>');
									if ($(optionPriceCurrencyField).val() != "") {
										$(vOptionPriceCurrencyDiv).html($(optionPriceCurrencyField).val() + '<span class="productDetailPriceCurrencyExGST">(ex GST)</span>');
									} else {
										$(vOptionPriceCurrencyDiv).html("&nbsp;");
									}
								}
							}
						}
						$(vStockMsgDiv).html($(optionStockLevelField).val());
						if ($(vStockMsgDiv).html().indexOf("In Stock") != -1) {
							$(vStockMsgDiv).attr("class","InStockMessage");
						} else {
							$(vStockMsgDiv).attr("class","OutOfStockMessage");
						}
						
						// Set the price, code and selected option for Print Product on detail page
						if ($(vProductPrintCodeDefaultDiv).length && vProdNum == "1") {
							$(vProductPrintCodeDefaultDiv).css("display","none");
							$(vProductPrintSelectedDefaultDiv).css("display","none");
							$(vProductPrintCodeOptionDiv).css("display","block");
							$(vProductPrintSelectedOptionDiv).css("display","block");
							$(vProductPrintCodeOptionDiv).html('<strong>Product Code:</strong> ' + $(optionCodeField).val());
							$(vProductPrintSelectedOptionDiv).html('<strong>Selected Option:</strong> ' + $(optionSizeField).val());
						}
						if ($(vProductPrintPriceDiv).length && vProdNum == "1") {
							if ($(optionPriceField).val() != "Price On Application") {
								$(vProductPrintPriceDiv).html('<strong>Price:</strong> $' + $(optionPriceField).val() + ' (inc GST)');
							} else {
								$(vProductPrintPriceDiv).html('<strong>Price:</strong> ' + $(optionPriceField).val());
							}
						}
						
						$(vOptionPriceStockWrapperInner).fadeOut(300, function() {
							if ($(optionPriceField).val() != "Price On Application") {
								if ($(vStockMsgDiv).html().indexOf("In Stock") == -1) {
									if ($(vStockMsgDiv).html() == "Out of Stock") {
										if ($(vCartDiv).css("display") == "none") {
											$(vCartDiv).fadeIn(300);
										}
									} else {
										if ($(vCartDiv).css("display") != "none") {
											$(vCartDiv).fadeOut(300);
										}
									}
								}
								else {
									if ($(vCartDiv).css("display") != "none") {
										$(vCartDiv).fadeOut(300);
									}
								}
							} else {
								if ($(vCartDiv).css("display") == "none") {
									$(vCartDiv).fadeIn(300);
								}
							}
						});
					});
				} else if(vSelectedOption == "") {
					$(vOptionPriceStockWrapperInner).fadeIn(300, function() {
						if ($(vOptionCodeDiv).length) {
							$(vOptionCodeDiv).html("&nbsp;");
						}
						$(vOptionPriceDiv).html("&nbsp;");
						$(vOptionPriceCurrencyDiv).html("&nbsp;");
						if ($(vProductLinePriceWrapperDiv).length) {
							$(vProductLinePriceWrapperDiv).css("display","none");
						}
						$(vStockMsgDiv).html("Please Select a Product");
						if ($(vProductLinePriceWrapperDiv).length) { // Change class for Line Style product list
							$(vStockMsgDiv).attr("class","InStockMessageLine");
						} else {
							$(vStockMsgDiv).attr("class","InStockMessage");
						}
						// Set the price, code and selected option for Print Product on detail page
						if ($(vProductPrintCodeDefaultDiv).length && vProdNum == "1") {
							$(vProductPrintCodeDefaultDiv).css("display","block");
							$(vProductPrintSelectedDefaultDiv).css("display","block");
							$(vProductPrintCodeOptionDiv).css("display","none");
							$(vProductPrintSelectedOptionDiv).css("display","none");
							$(vProductPrintCodeOptionDiv).html("&nbsp;");
							$(vProductPrintSelectedOptionDiv).html("&nbsp;");
						}
						if ($(vProductPrintPriceDiv).length && vProdNum == "1") {
							$(vProductPrintPriceDiv).html('<strong>Price:</strong> (No Option Selected)');
						}
						$(vOptionPriceStockWrapperInner).fadeOut(300, function() {
							if ($(vCartDiv).css("display") != "none") {
								$(vCartDiv).fadeOut(300);
							}
						});
					});
				}
			}
		},
		
		// Add to Cart validation - Product List
		checkAddToCartProductList: function(vProdCode,vProdNum,vVHN){ // Add to Cart validation - Product List
			var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vInfoDiv = "#addCartInfo_" + vProdNum;
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vQty = vForm.qty.value;
			var vOptionSelect = "#productcodeSelect" + vProdNum;
			var vVariantSelect = "#variant_" + vProdNum;
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
			
			if (vQty == "" || vQty <= 0) {
				alert("Please enter a Quantity greater than zero to add to cart.");
				return false;
			}
			
			if (vForm.isOptionSelect.value == "1" && $(vOptionSelect).val() == "") {
				alert("Please make a selection from the drop-down menu.");
				$(vOptionSelect).focus();
			} else {
				$(vInfoDiv).html(vAjaxLoadImg).show();
				if(vForm.isOptionSelect.value == "1") {
					var vSelectedOptionNameField = "#optionName_" + vProdNum + "_" + vForm.productcode.selectedIndex;
					var vSelectedOptionNameValue = $(vSelectedOptionNameField).val();
					var vSelectedProdCode = $(vOptionSelect).val();
					if ($(vVariantSelect).length) {
						vForm.productname.value = vSelectedOptionNameValue + " " + $(vVariantSelect).val();
					}
				} else {
					var vSelectedProdCode = "";
				}
				var vFormData = $(vForm).serialize();
				$("#ajaxSummaryCart").load(vSummaryCartURL, vFormData, function(response, status, xhr) {
					if (status == "error") {
						var msg = "Sorry but there was an error: ";
						$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
					} else {
						//vForm.reset();
						$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
							if (status == "error") {
								var msg = "Sorry but there was an error: ";
								$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
							} else {
								var htmlText = '<div id="addCartInfoContent">\n';
								htmlText += '<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n';
								htmlText += '<p>' + vQty + ' Item';
								if (vQty != "1") {
									htmlText += 's';
								}
								htmlText += '<br />\n<strong>Added to Cart!</strong></p></div>\n';
								
								$(vInfoDiv).html(htmlText);
								
								$(vInfoDiv).fadeOut(3000);
								//vForm.reset();
								SEL.updateOptionStockMsgPL(vProdNum,vSelectedProdCode,1);
								if ($('#ajaxFullCart').css("display") == "none") {
									SEL.showFullCart(vVHN);
								}
								if ($("#addToCartUIMessage").length) {
									alert($("#addToCartUIMessage").html());
								}
							}
						});
					}
				});
			}
		},
		
		// Add to Favourites validation - Product List
		checkRequestInfo: function(vProdCode,vProdNum,vVHN){ // Request Information validation - Product List
			var vForm = document.getElementById("AddToCartForm" + vProdNum);

			if (vForm.isOptionSelect.value == "1") {
				var vOptionSelect = vForm.productcode;
				if (vOptionSelect.options[vOptionSelect.selectedIndex].value == "") {
					alert("Please make a selection from the drop-down menu for " + document.getElementById('ProductName' + vProdCode).name);
					vForm.productcode.focus();
				}
				else {
					window.location.href = vVHN + "site/pages/request_information.php?ProductCodeID=" + vOptionSelect.options[vOptionSelect.selectedIndex].value;
				}
			}
			else {
				window.location.href = vVHN + "site/pages/request_information.php?ProductCodeID=" + vProdCode;
			}
		},
		
		// Add to Favourites validation - Product List
		checkAddToFavouritesProductList: function(vProdCode,vProdNum,vVHN){ // Add to Favourites validation - Product List
			var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vInfoDiv = "#favouriteInfo_" + vProdNum;
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			if (vForm.isOptionSelect.value == "1") {
				var vOptionSelect = vForm.productcode;
				if (vOptionSelect.options[vOptionSelect.selectedIndex].value == "") {
					alert("Please make a selection from the drop-down menu for " + document.getElementById('ProductName' + vProdCode).name);
					vForm.productcode.focus();
				}
				else {
					$(vInfoDiv).html(vAjaxLoadImg).show();
					var vFavWithOptionsURL = vVHN + 'product_list/widgets/ajax_add_favourite.php?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[' + encodeURIComponent(vOptionSelect.options[vOptionSelect.selectedIndex].value) + ']=' + encodeURIComponent(vOptionSelect.options[vOptionSelect.selectedIndex].value);
					
					$(vInfoDiv).load(vFavWithOptionsURL, function(response, status, xhr) {
    					if (status == "error") {
    						var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
    					} else {
    						$(vInfoDiv).fadeOut(3000);
    					}
    				});
				}
			}
			else {
				$(vInfoDiv).html(vAjaxLoadImg).show();
				var vFavNoOptionsURL = vVHN + 'product_list/widgets/ajax_add_favourite.php?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[' + encodeURIComponent(vProdCode) + ']=' + encodeURIComponent(vProdCode);
				
				$(vInfoDiv).load(vFavNoOptionsURL, function(response, status, xhr) {
					if (status == "error") {
						var msg = "Sorry but there was an error: ";
						$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
					} else {
						$(vInfoDiv).fadeOut(3000);
					}
				});
			}
		},

		// Shopping Cart functions

		creditCardRecalculateCart : function(vVHN) {
			if (confirm("Modifying your cart now will cancel the credit card order\nand return you to the start of the order process.\n\nContinue?")) {
				document.ShoppingCartForm.action = vVHN
						+ "payments/pages/purchase_pages.php?ResetDeliveryAddress=1";
				document.ShoppingCartForm.submit();
			}
		},
		
		checkProductCodeQuickOrder : function(vProdCode, vVHN) {
			var vForm = document.getElementById("QuickOrderForm");
			var vInfoDiv = "#enterCodeInfo";
			
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vFormData = $(vForm).serialize();
			
			var vQuickOrderURL = vVHN + 'admin/widgets/quick_order_form.php';
			
			$(vInfoDiv).html(vAjaxLoadImg).show();
			
			$('#qoOperation').attr("name","");
			$('#qoOperation').val("");
			vForm.productcode.value = "";
			vForm.productname.value = "";
			
			$.post(vQuickOrderURL, vFormData, function(response, status, xhr) {
				if (status == "error") {
					var msg = "Sorry but there was an error: ";
					$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
				} else {
					$("#QuickOrderFormWrapper").html(response);
					var oTextbox = new AutoSuggestControl(document.getElementById("qoProductCodeInput"), new ProductCodeSuggestions());
					if ($('#qoOperation').attr("name") == "") {
						$('#qoProductCodeInput').focus();
						$('#qoProductCodeInput').select();
					} else {
						if ($('#qoAddToCartSubmit').val() == "Try Again") {
							$('#qoAddToCartSubmit').focus();
							$('#qoAddToCartSubmit').select();
						} else{
							$('#qoProductQty').focus();
							$('#qoProductQty').select();
						}
					}
				}
			});
		},
		
		checkAddToCartQuickOrder : function(vProdCode, vVHN) { // Add to Cart validation - Quick Order
			var vForm = document.getElementById("QuickOrderForm");
			var vInfoDiv = "#addCartInfoQO";
			var vQty = vForm.qty.value;
			if (vQty == "" || vQty <= 0) {
				alert("Please enter a Quantity greater than zero to add to cart.");
				return false;
			}
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vFormData = $(vForm).serialize();
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php&Operation[0]=SetSessionVariable&Variable[ShowFullCart]=1';

			$(vInfoDiv).html(vAjaxLoadImg).show();
			
			$("#ajaxSummaryCart").load(vSummaryCartURL, vFormData, function(response, status, xhr) {
				if (status == "error") {
					var msg = "Sorry but there was an error: ";
					$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
				} else {
					vForm.reset();
					$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							var htmlText = '<div id="addCartInfoContent">\n';
							htmlText += '<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n';
							htmlText += '<p>' + vQty + ' Item';
							if (vQty != "1") {
								htmlText += 's';
							}
							htmlText += '<br />\n<strong>Added to Cart!</strong></p></div>\n';
							
							$(vInfoDiv).html(htmlText);
							$(vInfoDiv).fadeOut(3000);

							$("#qoOperation").attr("name","");
							$("#qoOperation").val("");
							vForm.productcode.value = "";
							vForm.productname.value = "";
							vForm.qoProductCode.value = "";

							SEL.checkProductCodeQuickOrder('',vVHN);

							if ($('#ajaxFullCart').css("display") == "none") {
								SEL.showFullCart(vVHN);
							}
							if ($("#addToCartUIMessage").length) {
								alert($("#addToCartUIMessage").html());
							}
						}
					});
				}
			});
		},

		recalculateCart: function(vVHN){ // Ajax recalculate cart
			var vForm = document.getElementById("ShoppingCartForm");
			var vInfoDiv = "#fullCartUpdateDiv";
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vFormData = $(vForm).serialize();
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
			
			$(vInfoDiv).html(vAjaxLoadImg).show();
			
			$("#ajaxSummaryCart").load(vSummaryCartURL, vFormData, function(response, status, xhr) {
				if (status == "error") {
					var msg = "Sorry but there was an error: ";
					$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
				} else {
					$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							var htmlText = '<div id="addCartInfoContent">\n<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n<p><strong>Recalculated<br />Cart!</strong></p></div>\n';
							
							$(vInfoDiv).html(htmlText);
							$(vInfoDiv).show();
							$(vInfoDiv).fadeOut(3000);
							
							if ($("#addToCartUIMessage").length) {
								alert($("#addToCartUIMessage").html());
							}
						}
					});
				}
			});
        },

		confirmClearCart: function(vVHN) {
			var vInfoDiv = "#fullCartUpdateDiv";
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			
			
			if (confirm("Are you sure you want to clear the cart?")) {
				var vURL = window.location.href;
				if (vURL.indexOf("?") != -1) { //URL has parameters
					var vURLArray = vURL.split('?');
					var vURL = vURLArray[0]; //URL without parameters
				}
				if (vURL.indexOf(".php") == -1) {
					vURL_Length = vURL.length;
					if (vURL.charAt(vURL_Length-1) == "/") {
						var vHomePage = "home.php";
					} else {
						var vHomePage = "/home.php";
					}
				} else {
					var vHomePage = "";
				}
				
				var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=ClearCart&Operation[1]=SetSessionVariable&Variable[ShowFullCart]=0';
				var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
				
				if ($("#paramID").length) {
					if ($("#paramID").attr("name") == "CCPage" || $("#paramID").attr("name") == "PaymentPage") {
						if (confirm("Clearing your cart now will cancel the order process\nand return you to our home page.\n\nCancel your order?")) {
							window.location.href = vVHN + "home.php?Operation[0]=ClearCart&Operation[1]=SetSessionVariable&Variable[ShowFullCart]=0&RedirectURL=" + encodeURIComponent(vVHN) + "&Operation[2]=Redirect";
						}
					} else {
						$(vInfoDiv).html(vAjaxLoadImg).show();
						
						$("#ajaxSummaryCart").load(vSummaryCartURL, function(response, status, xhr) {
							if (status == "error") {
								var msg = "Sorry but there was an error: ";
								$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
							} else {
								$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
									if (status == "error") {
										var msg = "Sorry but there was an error: ";
										$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
									} else {
										var htmlText = '<div id="addCartInfoContent">\n<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n<p><strong>Cleared<br />Cart!</strong></p></div>\n';
										
										$(vInfoDiv).html(htmlText);
										$(vInfoDiv).show();
										$(vInfoDiv).fadeOut(3000);
										
										SEL.showFullCart(vVHN);
									}
								});
							}
						});
					}
				} else {
					$(vInfoDiv).html(vAjaxLoadImg).show();
					
					$("#ajaxSummaryCart").load(vSummaryCartURL, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							var htmlText = '<div id="addCartInfoContent">\n<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n<p><strong>Cleared<br />Cart!</strong></p></div>\n';
							
							$(vInfoDiv).html(htmlText);
							$(vInfoDiv).show();
							$(vInfoDiv).fadeOut(3000);
							
							SEL.showFullCart(vVHN);
						}
					});
					
				}
			}
		},

		confirmRemoveCart: function(vIndex, vVHN) {
			var vInfoDiv = "#fullCartUpdateDiv";
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			
			if (confirm("Are you sure you want to remove this item from the cart?")) {
				var vURL = window.location.href;
				var vProdIdParam = "";
				var vQuantity = document.ShoppingCartForm.elements["productQuantityArray[" + vIndex + "]"].value;
				var vProductCode = document.ShoppingCartForm.elements["productCodesArray[" + vIndex + "]"].value;
				var vProductName = document.ShoppingCartForm.elements["productNamesArray[" + vIndex + "]"].value;
			
				if (vURL.indexOf("?") != -1) { // If URL has parameters
					var vURLArray = vURL.split('?');
					var vURL = vURLArray[0]; // Store URL without parameters
				}
				if (vURL.indexOf(".php") == -1) {
					vURL_Length = vURL.length;
					if (vURL.charAt(vURL_Length-1) == "/") {
						var vHomePage = "home.php";
					} else {
						var vHomePage = "/home.php";
					}
				} else {
					var vHomePage = "";
				}
				
				var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=RemoveFromCart&productcode=' + vProductCode + '&qty=' + vQuantity + '&productname=' + encodeURIComponent(vProductName);
				var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
				
				if ($("#paramID").length && $("#paramID").attr("name") == "CCPage") {
					if (confirm("Modifying your cart now will cancel the credit card order\nand return you to the start of the order process.\n\nContinue?")) {
						window.location.href = vVHN + "payments/pages/purchase_pages.php?ResetDeliveryAddress=1&Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&productname=" + encodeURIComponent(vProductName) + "&RedirectURL=" + encodeURIComponent(vVHN) + "payments/pages/purchase_pages.php&Operation[2]=Redirect";
					}
				} else {
					$(vInfoDiv).html(vAjaxLoadImg).show();
					
					$("#ajaxSummaryCart").load(vSummaryCartURL, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
								if (status == "error") {
									var msg = "Sorry but there was an error: ";
									$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
								} else {
									var htmlText = '<div id="addCartInfoContent">\n<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n<p><strong>Item Removed<br />From Cart!</strong></p></div>\n';
									
									$(vInfoDiv).html(htmlText);
									$(vInfoDiv).show();
									$(vInfoDiv).fadeOut(3000);
								}
							});
						}
					});
				}
			}
		},

		saveCart: function(vVHN){ // Ajax save cart
			var vForm = document.getElementById("ShoppingCartForm");
			if ($("#CartName").val() != "") {
				if (confirm("This Shopping Cart will be saved. You can access it via the Saved Carts option in your Account Menu.\n\nContinue?")) {
					vForm.elements["Operation[0]"].value = "SaveShoppingCart";
					var vInfoDiv = "#fullCartUpdateDiv";
					var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
					var vFormData = $(vForm).serialize();
					
					var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
					var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
					
					$(vInfoDiv).html(vAjaxLoadImg).show();
					
					$("#ajaxSummaryCart").load(vSummaryCartURL, vFormData, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
								if (status == "error") {
									var msg = "Sorry but there was an error: ";
									$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
								} else {
									var htmlText = '<div id="addCartInfoContent">\n<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n<p><strong>Cart<br />Saved!</strong></p></div>\n';
									
									$(vInfoDiv).html(htmlText);
									$(vInfoDiv).show();
									$(vInfoDiv).fadeOut(3000);
									
									if ($("#addToCartUIMessage").length) {
										alert($("#addToCartUIMessage").html());
									}
								}
							});
						}
					});
				}
			} else {
				alert("Please enter a name for your saved cart!");
				return false;
			}
		},

		confirmRestoreSavedCart : function(vCartID, vURL, vPageType) {
			if (confirm("This will restore your saved cart and merge it\nwith any currently active cart.\n\nContinue?")) {
				if (vPageType == "List") {
					window.location.href = vURL
							+ "admin/pages/saved_carts.php?ShoppingCartID="
							+ vCartID
							+ "&Operation[0]=RestoreCart&RedirectURL="
							+ encodeURIComponent(vURL)
							+ "admin/pages/saved_carts.php&Operation[1]=Redirect";
				} else if (vPageType == "View") {
					window.location.href = vURL
							+ "admin/pages/view_saved_cart.php?ShoppingCartID="
							+ vCartID
							+ "&Operation[0]=RestoreCart&RedirectURL="
							+ encodeURIComponent(vURL)
							+ "admin/pages/view_saved_cart.php?ShoppingCartID="
							+ vCartID + "&Operation[1]=Redirect";
				}
			}
		},

		confirmRemoveSavedCart : function(vCartID, vURL) {
			if (confirm("This will delete the selected saved cart.\n\nContinue?")) {
				window.location.href = vURL
						+ "admin/pages/saved_carts.php?ShoppingCartID="
						+ vCartID + "&Operation=RemoveShoppingCart";
			}
		},

		// Account Menu functions

		confirmReorderCart : function(vOrderID, vURL, vPageType) {
			if (confirm("This will restore your order and merge it\nwith any currently active cart.\n\nContinue?")) {
				if (vPageType == "View") {
					window.location.href = vURL
							+ "admin/pages/view_order.php?Operation[0]=ReorderCart&OrderID="
							+ vOrderID + "&ReorderType=ExactOrder&RedirectURL="
							+ encodeURIComponent(vURL)
							+ "admin/pages/view_order.php?OrderID=" + vOrderID
							+ "&Operation[1]=Redirect";
				} else {
					window.location.href = vURL
							+ "admin/pages/list_orders.php?Operation[0]=ReorderCart&OrderID="
							+ vOrderID
							+ "&ReorderType=ExactOrder&RedirectURL="
							+ encodeURIComponent(vURL)
							+ "admin/pages/list_orders.php&Operation[1]=Redirect";
				}
			}
		},

		addFavouriteToCart: function(vProdNum,vVHN) {
			var vForm = document.getElementById("FavouriteListForm");
			var vSelectedInStock = 0; //Used to test for selected items that are in stock
			var vSelectedOutOfStock = 0; //Used to test for selected items that are out of stock
			var vCheckSelected = 0; //Used to test for selected items
			
			if (vProdNum != "Multi") {
				document.getElementById("checkbox-" + vProdNum).checked = true;
			}
			var vInfoDiv = "#addCartInfo_" + vProdNum;
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vQty = 0;
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
			
			for (var i = 0; i < vForm.elements.length; i++) {
				if ((vForm.elements[i].type == "checkbox") && (vForm.elements[i].name != "checkAllToggle")) { // Loop through checkboxes (skip the "toggle" checkbox)
					if (vForm.elements[i].checked) {
						vCheckSelected += 1;
						var vCheckProductCode = vForm.elements[i].value;
						if (document.getElementById("inStock" + vCheckProductCode).value == "1") {
							document.getElementById("AddToCart_" + vCheckProductCode).name = "AddToCart[" + vCheckProductCode + "]";
							document.getElementById("AddToCart_" + vCheckProductCode).value = document.getElementById("qty-" + vCheckProductCode).value;
							vQty += parseInt(document.getElementById("qty-" + vCheckProductCode).value);
							
							vSelectedInStock += 1;
						} else {
							vSelectedOutOfStock += 1;
						}
					} else {
						var vCheckProductCode = vForm.elements[i].value;
						document.getElementById("AddToCart_" + vCheckProductCode).name = "";
						document.getElementById("AddToCart_" + vCheckProductCode).value = "";
					}
				}
			}
			if (vCheckSelected > 0) {
				if (vSelectedInStock > 0) {
					if (vSelectedOutOfStock > 0) {
						alert("Some selected items are marked as Out of Stock\r\nand will not be added to the cart.");
					}
					vForm.Operation.value = "ArrayAddToCart";
					var vFormData = $(vForm).serialize();
					
					$(vInfoDiv).html(vAjaxLoadImg).show();
					
					$("#ajaxSummaryCart").load(vSummaryCartURL, vFormData, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							//vForm.reset();
							$("#ajaxFullCart").load(vFullCartURL, function(response, status, xhr) {
								if (status == "error") {
									var msg = "Sorry but there was an error: ";
									$("#ajaxMsg").html(msg + xhr.status + " " + xhr.statusText);
								} else {
									var htmlText = '<div id="addCartInfoContent">\n';
									htmlText += '<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n';
									htmlText += '<p>' + vQty + ' Item';
									if (vQty != "1") {
										htmlText += 's';
									}
									htmlText += '<br />\n<strong>Added to Cart!</strong></p></div>\n';
									
									$(vInfoDiv).html(htmlText);
									
									$(vInfoDiv).fadeOut(3000);
									vForm.reset();
									$("#selectAllText").html("Select All");
									if ($('#ajaxFullCart').css("display") == "none") {
										SEL.showFullCart(vVHN);
									}
									if ($("#addToCartUIMessage").length) {
										alert($("#addToCartUIMessage").html());
									}
								}
							});
						}
					});
				} else {
					alert("All of the selected items are marked as Out of Stock.\r\nNothing will be added to the cart.");
					vForm.reset();
				}
			} else {
				alert("Please select one or more items to add to cart.");
			}
		},

		// Function to toggle favourite checkboxes on/off
		toggleSelect : function(form) {
			if (document.getElementById("checkAllToggle").checked) {
				var checkState = true;
				document.getElementById("selectAllText").innerHTML = "Deselect All";
			} else {
				var checkState = false;
				document.getElementById("selectAllText").innerHTML = "Select All";
			}
			for ( var i = 0; i < form.elements.length; i++) {
				if ((form.elements[i].type == "checkbox")
						&& (form.elements[i].name != "checkAllToggle")) { // Loop through checkboxes (skip the "toggle" checkbox)
					form.elements[i].checked = checkState;
				}
			}
		},

		deleteFavourites: function(vForm,vGroupName,vVHN) {
			var vInfoDiv = "#favouriteInfo_Delete";
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vFavouritesURL = vVHN + 'admin/pages/ajax_favourites.php';
			
			var vSelectedFavourites = 0;
			for (var i = 0; i < vForm.elements.length; i++) {
				if ((vForm.elements[i].type == "checkbox") && (vForm.elements[i].name != "checkAllToggle")) { // Loop through checkboxes (skip the "toggle" checkbox)
					if (vForm.elements[i].checked) {
						vSelectedFavourites += 1;
					}
				}
			}
			if (vSelectedFavourites > 0) {
				if (confirm("Are you sure you want to remove the selected Favourites?")) {
					vForm.Operation.value = "DeleteFavourite";
					var vFormData = $(vForm).serialize();
					
					$(vInfoDiv).html(vAjaxLoadImg).show();
					
					$("#favouritesTable").load(vFavouritesURL, vFormData, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#favouritesError").html(msg + xhr.status + " " + xhr.statusText);
						} else {
							vForm.reset();
					 		$("#selectAllText").html("Select All");
						}
					});
				}
			} else {
				alert("No favourites selected! Please select one or more favourites and try again.");
			}
		},

		// Function to display favourites for selected Group
		selectGroupName: function(vForm,vVHN) {
			var vSelectGroup = document.getElementById("SelectGroupName");
			var vSelectedGroup = vSelectGroup.options[vSelectGroup.selectedIndex].value;
			if (vSelectedGroup != "") {
				vForm.Operation.value = "";
				vForm.GroupName.value = vSelectedGroup;
				var vFavouritesURL = vVHN + 'admin/pages/ajax_favourites.php';
				var vFormData = $(vForm).serialize();
				
				$("#favouritesTable").load(vFavouritesURL, vFormData, function(response, status, xhr) {
					if (status == "error") {
						var msg = "Sorry but there was an error: ";
						$("#favouritesError").html(msg + xhr.status + " " + xhr.statusText);
					}
				});
			} else {
				alert("There is a problem with this Group Name! Please select another Group.");
				return false;
			}
		},

		moveFavourites: function(vForm,vGroupName,vVHN) {
			var vSelectGroup = document.getElementById("GroupNameMove");
			var vSelectedGroup = vSelectGroup.options[vSelectGroup.selectedIndex].value;
			if (vSelectedGroup != vGroupName) {
				var vSelectedFavourites = 0;
				for (var i = 0; i < vForm.elements.length; i++) {
					if ((vForm.elements[i].type == "checkbox") && (vForm.elements[i].name != "checkAllToggle")) { // Loop through checkboxes (skip the "toggle" checkbox)
						if (vForm.elements[i].checked) {
							vSelectedFavourites += 1;
						}
					}
				}
				if (vSelectedFavourites > 0) {
					vForm.Operation.value = "UpdateFavourite";
					vForm.GroupName.value = vSelectedGroup;
					var vFavouritesURL = vVHN + 'admin/pages/ajax_favourites.php';
					var vFormData = $(vForm).serialize();
					
					$("#favouritesTable").load(vFavouritesURL, vFormData, function(response, status, xhr) {
						if (status == "error") {
							var msg = "Sorry but there was an error: ";
							$("#favouritesError").html(msg + xhr.status + " " + xhr.statusText);
						}
					});
					vform.reset();
				} else {
					alert("No favourites selected! Please select one or more favourites and try again.");
				}
			} else {
				alert("Favourites are already in this Group. Please select a different Group.");
			}
		},

		createGroup : function(form, vVHN) {
			var vGroupName = form.GroupNameCreate.value;
			if (vGroupName != "") {
				form.submit();
			} else {
				alert("Please enter a Group Name!");
				form.GroupNameCreate.focus();
			}
		},

		deleteGroup : function(form) {
			var vSelectedGroupName = form.GroupName.options[form.GroupName.selectedIndex].value;
			if (vSelectedGroupName != "") {
				confirm('Are you sure you want to remove the selected Group?\nAll Favourites in this Group will also be deleted!');
				form.submit();
			} else {
				alert("No Group to delete!");
			}
		},

		// Payment Pages functions

		// check the contact and delivery details
		submitContactAndDeliveryForm : function(frm) {
			var vEmail = frm.ContactEmail.value;
			var vDeliveryCountrySelect = frm.elements["Delivery[Country]"];

			if (SEL.trim(frm.ContactName.value) == "") {
				alert("Please enter a Contact Name.");
				frm.ContactName.focus();
				return false;
			} else if (SEL.trim(frm.ContactEmail.value) == "") {
				alert("Please enter a Contact Email Address.");
				frm.ContactEmail.focus();
				return false;
			} else if ((SEL.trim(frm.ContactEmail.value) != "")
					&& (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
				alert("Please enter a valid Contact Email Address (ie yourname@yourdomain.com)");
				frm.ContactEmail.focus();
				return false;
			} else if (SEL.trim(frm.Recipient.value) == "") {
				alert("Please enter a Delivery Recipient.");
				frm.Recipient.focus();
				return false;
			} else if (vDeliveryCountrySelect.options[vDeliveryCountrySelect.selectedIndex].value == "") {
				alert("Please select a Country.");
				frm.elements["Delivery[Country]"].focus();
				return false;
			} else if (SEL.trim(frm.elements["Delivery[Address1]"].value) == "") {
				alert("Please enter a Delivery Address.");
				frm.elements["Delivery[Address1]"].focus();
				return false;
			} else if (SEL.trim(frm.elements["Delivery[Suburb]"].value) == "") {
				alert("Please enter a Delivery Suburb.");
				frm.elements["Delivery[Suburb]"].focus();
				return false;
			} else if (vDeliveryCountrySelect.options[vDeliveryCountrySelect.selectedIndex].value == "AU") {
				if (SEL.trim(frm.elements["Delivery[State]"].value) == "") {
					alert("Please enter a Delivery State.");
					frm.elements["Delivery[State]"].focus();
					return false;
				}
				if (SEL.trim(frm.elements["Delivery[PostCode]"].value) == "") {
					alert("Please enter a Delivery PostCode.");
					frm.elements["Delivery[PostCode]"].focus();
					return false;
				}
			}
			return true;
		},

		// check the freight and terms form
		submitFreightAndTermsForm : function(frm) {
			var vFreightSelected = false;
			freightRadio = document.getElementsByName("Freight");
			for ( var i = 0; i < freightRadio.length; i++) {
				if (freightRadio[i].checked) {
					vFreightSelected = true;
				}
			}
			if (vFreightSelected == false) {
				alert('Please select a freight option');
				return false;
			}

			id = false;
			colRadio = document.getElementsByName("PaymentTerm");
			for ( var i = 0; i < colRadio.length; i++) {
				if (colRadio[i].checked) {
					id = colRadio[i].value;
				}
			}
			if (id == false) {
				alert('Please select a payment term');
				return false;
			}

			divElem = document.getElementById('forceCredit');
			if (document.getElementById(id + '[AllowOnlineCreditCard]').value == 1) {
				divElem.innerHTML = '<input type="hidden" name="Operation[2]" id="Operation[2]" value="CreateWebOrder">' + '<input type="hidden" id="WebOrderStatus" name="WebOrderStatus" value="4">' + '<input type = hidden name="PageName" value="payments/pages/order_payment.php"/>';
			} else {
				divElem.innerHTML = '<input type="hidden" name="WebOrderStatus" name="WebOrderStatus" value="1">';
			}

			return true;
		},

		// List Invoices page
		checkInvoiceSubmitParams : function() {
			if (document.getElementById("Open").checked == false
					&& document.getElementById("Credit").checked == false
					&& document.getElementById("Closed").checked == false) {
				alert("Sorry, at least one of the checkboxes need to be selected");
				return false;
			}
			return true;
		},
		
		submitMultipleInvoicePayment: function() {
			var invs = document.getElementsByName("InvoiceIDs[]");
			var inv_count = 0;
			var inv_checked = false;
			var inv_ids = "";

			for (inv_count=0; inv_count<invs.length; inv_count++) {
				if(invs[inv_count].checked) {
					inv_checked = true;
					if(inv_ids != "") {
						inv_ids = "|" + inv_ids;
					}
					inv_ids = invs[inv_count].value + inv_ids;
				}
			}

			if(inv_ids == "") {
				alert("Sorry, at least one of the invoice checkboxes needs to be selected");
				return false;
			}
			else {
				var url_redir = document.getElementById("multipleInvoiceRedirect").href;
				document.getElementById("multipleInvoiceRedirect").href = url_redir.replace("~INVIDS~", inv_ids);
				return true;
			}
		}

	};
}();

