function submitonEnter(evt, frm){
	if (window.event) { //IE
		var charCode = event.keyCode;
	} else {
		var charCode = evt.which;
	}
	if(charCode == '13'){
		document.forms[frm].submit();
	}
}
function validateText(field, descField) {
	if (field.value == "") {
		alert ("Please complete the " + descField + " field.")
		field.focus();
		return (false);
	}
	return (true)
}

function validateSingleChkbox(field, descField) {
	if (!field.checked) {
		alert ("Please complete the " + descField + ".")
		field.focus();
		return (false);
	}
	return (true)
}

function validateChkbox(field, descField) {
	var valid
	valid = false
	for (i = 0; i < field.length; i++) {
		if (field[i].checked){
			valid = true
		}
	}
	if (!valid) {
		alert ("Please complete the " + descField + ".")
		field[0].focus();
		return (false);
	}
	return (true)
}

function validateCombo(field, descField) {
	with(field) {
		if (options[selectedIndex].text == "") {
		alert ("Please complete the " + descField + " field.")
		field.focus();
		return (false);
		}
		return (true)
	}
}

function validateNumber(field, descField) {
	with(field) {
		var re = /,/g 
		var tmpNum = parseFloat(field.value.replace(re,""))
		if (Number(tmpNum) != tmpNum) {
			alert ("Please enter a valid number for the " + descField + " field.");
			field.focus();
			return (false);
		}
		return (true)
	}
}

function isFloat(s,allowCommas) { 
        var result; 
        var re = /,/g 
        if(typeof(allowCommas)=='undefined') { var allowCommas = false; } 
        
        if (allowCommas) { 
                result = s != "" && parseFloat(s.replace(re,"")) == s.replace(re,""); 
        } 
        else { 
                result = s != "" && parseFloat(s) == s; 
        } 
        return result;         
} 

function checkEmailAddress(field){
	var x = field.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)){
		return(true);
	} else {
		alert('Incorrect email address format');
		field.focus();
		return(false);
	}
}

//Pop up window functions
function openWindow (url, strWidth, strHeight) {
	//Get the screen size
//	if (document.all) {
//	   w = document.body.clientWidth;
//	   h = document.body.clientHeight;
//	}
//	else if (document.layers) {
//	   w = window.innerWidth;
//	   h = window.innerHeight;
//	}
	//Calc the centre position
	w = 1024;
	h = 768;
	var topPos = (h-strHeight)/2, leftPos = (w-strWidth)/2;
	//Create the window
     popWindow = window.open ( url,'popWindow', 'width=' + strWidth + ',height=' + strHeight + 'top=' + topPos + ',left=' + leftPos + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1')
     popWindow.focus();
}

function openWindowMenu (url, strWidth, strHeight) {
	//Get the screen size
//	if (document.all) {
//	   w = document.body.clientWidth;
//	   h = document.body.clientHeight;
//	}
//	else if (document.layers) {
//	   w = window.innerWidth;
//	   h = window.innerHeight;
//	}
	//Calc the centre position
	w = 1024;
	h = 768;
	var topPos = (h-strHeight)/2, leftPos = (w-strWidth)/2;
	//Create the window
     popWindow = window.open ( url,'popWindow', 'width=' + strWidth + ',height=' + strHeight + 'top=' + topPos + ',left=' + leftPos + ',toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1')
     popWindow.focus();
}

function showProcessing() {
	processing.style.visibility = "visible";
}
function hideProcessing() {
	processing.style.visibility = "hidden";
}

function showHideProductCat() {
	with (document.forms[0]){
		if (InputType.options[InputType.selectedIndex].text=='Product') {
			divSelectProductCat.style.display = 'block';
		} else if (InputType.options[InputType.selectedIndex].text=='Replacement Accessory') {
			divSelectProductCat.style.display = 'block';			
		} else {
			divSelectProductCat.style.display = 'none';
		}
	}
}

function showHideAccessory(id) {
	if (document.getElementById('divprodaccoption' + id).style.display == 'none') {
		document.getElementById('divprodaccoption' + id).style.display = 'block';
	} else {
		document.getElementById('divprodaccoption' + id).style.display = 'none';
	}
}


function isValidObject(objToTest) {
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}
	return true;
}

//@Left equivalents
function strLeft(sourceStr, keyStr){
return (sourceStr.indexOf(keyStr) == -1 | keyStr=='') ? '' : sourceStr.split(keyStr)[0];
}
function nLeft(str, n){
if (n <= 0)     // Invalid bound, return blank string
	return "";
else if (n > String(str).length)   // Invalid bound, return
	return str;  // entire string
else // Valid bound, return appropriate substring
	return String(str).substring(0,n);
}

