/*
 +------------------------------------------------------------------------------+
 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";
                }
        },
        // Dynamically update the States entry field based on the Country selected - Contact/Checkout page
        changeStatesCheckout: function(form){
            var countryList = form.elements["Delivery[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 { // Statndard 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.EmailFrom.value = frm.ContactEmail.value;
                        frm.EmailContent.value = eContent;
                        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.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;
			                                            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;
        },
        
        // Register form "slide down"
        registerSlider: function() {
        	var vForm = document.getElementById("AddUserForm");
        	if ($("#checkout-register-slider").css("display") == "none") {
        		$("#checkout-register-slider").slideDown(500, function() {
        			$("#checkRegister").attr("checked", "checked");
        			window.location.href = "#Join";
        			vForm.AdminName.focus();
        		});
        		
        	} else {
        		$("#checkout-register-slider").slideUp(500);
        	}
        },
        
        toggleStoreAddress: function(vAddress){
			if ($("#" + vAddress).css("display") == "none") {
				$("#" + vAddress).slideDown(500);
			} else {
				$("#" + vAddress).slideUp(500);
			}
        },
        toggleAccountMenu: function(vVHN){ // Function to show/hide full cart
			if ($("#amWrapper").css("display") == "none") {
				$.get( vVHN + 'site/widgets/am_show_menu.php?Operation[0]=SetSessionVariable&Variable[ShowAccountMenu]=1', function() {
					$("#toggleIcon").attr("src", vVHN + "documents/am-toggle-hide.gif");
					$("#toggleIcon").attr("alt", "Hide Menu");
					$("#toggleIcon").attr("title", "Hide Menu");
					$("#amWrapper").slideDown(500);
				});
			} else if ($("#amWrapper").css("display") != "none") {
				$.get( vVHN + 'site/widgets/am_show_menu.php?Operation[0]=SetSessionVariable&Variable[ShowAccountMenu]=0', function() {
					$("#toggleIcon").attr("src", vVHN + "documents/am-toggle-show.gif");
					$("#toggleIcon").attr("alt", "Show Menu");
					$("#toggleIcon").attr("title", "Show Menu");
					$("#amWrapper").slideUp(500);
				});
			}
        },
        
        // ===== Product List, Product Detail and Search functions =====
        

		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;
		},
		
		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;
			}
			frm.submit();
			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;
		},
		
		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);
				});
			}
        },
        
        // Check quantity entered for Add to Cart/Recalcule Cart
        // Must be less than or equal to MaxQuantity custom field, if set
        checkCartMaxQuantity: function(vMaxQty,vQtyId){
        	
        	var vSubmitQty = $("#" + vQtyId).attr("value");
        	if (vSubmitQty > parseInt(vMaxQty)) {
        		alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nThe Quantity value will be set to the maximum value allowed.");
        		$("#" + vQtyId).attr("value", vMaxQty);
        		$("#" + vQtyId).focus();
        	}
        },
        
        checkCartMaxQuantityPD: function(vMaxQty,vQtyId,vProdCode){
        	if ($("#cartItemQty" + vProdCode).length) { // This product is in the cart
        		var vCartQty = parseInt($("#cartItemQty" + vProdCode).attr("value")); // Number of this product already in the cart
        	} else {
        		var vCartQty = 0;
        	}
        	var vSubmitQty = parseInt($("#" + vQtyId).attr("value"));
        	var vTotalQty = vCartQty + vSubmitQty;
        	if (vTotalQty > parseInt(vMaxQty)) {
        		if (vCartQty > 0) {
        			if (vCartQty == parseInt(vMaxQty)) {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have the maximum of " + vCartQty + " in the cart.");
            			$("#" + vQtyId).attr("value", "1");
        			} else {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have " + vCartQty + " in the cart.\nThe Quantity value will be set to the maximum value allowed.");
        				$("#" + vQtyId).attr("value", vMaxQty-vCartQty);
        			}
        		} else {
        			alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nThe Quantity value will be set to the maximum value allowed.");
            		$("#" + vQtyId).attr("value", vMaxQty);
        		}
        		$("#" + vQtyId).focus();
        		return false;
        	}
        },
		
        updateOptionStockMsgPL: function(vProdNum){ // Swap Stock Level display based on selected Option
        	var vForm = document.getElementById("AddToCartForm" + vProdNum);
        	var vOptionSelect = vForm.productcode;
        	var vSelectedOption = vOptionSelect.options[vOptionSelect.selectedIndex].value;
			var vStockMsgDiv = "#stockMessage_" + vProdNum;
			var vCartDiv = "#addToCartDiv" + vProdNum;
			
			if (vSelectedOption == "") {
				$(vStockMsgDiv).html("&nbsp;");
            } else {
            	var vStockMsg = document.getElementById("optionStockLevel_" + vProdNum + "_" + vSelectedOption).value;
            	$(vStockMsgDiv).html(vStockMsg);
            	if ($(vStockMsgDiv).html() != "In Stock") {
            		if ($(vStockMsgDiv).html() == "Out of Stock") {
            			if ($(vCartDiv).css("display") != "none") {
            				$(vCartDiv).fadeOut(500);
            			}
            		} else {
            			if ($(vCartDiv).css("display") == "none") {
            				$(vCartDiv).fadeIn(500);
            			}
            		}
            		$(vStockMsgDiv).attr("class","OutOfStockMessage");
            	} else {
            		$(vStockMsgDiv).attr("class","InStockMessage");
            		if ($(vCartDiv).css("display") == "none") {
        				$(vCartDiv).fadeIn(500);
        			}
            	}
            }
        },
        
		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 vFormData = $(vForm).serialize();
			var vQty = vForm.qty.value;
			var vOptionSelect = vForm.productcode;
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
			
			if (vForm.isOptionSelect.value == "1" && vOptionSelect.options[vOptionSelect.selectedIndex].value == "") {
				alert("Please make a selection from the drop-down menu.");
				vForm.productcode.focus();
			} else {
				$(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();
						$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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();
										
										if ($("#addToCartUIMessage").length) {
											alert($("#addToCartUIMessage").html());
										}
									}
								});
							}
						});
					}
				});
            }
        },
        
        // Add to cart for products with a Maximum Quantity set
        checkAddToCartProductListMaxQty: function(vProdCode,vProdNum,vVHN,vMaxQty,vQtyId){ // Add to Cart validation - Product List
        	if ($("#cartItemQty" + vProdCode).length) { // This product is in the cart
        		var vCartQty = parseInt($("#cartItemQty" + vProdCode).attr("value")); // Number of this product already in the cart
        	} else {
        		var vCartQty = 0;
        	}
        	var vSubmitQty = parseInt($("#" + vQtyId).attr("value"));
        	var vTotalQty = vCartQty + vSubmitQty;
        	if (vTotalQty > parseInt(vMaxQty)) {
        		if (vCartQty > 0) {
        			if (vCartQty == parseInt(vMaxQty)) {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have the maximum of " + vCartQty + " in the cart.");
            			$("#" + vQtyId).attr("value", "1");
        			} else {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have " + vCartQty + " in the cart.\nThe Quantity value will be set to the maximum value allowed.");
        				$("#" + vQtyId).attr("value", vMaxQty-vCartQty);
        			}
        		} else {
        			alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nThe Quantity value will be set to the maximum value allowed.");
            		$("#" + vQtyId).attr("value", vMaxQty);
        		}
        		$("#" + vQtyId).focus();
        		return false;
        	}
			
        	var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vInfoDiv = "#addCartInfo_" + vProdNum;
			var vAjaxLoadImg = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vFormData = $(vForm).serialize();
			var vQty = vForm.qty.value;
			var vOptionSelect = vForm.productcode;
			
			var vSummaryCartURL = vVHN + 'product_list/widgets/ajax_summary_cart.php';
			var vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.php';
			var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
			
			if (vForm.isOptionSelect.value == "1" && vOptionSelect.options[vOptionSelect.selectedIndex].value == "") {
				alert("Please make a selection from the drop-down menu.");
				vForm.productcode.focus();
			} else {
				$(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();
						$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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();
										
										if ($("#addToCartUIMessage").length) {
											alert($("#addToCartUIMessage").html());
										}
									}
								});
							}
						});
					}
				});
            }
        },
        
        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[' + vOptionSelect.options[vOptionSelect.selectedIndex].value + ']=' + 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[' + vProdCode + ']=' + 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();
			}
		},
		
		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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.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 {
					$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.php';
				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 {
						SEL.showFullCart(vVHN);
						//$(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 {
								$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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 {
					SEL.showFullCart(vVHN);
					//$(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 {
							$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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);
										}
									});
								}
							});
						}
					});
					
				}
			}
		},
		
		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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.php';
				var vFullCartURL = vVHN + 'product_list/widgets/ajax_full_cart.php';
				
				if ($("#paramID").length && $("#paramID").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 {
							$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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").value != "") {
				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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.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 {
							$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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 in stock
			var vCheckSelected = 0; //Used to test for selected items that are in stock
			
			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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.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 {
							$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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';
											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 ($("#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.");
			}
		},
		
		addFavouriteToCartMaxQty: function(vProdCode,vProdNum,vVHN,vMaxQty,vQtyId) {
			if ($("#cartItemQty" + vProdCode).length) { // This product is in the cart
        		var vCartQty = parseInt($("#cartItemQty" + vProdCode).attr("value")); // Number of this product already in the cart
        	} else {
        		var vCartQty = 0;
        	}
        	var vSubmitQty = parseInt($("#" + vQtyId).attr("value"));
        	var vTotalQty = vCartQty + vSubmitQty;
        	if (vTotalQty > parseInt(vMaxQty)) {
        		if (vCartQty > 0) {
        			if (vCartQty == parseInt(vMaxQty)) {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have the maximum of " + vCartQty + " in the cart.");
            			$("#" + vQtyId).attr("value", "1");
        			} else {
        				alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nYou currently have " + vCartQty + " in the cart.\nThe Quantity value will be set to the maximum value allowed.");
        				$("#" + vQtyId).attr("value", vMaxQty-vCartQty);
        			}
        		} else {
        			alert("Sorry, this item has a Maximum Order Quantity of " + parseInt(vMaxQty) + ".\nThe Quantity value will be set to the maximum value allowed.");
            		$("#" + vQtyId).attr("value", vMaxQty);
        		}
        		$("#" + vQtyId).focus();
        		return false;
        	}
			
			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 in stock
			var vCheckSelected = 0; //Used to test for selected items that are in stock
			
			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 vSummaryCartLeftURL = vVHN + 'product_list/widgets/ajax_summary_cart_left.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 {
							$("#ajaxSummaryCartLeft").load(vSummaryCartLeftURL, 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';
											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 ($("#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(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 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(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 == "") {
				alert("Please select a Delivery Country.");
				frm.elements["Delivery[Country]"].focus();
				return false;
			} else if (SEL.trim(selectedState) == "") {
				alert("Please enter a Delivery State.");
				stateList.focus();
				return false;
			} else if(SEL.trim(frm.elements["Delivery[PostCode]"].value) == "") {
					alert("Please enter a Delivery PostCode.");
					frm.elements["Delivery[PostCode]"].focus();
					return false;
			}
			frm.elements["Delivery[State]"].value = selectedState;
			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"/>';
				_gaq.push(['_link', 'https://secure.straightsell.com.au/payments/pages/order_payment.php?session_id=']);
			} 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;
		}
        
    };
}
();

