/*
 +------------------------------------------------------------------------------+
 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;
            frm.captcha.value=frm.captcha.value.toUpperCase();

            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;
            }
			
			if (SEL.trim(frm.CompanyName.value) == "") {
                alert("Please enter an Company Name.");
                frm.CompanyName.focus();
                return false;
            }
			
			if (SEL.trim(frm.ContactEmail.value) == "") {
                alert("Please enter an Email Address.");
                frm.ContactEmail.focus();
                return false;
            }

			if (SEL.trim(frm.ContactPhone.value) == "") {
                alert("Please enter an Phone Number.");
                frm.ContactPhone.focus();
                return false;
            }
            
			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;
            }
            
                    
			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 += "Company Name:" + space + frm.CompanyName.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;
        },
        
        /* Sell Your Equipment Form validation. */
        checkSellEquipmentForm: function(){
           var frm = document.getElementById("SellEquipmentForm");
           var ContactPrefList = frm.ContactPref;
           var selectedContactPref = ContactPrefList.options[ContactPrefList.selectedIndex].value;
           var vEmail = frm.Email.value;
		   frm.captcha.value=frm.captcha.value.toUpperCase();
           
           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(selectedContactPref) == "") {
               alert("Please enter a Contact Preference.");
               frm.ContactPref.focus();
               return false;
           } else if (SEL.trim(frm.FirstName.value) == "") {
        	   alert("Please enter a First Name.");
        	   frm.FirstName.focus();
        	   return false;
           } else if (SEL.trim(frm.LastName.value) == "") {
	           alert("Please enter a Last Name.");
	           frm.LastName.focus();
	           return false;
           } else if (SEL.trim(frm.Email.value) == "") {
	           alert("Please enter an Email Address.");
	           frm.Email.focus();
	           return false;
           } else if ((SEL.trim(frm.Email.value) != "") && (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
	           alert("Please enter a valid Email Address (ie yourname@yourdomain.com)");
	           frm.Email.focus();
	           return false;
           } else {
        	   frm.State.value = selectedState;
        	   newline = "\n";
        	   space = " ";
           
        	   var eContent = "A Sell Your Equipment Form has been submitted through your StraightSell website. Here are the details:" + newline + newline;
        	   eContent += "Contact Preference:" + space + selectedContactPref + newline;
        	   eContent += "First Name:" + space + frm.FirstName.value + newline;
        	   eContent += "Last Name:" + space + frm.LastName.value + newline;
        	   eContent += "Title:" + space + frm.Title.value + newline;
        	   eContent += "Company Name:" + space + frm.CompanyName.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;
        	   eContent += "Phone:" + space + frm.Phone.value + newline;
        	   eContent += "Mobile:" + space + frm.Mobile.value + newline;
        	   eContent += "Email:" + space + frm.Email.value + newline;
        	   eContent += "Fax:" + space + frm.Fax.value + newline + newline;
        	   if (frm.Comments.value == "Comments") {
        		   frm.Comments.value = "";
        	   }
        	   eContent += "Comments:" + space + frm.Comments.value + newline;
           
        	   frm.EmailFrom.value = frm.Email.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;
        },
        
        showLogin: function() { // Function to show/hide login strip
        	if ($($('loginstrip')).style.display == "none") {
        		Effect.SlideDown('loginstrip',{ duration: 0.5 });
        	} else {
        		Effect.SlideUp('loginstrip',{ duration: 0.5 });
        	}
        },
        
        checkSignup: function(){
			var frm = document.getElementById("newsletterSignupForm");
			var vEmail = frm.DefaultEmail.value;
			var countryList = frm.Country;
			var industryList = frm.Industry;
			var selectedCountry = countryList.options[countryList.selectedIndex].value;
			var selectedIndustry = industryList.options[industryList.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 (frm.FirstName.value == "") {
                alert("Please enter your First Name");
                frm.FirstName.focus();
                return false;
            }
            if (frm.LastName.value == "") {
                alert("Please enter your Last Name.");
                frm.LastName.focus();
                return false;
            }
            if (selectedIndustry == "") {
            	alert("Please select an Industry.");
            	frm.Industry.focus();
                return false;
			}
            /*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.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.ContactType.value = "Newsletter - " + selectedIndustry;
    		frm.State.value = selectedState;
        	frm.elements["EmailAddressTo[0]"].value = frm.DefaultEmail.value;
            return true;
        },
        // ===== Product List, Product Detail and Search functions =====
        
		showCatMenus: function(){ // Login Form validation
            $($("catmenuToggle")).style.marginLeft = 0;
        },
		
		checkSimpleSearch: function(frm, vURL) {
			if(frm.searchfilter.value == "" || frm.searchfilter.value == "Search Products/Item No.") {
				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);

			var searchOption = -1;
			for (i=frm.searchFields.length-1; i > -1; i--) {
				if (frm.searchFields[i].checked) {
					searchOption = i; i = -1;
				}
			}
			location.href = vURL + searchValue + "/sf/pl.php?sfield=" + frm.searchFields[searchOption].value;
			return false;
		},
		
		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')).style.display == "none") {
				new Ajax.Request( vVHN + 'product_list/widgets/ajax_show_fullcart.php?Operation[0]=SetSessionVariable&Variable[ShowFullCart]=1',
				{
					method: 'get',
					onSuccess: function(){
						Effect.SlideDown('ajaxFullCart',{ duration: 0.5 });
					}
				});
			} else if ($($('ajaxFullCart')).style.display != "none") {
				new Ajax.Request( vVHN + 'product_list/widgets/ajax_show_fullcart.php?Operation[0]=SetSessionVariable&Variable[ShowFullCart]=0',
				{
					method: 'get',
					onSuccess: function(){
						Effect.SlideUp('ajaxFullCart',{ duration: 0.5 });
					}
				});
			}
        },
		
		checkAddToCartProductList: function(vProdCode,vProdNum,vVHN){ // Add to Cart validation - Product List
			var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vInfoDiv = 'addCartInfo_' + vProdNum;
			$(vInfoDiv).innerHTML = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vQty = vForm.qty.value;
			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.");
					vForm.productcode.focus();
				}
				else {
					$($(vInfoDiv)).show();
					new Ajax.Updater({
						success: 'ajaxSummaryCart',
						failure: 'ajaxMsg'
					}, vVHN + 'product_list/widgets/ajax_summary_cart.php', {
						method: 'post',
						parameters: $(vForm).serialize(true),
						onComplete: function(){
							vForm.reset();
							new Ajax.Updater({
								success: 'ajaxFullCart',
								failure: 'ajaxMsg'
							}, vVHN + 'product_list/widgets/ajax_full_cart.php', {
								method: 'post',
								parameters: {},
								onComplete: function(){
									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).innerHTML = htmlText;
									
									$(vInfoDiv).fade({
										duration: 3.0,
										from: 1,
										to: 0
									});
									vForm.reset();
									if ($('addToCartUIMessage')) {
										alert($('addToCartUIMessage').innerHTML);
									}
								}
							});
						}
					});
				}
            }
            else {
				$($(vInfoDiv)).show();
				new Ajax.Updater({ success: 'ajaxSummaryCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_summary_cart.php',
				{
					method: 'post',
					parameters: $(vForm).serialize(true),
					onComplete: function(){
						vForm.reset();
						new Ajax.Updater({ success: 'ajaxFullCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_full_cart.php',
						{
							method: 'post',
							parameters: {},
							onComplete: function(){
								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).innerHTML = htmlText;
								
								$(vInfoDiv).fade({
									duration: 3.0,
									from: 1,
									to: 0
								});
								vForm.reset();
								if ($('addToCartUIMessage')) {
									alert($('addToCartUIMessage').innerHTML);
								}
							}
						});
					}
				});
            }
        },
        
        checkAddToFavouritesProductList: function(vProdCode,vProdNum,vVHN){ // Add to Favourites validation - Product List
			var vForm = document.getElementById("AddToCartForm" + vProdNum);
			var vInfoDiv = 'favouriteInfo_' + vProdNum;
			$($(vInfoDiv)).innerHTML = '<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 {
                    //alert("This product will be added to your Favourites List, which can be accessed via your Account Menu.");
					$(vInfoDiv).show();
					new Ajax.Updater({ success: 'favouriteInfo_' + vProdNum, failure: 'favouriteInfo_' + vProdNum }, vVHN + 'product_list/widgets/ajax_add_favourite.php?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[' + vOptionSelect.options[vOptionSelect.selectedIndex].value + ']=' + vOptionSelect.options[vOptionSelect.selectedIndex].value,
					{
						method: 'get',
						onComplete: function(){
							$(vInfoDiv).fade({
								duration: 3.0,
								from: 1,
								to: 0
							});
						}
					});
                }
            }
            else {
               // alert("This product will be added to your Favourites List, which can be accessed via your Account Menu.");
				$(vInfoDiv).show();
				new Ajax.Updater({ success: 'favouriteInfo_' + vProdNum, failure: 'favouriteInfo_' + vProdNum }, vVHN + 'product_list/widgets/ajax_add_favourite.php?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[' + vProdCode + ']=' + vProdCode,
				{
					method: 'get',
					onComplete: function(){
						$(vInfoDiv).fade({
							duration: 3.0,
							from: 1,
							to: 0
						});
					}
				});
            }
        },
		
		checkAddToCartProductDetail: function(vProdCode) {
			var vForm = document.getElementById("AddToCartForm" + vProdCode);
			
			// Check if product addons with associations have been added to the cart with an option selected - error if not.
			for (var i = 0; i < vForm.elements.length; i++) {
				if ((vForm.elements[i].type == "checkbox") && (vForm.elements[i].checked)) { // Loop through checked checkboxes
					var vCheckName = vForm.elements[i].name;
					var vCheckNameArray = vCheckName.split("_",2);
					var vCheckProductCode = vCheckNameArray[1]; // Extract addon's product code from checkbox name - (name_productcode)
					if (vForm.elements["isOptionSelect_" + vCheckProductCode].value == "1") { // This addon has associated products
						var vAddonSelect = vForm.elements["addonSelect_" + vCheckProductCode];
						var vAddonSelectValue = vAddonSelect.options[vAddonSelect.selectedIndex].value; // Get the value/product code of the selected option
						if (vAddonSelectValue == "") { // No option selected
							alert("Please make a selection from the drop-down menu for\r\n" + document.getElementById('AddonName_' + vCheckProductCode).name);
							vAddonSelect.focus();
							return false;
						} else { // Option selected - add selected productcode to "AddToCart[]" name
							document.getElementById("AddToCart_" + vCheckProductCode).name = "AddToCart[" + vAddonSelectValue + "]";
						}
					} else { // This addon doesn't have any associated products
						document.getElementById("AddToCart_" + vCheckProductCode).name = "AddToCart[" + vCheckProductCode + "]";
					}
				}
			}
			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\r\n" + document.getElementById('ProductName').name);
					vForm.productcode.focus();
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		},
		
		checkAddToFavouritesProductDetail: function(vProdCode) {
			var vForm = document.getElementById("AddToCartForm" + vProdCode);
			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\r\n" + document.getElementById('ProductName').name);
					vForm.productcode.focus();
				} else {
					var vURL = window.location.href;
					if (vURL.indexOf("?") != -1) { // If URL has parameters
						var vURLArray = vURL.split('?');
						var vURL = vURLArray[0]; // Store URL without parameters
					}
					alert("This product will be added to your Favourites List, which you can access via your Account Menu.");
					window.location.href = vURL + "?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[" + vOptionSelect.options[vOptionSelect.selectedIndex].value + "]=" + vOptionSelect.options[vOptionSelect.selectedIndex].value;
				}
			} else {
				var vURL = window.location.href;
				if (vURL.indexOf("?") != -1) { // If URL has parameters
					var vURLArray = vURL.split('?');
					var vURL = vURLArray[0]; // Store URL without parameters
				}
				alert("This product will be added to your Favourites List, which you can access via your Account Menu.");
				window.location.href = vURL + "?Operation=CreateFavourite&GroupName=Unassigned&ProductCode[" + vProdCode + "]=" + vProdCode;
			}
		},
		
		
		// ===== 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?")) {
				//window.location.href = vVHN + "payments/pages/purchase_pages.php?Operation[0]=ModifyCart&ResetDeliveryAddress=1&RedirectURL=" + encodeURIComponent(vVHN) + "payments/pages/purchase_pages.php&Operation[1]=Redirect";
				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';
			$(vInfoDiv).innerHTML = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			
			$(vInfoDiv).show();
			new Ajax.Updater({ success: 'ajaxSummaryCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_summary_cart.php',
			{
				method: 'post',
				parameters: $(vForm).serialize(true),
				onComplete: function(){
					//vForm.reset();
					new Ajax.Updater({ success: 'ajaxFullCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_full_cart.php',
					{
						method: 'post',
						parameters: {},
						onComplete: function(){
							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).innerHTML = htmlText;
							$(vInfoDiv).show();
							
							$(vInfoDiv).fade({
								duration: 3.0,
								from: 1,
								to: 0
							});
							//vForm.reset();
							if ($('addToCartUIMessage')) {
								alert($('addToCartUIMessage').innerHTML);
							}
						}
					});
				}
			});
        },
		
		confirmClearCart: function(vVHN) {
			var vInfoDiv = 'fullCartUpdateDiv';
			$(vInfoDiv).innerHTML = '<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 = "";
				}
				if ($($('paramID'))) {
					if ($('paramID').name == "CCPage" || $('paramID').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)).show();
						new Ajax.Updater({
							success: 'ajaxSummaryCart',
							failure: 'ajaxMsg'
						}, vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=ClearCart&Operation[1]=SetSessionVariable&Variable[ShowFullCart]=0', {
							method: 'post',
							parameters: {},
							onComplete: function(){
								new Ajax.Updater({
									success: 'ajaxFullCart',
									failure: 'ajaxMsg'
								}, vVHN + 'product_list/widgets/ajax_full_cart.php', {
									method: 'post',
									parameters: {},
									onComplete: function(){
										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).innerHTML = htmlText;
										$(vInfoDiv).show();
										
										$(vInfoDiv).fade({
											duration: 3.0,
											from: 1,
											to: 0
										});
										
										SEL.showFullCart(vVHN);

									}
								});
							}
						});
					}
				} else {
					$($(vInfoDiv)).show();
					new Ajax.Updater({
						success: 'ajaxSummaryCart',
						failure: 'ajaxMsg'
					}, vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=ClearCart&Operation[1]=SetSessionVariable&Variable[ShowFullCart]=0', {
						method: 'post',
						parameters: {},
						onComplete: function(){
							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).innerHTML = htmlText;
							
							$(vInfoDiv).fade({
								duration: 3.0,
								from: 1,
								to: 0
							});
							
							SEL.showFullCart(vVHN);

						}
					});
				}
			}
		},
		
		confirmRemoveCart: function(vIndex, vVHN) {
			var vInfoDiv = 'fullCartUpdateDiv';
			$(vInfoDiv).innerHTML = '<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 = "";
				}
				if ($($('paramID'))) {
					if ($('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)).show();
						new Ajax.Updater({ success: 'ajaxSummaryCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=RemoveFromCart&productcode=' + vProductCode + '&qty=' + vQuantity + '&productname=' + encodeURIComponent(vProductName),
						{
							method: 'post',
							parameters: {},
							onComplete: function(){
								//vForm.reset();
								new Ajax.Updater({ success: 'ajaxFullCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_full_cart.php',
								{
									method: 'post',
									parameters: {},
									onComplete: function(){
										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).innerHTML = htmlText;
										$(vInfoDiv).show();
										
										$(vInfoDiv).fade({
											duration: 3.0,
											from: 1,
											to: 0
										});
										//vForm.reset();
									}
								});
							}
						});
					}
				} else {
					$($(vInfoDiv)).show();
					new Ajax.Updater({ success: 'ajaxSummaryCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_summary_cart.php?Operation[0]=RemoveFromCart&productcode=' + vProductCode + '&qty=' + vQuantity + '&productname=' + encodeURIComponent(vProductName),
					{
						method: 'post',
						parameters: {},
						onComplete: function(){
							//vForm.reset();
							new Ajax.Updater({ success: 'ajaxFullCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_full_cart.php',
							{
								method: 'post',
								parameters: {},
								onComplete: function(){
									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).innerHTML = htmlText;
									$(vInfoDiv).show();
									
									$(vInfoDiv).fade({
										duration: 3.0,
										from: 1,
										to: 0
									});
									//vForm.reset();
								}
							});
						}
					});
				}
			}
		},
		
		/*confirmRemoveCart: function(vIndex, vVHN) {
			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 = "";
				}
				if ($($('paramID'))) {
					if ($('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 if($('paramID').name == "PaymentPage") {
						window.location.href = vURL + vHomePage + "?Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&productname=" + encodeURIComponent(vProductName) + "&RedirectURL=" + encodeURIComponent(vURL) + "?ResetDeliveryAddress=1&Operation[2]=Redirect";
					} else {
						window.location.href = vURL + vHomePage + "?Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&productname=" + encodeURIComponent(vProductName) + "&RedirectURL=" + encodeURIComponent(vURL) + "?" + $('paramID').name + "=" + $('paramID').value + "&Operation[2]=Redirect";
					}
				} else {
					window.location.href = vURL + vHomePage + "?Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&productname=" + encodeURIComponent(vProductName) + "&RedirectURL=" + encodeURIComponent(vURL) + "&Operation[2]=Redirect";
				}
			}
		},*/
		
		
		/*saveCart: function(frm) {
			if (document.getElementById("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?")) {
					frm.elements["Operation[0]"].value = "SaveShoppingCart";
					frm.submit();
				}
			} else {
				alert("Please enter a name for your saved cart!");
				return false;
			}
		},*/
		
		saveCart: function(vVHN){ // Ajax save cart
			var vForm = document.getElementById("ShoppingCartForm");
			if (document.getElementById("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';
					$(vInfoDiv).innerHTML = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
					
					$(vInfoDiv).show();
					new Ajax.Updater({ success: 'ajaxSummaryCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_summary_cart.php',
					{
						method: 'post',
						parameters: $(vForm).serialize(true),
						onComplete: function(){
							//vForm.reset();
							new Ajax.Updater({ success: 'ajaxFullCart', failure: 'ajaxMsg' }, vVHN + 'product_list/widgets/ajax_full_cart.php',
							{
								method: 'post',
								parameters: {},
								onComplete: function(){
									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).innerHTML = htmlText;
									$(vInfoDiv).show();
									
									$(vInfoDiv).fade({
										duration: 3.0,
										from: 1,
										to: 0
									});
									//vForm.reset();
									if ($('addToCartUIMessage')) {
										alert($('addToCartUIMessage').innerHTML);
									}
								}
							});
						}
					});
				}
			} 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
			
			var vInfoDiv = 'addCartInfo_' + vProdNum;
			$(vInfoDiv).innerHTML = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vQty = 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) {
						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";
					
					$($(vInfoDiv)).show();
					new Ajax.Updater({
						success: 'ajaxSummaryCart',
						failure: 'ajaxMsg'
					}, vVHN + 'product_list/widgets/ajax_summary_cart.php', {
						method: 'post',
						parameters: $(vForm).serialize(true),
						onComplete: function(){
							vForm.reset();
							new Ajax.Updater({
								success: 'ajaxFullCart',
								failure: 'ajaxMsg'
							}, vVHN + 'product_list/widgets/ajax_full_cart.php', {
								method: 'post',
								parameters: {},
								onComplete: function(){
									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).innerHTML = htmlText;
									
									$(vInfoDiv).fade({
										duration: 3.0,
										from: 1,
										to: 0
									});
									vForm.reset();
									document.getElementById("selectAllText").innerHTML = "Select All";
									if ($('addToCartUIMessage')) {
										alert($('addToCartUIMessage').innerHTML);
									}
								}
							});
						}
					});
				} 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(form,vGroupName,vVHN) {
			var vInfoDiv = 'favouriteInfo_Delete';
			$(vInfoDiv).innerHTML = '<img src="' + vVHN + 'documents/ajax-loader-blue.gif" alt="" />';
			var vSelectedFavourites = 0;
			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)
					if (form.elements[i].checked) {
						vSelectedFavourites += 1;
					}
				}
			}
			if (vSelectedFavourites > 0) {
				if (confirm("Are you sure you want to remove the selected Favourites?")) {
					form.Operation.value = "DeleteFavourite";
					$($(vInfoDiv)).show();
					new Ajax.Updater({ success: 'favouritesTable', failure: 'favouritesError' }, vVHN + 'admin/pages/ajax_favourites.php',
					{
					    method:'post',
						parameters: $('FavouriteListForm').serialize(true),
						onComplete: function(){
							//$($(vInfoDiv)).show();
							//var htmlText = '<div id="addCartInfoContent">\n';
							//htmlText += '<img src="' + vVHN + 'documents/greentick.gif" name="GreenTick" alt="" />\n';
							//htmlText += '<p>' + vSelectedFavourites + ' Item';
							//if (vSelectedFavourites != "1") {
							//	htmlText += 's';
							//}
							//htmlText += '<br />\n<strong>Deleted from List!</strong></p></div>\n';
							//
							//$(vInfoDiv).innerHTML = htmlText;
							//$(vInfoDiv).fade({
							//	duration: 3.0,
							//	from: 1,
							//	to: 0
							//});
							form.reset();
					 		document.getElementById("selectAllText").innerHTML = "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(form,vVHN) {
			var vSelectGroup = document.getElementById("SelectGroupName");
			var vSelectedGroup = vSelectGroup.options[vSelectGroup.selectedIndex].value;
			if (vSelectedGroup != "") {
				form.Operation.value = "";
				form.GroupName.value = vSelectedGroup;
				new Ajax.Updater({ success: 'favouritesTable', failure: 'favouritesError' }, vVHN + 'admin/pages/ajax_favourites.php',
					  {
					    method:'post',
						parameters: $('FavouriteListForm').serialize(true)
					  });
			} else {
				alert("There is a problem with this Group Name! Please select another Group.");
				return false;
			}
		},
		
		moveFavourites: function(form,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 < form.elements.length; i++) {
					if ((form.elements[i].type == "checkbox") && (form.elements[i].name != "checkAllToggle")) { // Loop through checkboxes (skip the "toggle" checkbox)
						if (form.elements[i].checked) {
							vSelectedFavourites += 1;
						}
					}
				}
				if (vSelectedFavourites > 0) {
					form.Operation.value = "UpdateFavourite";
					form.GroupName.value = vSelectedGroup;
					new Ajax.Updater({ success: 'favouritesTable', failure: 'favouritesError' }, vVHN + 'admin/pages/ajax_favourites.php',
					  {
					    method:'post',
						parameters: $('FavouriteListForm').serialize(true)
					  });
					  form.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;
		}
        
    };
}
();

