/*
 +------------------------------------------------------------------------------+
 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);
 Ensure that any new functions are placed within the outer "return" block,
 and that each function is terminated with a "," (except for the last
 function), ie:
 functionName: function(a,b,c) {
 var x =  a + b + c;
 ..
 },
 +------------------------------------------------------------------------------+
 CSS Label: NA
 +------------------------------------------------------------------------------+
 Created: December 13 2007
 +------------------------------------------------------------------------------+
 Current Version: 1.0
 +------------------------------------------------------------------------------+
 Change History:
 December 13 2007 - Created
 +------------------------------------------------------------------------------+
 Author(s): Paul Johnson
 +------------------------------------------------------------------------------+
 */
var popUpWin=0; // Initialise variable - used by the popUpWindow() function

var SEL = function(){
    return {
    
        // ===== General functions =====
        
        trim: function(s){
            return s.replace(/^\s&#42;(\S&#42;(\s+\S+)&#42;)\s&#42;&#36;/, "&#36;1");
        },
        
        onlyNumbers: function(e){ // Allow only numbers to be entered into text fields. Checks input as it is being typed.
            var keynum;
            var keychar;
            var numcheck;
            
            if (window.event) // IE
            {
                keynum = e.keyCode;
            }
            else 
                if (e.which) // Netscape/Firefox/Opera
                {
                    keynum = e.which;
                }
            if (!keynum) {
                return true;
            }
            //alert(keynum);
            //if backspace - for firefox
            if (keynum == 8) {
                return true;
            }
            
            keychar = String.fromCharCode(keynum);
            
            if ((keychar >= "0") && (keychar <= "9")) {
                return true;
            }
            else {
                return false;
            }
        },
		
		
		popUpWindow: function(URLStr, left, top, width, height) {
			if(popUpWin) {
				if(!popUpWin.closed) popUpWin.close();
			}
			popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
		},
        
        // ===== Contact, Registration, Request Info/Quote and Login forms. =====
        
        changeStates: function(form){ // Dynamically update the States entry field based on the Country selected.
            var countryList = form.Country;
            var selectedCountry = countryList.options[countryList.selectedIndex].value;
            
            if (selectedCountry == "AU") {
                document.getElementById("StatesAU").style.display = "block";
                document.getElementById("StatesUS").style.display = "none";
                document.getElementById("StatesOther").style.display = "none";
            }
            else 
                if (selectedCountry == "US") {
                    document.getElementById("StatesAU").style.display = "none";
                    document.getElementById("StatesUS").style.display = "block";
                    document.getElementById("StatesOther").style.display = "none";
                }
                else {
                    document.getElementById("StatesAU").style.display = "none";
                    document.getElementById("StatesUS").style.display = "none";
                    document.getElementById("StatesOther").style.display = "block";
                }
        },
        
        /* Contact Form validation. Also handles the Request Information and Request for Quote forms.
         Checks for a hidden field named "FormType" and sets the form introduction text and field data accordingly. */
        checkContactForm: function(){
            var frm = document.getElementById("ContactForm");
            var vEmail = frm.ContactEmail.value;
            
            if (document.getElementById("StatesAU").style.display == "block") {
                var stateList = frm.StateAU;
                var selectedState = stateList.options[stateList.selectedIndex].value;
            }
            else 
                if (document.getElementById("StatesUS").style.display == "block") {
                    var stateList = frm.StateUS;
                    var selectedState = stateList.options[stateList.selectedIndex].value;
                }
                else 
                    if (document.getElementById("StatesOther").style.display == "block") {
                        var stateList = frm.StateOther;
                        var selectedState = stateList.value;
                    }
            
            if (SEL.trim(frm.ContactName.value) == "") {
                alert("Please enter a Contact Name.");
                frm.ContactName.focus();
                return false;
            }
            else 
                if (SEL.trim(frm.ContactEmail.value) == "") {
                    alert("Please enter an Email Address.");
                    frm.ContactEmail.focus();
                    return false;
                }
                else 
                    if ((SEL.trim(frm.ContactEmail.value) != "") && (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
                        alert("Please enter a valid Email Address (ie yourname@yourdomain.com)");
                        frm.ContactEmail.focus();
                        return false;
                    }
                    else {
                    
                        frm.State.value = selectedState;
                        newline = "\n";
                        space = " ";
                        
                        if (frm.FormType.value == "prodInfo") { // Request for Information
                            var eContent = "A Request for Information Form has been submitted through your StraightSell website. Here are the details:" + newline + newline;
                            eContent += "Requested Product:" + space + frm.TheProduct.value + newline + newline;
                        }
                        else 
                            if (frm.FormType.value == "prodQuote") { // Request for Quote
                                var eContent = "A Request Quote has been submitted through your StraightSell website. Here are the details:" + newline + newline;
                                eContent += Products + newline;
                                eContent += "==========================================================\n";
                            }
                            else { // 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.AdminUserName.value) == "") {
                alert("Please enter a Username.");
                frm.AdminUserName.focus();
                return false;
            }
            else 
                if (frm.AdminPassword.value == "" || frm.RetypeAdminPassword.value == "" || frm.AdminPassword.value != frm.RetypeAdminPassword.value) {
                    alert("Please enter a Password - twice to confirm.");
                    frm.AdminPassword.focus();
                    return false;
                }
                else 
                    if (SEL.trim(frm.AdminName.value) == "") {
                        alert("Please enter your full name.");
                        frm.AdminName.focus();
                        return false;
                    }
                    else 
                        if (SEL.trim(frm.AdminEmail.value) == "") {
                            alert("Please enter an Email Address.");
                            frm.AdminEmail.focus();
                            return false;
                        }
                        else 
                            if ((SEL.trim(frm.AdminEmail.value) != "") && (vEmail.indexOf("@") == -1 || vEmail.indexOf(".") == -1)) {
                                alert("Please enter a valid Email Address (ie yourname@yourdomain.com)");
                                frm.AdminEmail.focus();
                                return false;
                            }
                            else 
                                if (SEL.trim(frm.PostCode.value) == "") {
                                    alert("Please enter your postcode.");
                                    frm.PostCode.focus();
                                    return false;
                                }
                                else 
                                    if (SEL.trim(selectedState) == "") {
                                        alert("Please enter your State.");
                                        stateList.focus();
                                        return false;
                                    }
                                    else 
                                        if (SEL.trim(frm.AdminPhone.value) == "") {
                                            alert("Please enter your phone number.");
                                            frm.AdminPhone.focus();
                                            return false;
                                        }
                                        else {
                                            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;
        },
        
        
        // ===== Product List, Product Detail and Search functions =====
        
		checkSimpleSearch: function(frm, vURL) {
			if(frm.searchfilter.value == "" || frm.searchfilter.value == "Search Products") {
				alert("Please enter a search term");
				frm.searchfilter.focus();
				frm.searchfilter.select();
				return false;
			}
			frm.action = vURL + "product_list/pages/product_list.php?pager=1&startpage=1&searchfilter=" + frm.searchfilter.value;
			return true;
		},
		
		quantityPlusMinus: function(vProdCode, vPlusMinus, vMinQty){ // ProductList Quantity Plus/Minus functionality
            var vForm = document.getElementById("AddToCartForm" + vProdCode);
			
			if (vPlusMinus == "Plus") {
				vForm.qtyPack.value = parseInt(vForm.qtyPack.value) + parseInt(vMinQty);
				vForm.qty.value = parseInt(vForm.qtyPack.value);
				return true;
			}
			if (vPlusMinus == "Minus") {
				if (vForm.qtyPack.value > vMinQty) {
					vForm.qtyPack.value = parseInt(vForm.qtyPack.value) - parseInt(vMinQty);
					vForm.qty.value = parseInt(vForm.qtyPack.value);
					return true;
				} else {
					return false;
				}
			}
        },
		
		quantityPlusMinusCart: function(vIndex, vPlusMinus, vMinQty){ // Shopping Cart Quantity Plus/Minus functionality
            var vForm = document.getElementById("ShoppingCartForm");

			if (vPlusMinus == "Plus") {
				vForm.elements["qtyPack-" + vIndex].value = parseInt(vForm.elements["qtyPack-" + vIndex].value) + parseInt(vMinQty);
				vForm.elements["productQuantityArray[" + vIndex + "]"].value = parseInt(vForm.elements["qtyPack-" + vIndex].value);
				return true;
			}
			if (vPlusMinus == "Minus") {
				if (vForm.elements["qtyPack-" + vIndex].value > vMinQty) {
					vForm.elements["qtyPack-" + vIndex].value = parseInt(vForm.elements["qtyPack-" + vIndex].value) - parseInt(vMinQty);
					vForm.elements["productQuantityArray[" + vIndex + "]"].value = parseInt(vForm.elements["qtyPack-" + vIndex].value);
					return true;
				} else {
					return false;
				}
			}
        },
		
		quantityPlusMinusFav: function(vProdCode, vPlusMinus, vMinQty){ // Favourites List Quantity Plus/Minus functionality
            var vForm = document.getElementById("FavouriteListForm");
			
			if (vPlusMinus == "Plus") {
				vForm.elements["qtyPack-" + vProdCode].value = parseInt(vForm.elements["qtyPack-" + vProdCode].value) + parseInt(vMinQty);
				vForm.elements["qty-" + vProdCode].value = parseInt(vForm.elements["qtyPack-" + vProdCode].value);
				return true;
			}
			if (vPlusMinus == "Minus") {
				if (vForm.elements["qtyPack-" + vProdCode].value > vMinQty) {
					vForm.elements["qtyPack-" + vProdCode].value = parseInt(vForm.elements["qtyPack-" + vProdCode].value) - parseInt(vMinQty);
					vForm.elements["qty-" + vProdCode].value = parseInt(vForm.elements["qtyPack-" + vProdCode].value);
					return true;
				} else {
					return false;
				}
			}
        },
		
        checkAddToCartProductList: function(vProdCode){ // Add to Cart validation - Product List
            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.");
                    vForm.productcode.focus();
					return false;
                }
                else {
                    return true;
                }
            }
            else {
                return true;
            }
        },
        
        checkAddToFavouritesProductList: function(vProdCode){ // Add to Favourites validation - Product List
            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" + document.getElementById('ProductName' + vProdCode).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;
            }
        },
		
		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 =====
		
		confirmClearCart: function() {
			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
				}
				window.location.href = vURL + "?Operation[0]=ClearCart&RedirectURL=" + vURL + "&Operation[1]=Redirect";
			}
		},
		
		confirmRemoveCart: function(vIndex) {
			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
				}
				//window.location.href = vURL + "?Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&productname=" + vProductName + "&RedirectURL=" + vURL + "&Operation[1]=Redirect";
				window.location.href = vURL + "?Operation[0]=RemoveFromCart&productcode=" + vProductCode + "&qty=" + vQuantity + "&RedirectURL=" + vURL + "&Operation[1]=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.Operation.value = "SaveShoppingCart";
					frm.submit();
				}
			} else {
				alert("Please enter a name for your saved cart!");
				return false;
			}
		},
		
				
		// ===== 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;
		}
        
    };
}
();