//@Right equivalents
function strRight(sourceStr, keyStr){
idx = sourceStr.indexOf(keyStr);
return (idx == -1 | keyStr=='') ? '' : sourceStr.substr(idx+ keyStr.length);
}
function nRight(str, n){
if (n <= 0)     // Invalid bound, return blank string
	return "";
else if (n > String(str).length)   // Invalid bound, return
	return str;  // entire string
else { // Valid bound, return appropriate substring
	var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);}
}

//@RightBack equivalent
function rightBack(sourceStr, keyStr){
arr = sourceStr.split(keyStr);
return (sourceStr.indexOf(keyStr) == -1 | keyStr=='') ? '' : arr.pop()
}

//@LeftBack equivalent
function leftBack(sourceStr, keyStr){
arr = sourceStr.split(keyStr)
arr.pop();
return (keyStr==null | keyStr=='') ? '' : arr.join(keyStr)
}

//@Middle equivalent
function middle(sourceStr, keyStrLeft, keyStrRight){ 
return strLeft(strRight(sourceStr,keyStrLeft), keyStrRight);
} 

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
function arrayUnique(a){
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++) {
      for(var x = i + 1 ; x < n; x++)
      {
         if(a[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}
function cleanArray(actual){
  var newArray = new Array();
  for(var i = 0; i<actual.length; i++){
      if (actual[i]){
        newArray.push(actual[i]);
    }
  }
  return newArray;
}


function addToCart(idprod) {
	//Validate
	frm = document.forms[0];
	with (document.forms[0]){	
		intQty = qty.value;		
		var idprodoption = '';
		var idprodoptionlist = '';
		var idaccoption = '';
		var idaccoptionlist = '';
		if (!validateText(qty, 'quantity')) return(false);
		if (!validateNumber(qty, 'quantity')) return(false);
		//Product options
		//Loop through all product option radios and confirm an option has been checked
		for (var i = 0; i < frm.elements.length; i++) {
			if (nLeft(frm.elements[i].name, 18) == "InputProductOption") {
				if (frm[frm.elements[i].name].length == undefined) {
					if (!validateSingleChkbox(frm[frm.elements[i].name], 'product options')) return(false);
				} else {
					if (!validateChkbox(frm[frm.elements[i].name], 'product options')) return(false);
				}					
				//Get the prod option ids
				if (frm[frm.elements[i].name].length == undefined) {
					if (frm[frm.elements[i].name].checked){
						idprodoption = idprodoption + ' ' + frm[frm.elements[i].name].value;
					}	
				} else {
					for (y = 0; y < frm[frm.elements[i].name].length; y++) {
						if (frm[frm.elements[i].name][y].checked){
							idprodoption = idprodoption + ' ' + frm[frm.elements[i].name][y].value;
						}
					}															
				}							
			}
		}
		//Remove duplicates and clean array
		var arrids = new Array();
		arrids = idprodoption.split(' ');
		arrids = cleanArray(arrids);
		idprodoptionlist = idprod + '(' + arrayUnique(arrids).toString().replace(/,/g, '~') + '):' + intQty;	
		//Product accessories		
		//Now if any accessories have been selected then check for any accessory options
		for (var x = 0; x < frm.elements.length; x++) {
			if (nLeft(frm.elements[x].name, 21) == "InputProductAccessory") {
				if (frm[frm.elements[x].name].checked) {
					idaccoption = '';
					var idacc = strRight(frm.elements[x].name, 'InputProductAccessory')
					for (var i = 0; i < frm.elements.length; i++) {
						if (nLeft(frm.elements[i].name, 20 + idacc.length) == "InputAccessoryOption" + idacc) {
							if (frm[frm.elements[i].name].length == undefined) {
								if (!validateSingleChkbox(frm[frm.elements[i].name], 'accessory options')) return(false);
							} else {
								if (!validateChkbox(frm[frm.elements[i].name], 'accessory options')) return(false);
							}			
							//Find out which id was checked (from the selected option id we can get back to the accessory)
							if (frm[frm.elements[i].name].length == undefined) {
								if (frm[frm.elements[i].name].checked){
									idaccoption = idaccoption + ' ' + frm[frm.elements[i].name].value;
								}	
							} else {
								for (y = 0; y < frm[frm.elements[i].name].length; y++) {
									if (frm[frm.elements[i].name][y].checked){
										idaccoption = idaccoption + ' ' + frm[frm.elements[i].name][y].value;
									}
								}															
							}
						}
					}
					//Remove duplicates and clean array
					var arrids = new Array();
					arrids = idaccoption.split(' ');
					arrids = cleanArray(arrids);
					if (idaccoptionlist != '') {
						idaccoptionlist = idaccoptionlist + ';';
					}
					idaccoptionlist = idaccoptionlist + idacc + '(' + arrayUnique(arrids).toString().replace(/,/g, '~') + '):' + intQty;
				}	
			}
		}	
	}
	
	//Add to cart
	//Shopping cart order code format to be the id of the product and then and option ids and then accessory id with option ids
	//id(idoptionlist.idoptionlist.idoptionlist):qty;idaccessory(idoptionlist.idoptionlist.idoptionlist):qty;idaccessory(idoptionlist.idoptionlist):qty	etc etc
	strCombine = idprodoptionlist;
	if (idaccoptionlist != '') {
		strCombine = idprodoptionlist + ';' +idaccoptionlist;
	}
	self.location.href="cart.php?action=add&item=" + strCombine;
}

function addSpecialPaymentToCart(strID) {
	//Validate
	with (document.forms[0]){
		if (!validateText(description, 'description')) return(false);	
		if (!validateText(amount, 'amount')) return(false);			
		if (!validateNumber(amount, 'amount')) return(false);		
		var re = /,/g 
		var tmpNum = parseFloat(amount.value.replace(re,""));
		if (tmpNum <= 0){
			alert("Please enter an amount larger than $0.00");
			amount.focus()
			return(false)
		}
	}
	var id = strID;
	var strProd = 'SPECIAL'
	var strOption = '';
	var strOption1 = '';	
	var strSpecialDesc = document.forms[0].description.value; //Use for special payment desc
	strSpecialDesc = strSpecialDesc.replace(/#/g, '');
	strSpecialDesc = strSpecialDesc.replace(/&/g, '');
	strSpecialDesc = strSpecialDesc.replace(/:/g, '');
	strSpecialDesc = strSpecialDesc.replace(/'/g, '');
	strSpecialDesc = strSpecialDesc.replace(/"/g, '');	
	strSpecialDesc = strSpecialDesc.replace(/,/g, '');
	strSpecialDesc = strSpecialDesc.replace(/[(]/g, '');	
	strSpecialDesc = strSpecialDesc.replace(/[)]/g, '');	
	strSpecialDesc = strSpecialDesc.replace(/[[]/g, '');	
	strSpecialDesc = strSpecialDesc.replace(/[]]/g, '');
	var curSpecialPrice = document.forms[0].amount.value;
	var intQty = '1'; 
	//Add to cart
	strCombine = id + '(' + strSpecialDesc + '[' + curSpecialPrice + ']):' + intQty;
	strCombine = strCombine.replace(/ /g, '_');	
	self.location.href="cart.php?action=add&item=" + strCombine;
}
function updateCart() {
	//Validate all the qty fields
	elems = document.getElementsByTagName( 'input' )
	for (var x = 0; x < elems.length; x++) {	
		if (nLeft(elems[x].name, 3) == 'qty') {
			if (!validateNumber(elems[x], 'quantity')) return(false);
		}
	}
	document.forms['cart'].submit();
}

function submitOnlineOrder() {
	with (document.forms['OnlineOrder']){
		if (!validateText(Delivery_name, 'delivery name')) return(false);
		if (!validateText(Delivery_address1, 'delivery address1')) return(false);
		if (!validateText(Delivery_city, 'delivery city')) return(false);						
		if (!validateText(Delivery_state, 'delivery state')) return(false);		
		if (!validateText(Contact_email, 'contact email')) return(false);			
		if (!checkEmailAddress(Contact_email)) return(false);					
		if (!validateSingleChkbox(InputTerms, 'terms and conditions')) return(false);		
	}
	document.forms['OnlineOrder'].submit();
}

function copyAddress() {
	with (document.forms['OnlineOrder']) {
		Delivery_name.value = Billing_name.value
		Delivery_address1.value = Billing_address1.value
		Delivery_address2.value = Billing_address2.value
		Delivery_city.value = Billing_city.value
		Delivery_state.value = Billing_state.value
		Delivery_zip.value = Billing_zip.value
		Delivery_country.value = Billing_country.value
	}
}

function switchCountry() {
	with(document.forms[0].customercountry) {
		//Country switcher can be done from any page, just bounce back to home page
		self.location.href = 'index.php?switchcountryto=' + options[selectedIndex].text;
	}
}

function rowHighlight(objectThis, strClass) {
	objectThis.className=strClass
}