function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function imagePreload(tag, img_out, img_on) {
	var img = document.getElementById(tag);
	var imgOut = new Image;
	imgOut.src = img_out;
	var imgOn = new Image;
	imgOn.src = img_on;
	//alert(this.src);
	var p = img.parentNode;
	p.onmouseover = function () {
		img.src = imgOn.src;
	}
	p.onmouseout = function () {
		img.src = imgOut.src;
	}

}

// Popup Window (Centred)
function popup(url,winname,w,h,feat) {
	if (!(isNaN(w) || isNaN(h))) {
		var x=parseInt((screen.width-w)/2);
		var y=parseInt((screen.height-h)/2);
		if (x<0)	x=0;
		if (y<0)	y=0;

		if (feat!=null && feat!="") {
			feat=","+feat;
		} else {
			feat="";
		}
		feat="left="+x+",top="+y+",width="+w+",height="+h+feat;
	}
	window.open(url,winname,feat);
}

function launchPopUp(strURL,strType,strHeight,strWidth) {
	var strOptions="";
	if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
	if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
	if (strType=="elastic") strOptions="scrollbars,height="+strHeight+",width="+strWidth;//,resizable,location
	window.open(strURL, 'newWin', strOptions);
}


function openGoogle(url) {
	popup(url,"",780,600,"resizable");
}

//If a field has not been edited athen clear it on click

function clearThis(el) {
  if (el.defaultValue==el.value) el.value = ""
}

//Change the class to a dimmed version and disabled form elements
function useBill() {
	var billVal = document.getElementById('useBillingAddress').checked;
	if (billVal == true) {
		disabledForm("DeliveryForm", true);
		document.getElementById('DeliverySave').className = "red232Disabled";
		document.getElementById('DeliveryForm').className = "disabled";
	} else {
		disabledForm("DeliveryForm", false);
		document.getElementById('DeliverySave').className = "red232";
		document.getElementById('DeliveryForm').className = null;
	}
}

//Run through the array in the form and disable everything
function disabledForm(formName, trueFalse) {
	targetForm = document.getElementById(formName);
	for (i=0;i<targetForm.elements.length;i++) {
		targetForm.elements[i].disabled = trueFalse;
	}
}

//Simple show and hide functions
function hide(elementName) { document.getElementById(elementName).style.display = "none"  ;}
function show(elementName) { document.getElementById(elementName).style.display = "block" ;}

//Find the status of all the controls on the address page
//Left Side
var savedBill;
//Right Side
var sameAsBill;
var savedDeli;
function addressGetStatus() {
	savedDeli  = document.getElementById('savedNewBilling1').checked;
	sameAsBill = document.getElementById('useBillingAddress').checked;
	savedDeli  = document.getElementById('savedNewDelivery1').checked;
}

function sameAsBillingAddress() {
	addressGetStatus();
	if(sameAsBill == true) {
		hide('deliveryAddressHolder');
		document.getElementById('reqDelivery').style.color = "#ffffff";
		document.getElementById('savedNewDelivery1').disabled = true;
		document.getElementById('savedNewDelivery2').disabled = true;
	} else {
		if(savedDeli == false) {
			show('deliveryAddressHolder');
		}
		document.getElementById('reqDelivery').style.color = "#7c7a65";
		document.getElementById('savedNewDelivery1').disabled = false;
		document.getElementById('savedNewDelivery2').disabled = false;
	}
}





function paymentSwitcher(option){
	selectedOpt = document.getElementById(option);
	for(i=1;i<3;i++){
	document.getElementById('opt'+i).className = "paymentOption";
	}
	selectedOpt.className = "paymentOption paymentHighlight";

	hide("VISAPanel");
	hide("PayLaterPanel");

	switch (option) {
		case "opt1":
			show("VISAPanel");
		break;
		case "opt2":
			show("PayLaterPanel");
		break;
	}

}





function openDiv(targetDiv, note, imageDir){

	div = document.getElementById(targetDiv);
	indi = document.getElementById(note);


	if (div.style.display == "none"){
		show(targetDiv);
		indi.innerHTML = '<img src="' + imageDir + '/arrow_up.gif" alt="arrow" />Close';

	} else {
		hide(targetDiv);
		indi.innerHTML = '<img src="' + imageDir + '/arrow_down.gif" alt="arrow" />Open';
	}

}



//Generic site wide Add to Basket / Buy Now function.
function AddThisToBasket(thisFormName, thisQtyElementID, catEntryID, quantityElementID, catEntryElementID) {

	if (quantityElementID == null){
		quantityElementID = "OrderItemAddFormQuantity";
	  }
	 if (catEntryElementID == null){
		catEntryElementID = "OrderItemAddFormCatEntryId";
  	}

	//##debug##
	//alert(thisFormName + ' \n' + thisQtyElementID + ' \n' + catEntryID + ' \n' + quantityElementID + ' \n' + catEntryElementID);

	if(document.getElementById(thisQtyElementID).value=="" || document.getElementById(thisQtyElementID).value==0){
		alert("Make sure you specify a valid 'quantity' for your item");
		document.getElementById(thisQtyElementID).focus();
		return false
	}

	document.getElementById(quantityElementID).value = document.getElementById(thisQtyElementID).value;
	document.getElementById(catEntryElementID).value = catEntryID;

	document.getElementById(thisFormName).submit();

}



//Validates product code field and submits form.
function VerifyProductCode(thisFormName, productID) {
	if(document.getElementById(productID).value==""){
		alert("Please specify a valid product code");
		document.getElementById(productID).focus();
		return false;
	}
    if(validatequantity(document.getElementById('QuickOrderQuantityId'))==true){
	  document.QuickQuickOrderItemAddForm.partNumber.value = document.getElementById(productID).value.toUpperCase();
	  document.QuickQuickOrderItemAddForm.quantity.value = document.getElementById('QuickOrderQuantityId').value;
	  document.QuickQuickOrderItemAddForm.submit();
	}
}



function validatequantity(quantityId){
  dotphone = quantityId.value.lastIndexOf('.');
  if(isNaN(quantityId.value) || quantityId.value<0 || dotphone !=-1){ 
    alert('The field "Qty" should be numeric, integer and positive');
    quantityId.value="1";
    quantityId.focus();
    return false;
  }
  return true;
}


//Generic site wide email validation
function validate_email(field,alerttxt){
	with (field){
		apos=value.indexOf("@")
		dotpos=value.lastIndexOf(".")
		if (apos<1||dotpos-apos<2){
			alert(alerttxt);
			return false
		}
		else{
			return true
		}
	}
}



// Eliminates blank spaces at the begining and the end
function trimer(parameter){
  while (parameter.value.charAt(0) == " ") {
    parameter.value = parameter.value.substr(1, parameter.value.length - 1); 
  }
  while (parameter.value.charAt(parameter.value.length - 1) == " ") {
    parameter.value = parameter.value.substr(0, parameter.value.length - 1); 
  }
  return true;
}

// Eliminates blank spaces inside a String
function trimall(param) {
  var newparam ="";
  for (var x=0;x<param.value.length;x++){
    if (param.value.charAt(x)==" "){
      newparam = newparam;
    }else {
      newparam = newparam + param.value.charAt(x);
    }
  }
  param.value=newparam;
}

// This could be an alternative for trimall(param) function 
// although some browsers could not support it
// param.value = param.value.replace(/ /g, "");
// Give back navigator & version
// alert("navigator: " + navigator.appName + " version: " + navigator.appVersion)

//Email validation
function validateemail(param) {
  var at;
  var dot;
  var difference;
  var firstat;
  at = param.value.lastIndexOf('@');
  dot = param.value.lastIndexOf('.');
  difference = dot-at;
  if (at!=-1){
    for(var x=0;x<=at;x++){
      if(param.value.charAt(x)=="@"){
        firstat = x;
        break;
      }
    }
  }
  if(param.value.length!=0) {
    if (at== -1 || dot== -1 || difference<2 || (firstat!=at) || param.value.length<5 || firstat==0) {
      alert(param.value +" is not a valid email address!");
      param.focus();
      param.value="";
      return false; 
    } 
  }else {
    alert('Please enter an email address');
    param.focus();
    return false;
  }
  return true;
}
 
 
 
// Validate phone and fax numbers

function validatephonefax(phone, fax){
  if (phone!=null){
    dotphone = phone.value.lastIndexOf('.');
    if (phone.value.length!=0){
      if(isNaN(phone.value) || phone.value<0 || dotphone !=-1){ 
        alert('The field "Phone Number" should be numeric, integer and positive');
        phone.value="";
        phone.focus();
        return false;
      }
    }
  }
  if(fax!=null){
    dotfax = fax.value.lastIndexOf('.');
    if (fax.value.length!=0){
      if(isNaN(fax.value) || fax.value<0 || dotfax !=-1){  
        alert('The field "Fax Number" should be numeric, integer and positive');
        fax.value="";
        fax.focus();
        return false;
      }
    }
  }
  return true;
}

// Validate phone and fax numbers

function validatephone(phone){
    dotphone = phone.value.lastIndexOf('.');
    if (phone.value.length!=0){
      if(isNaN(phone.value) || phone.value<0 || dotphone !=-1){
        alert('The field "Phone Number" should be numeric, integer and positive');
        phone.value="";
        phone.focus();
        return false;
      }
    }else {
    alert('Please enter a phone number');
    phone.focus();
    return false;
  }
  return true;
}

// Validate no numbers
function validateparam(param){
  var paternnumber = /[0-9]/
  var result = paternnumber.test(param.value);
  if (result) {
    param.value="";
	param.focus();
	return false;
  }
  return true;
}



//Validate name and surname
function validatenamesurname(name, surname){
  var paternnumber = /[0-9]/
  if (name!=null){
    var resultname = paternnumber.test(name.value);
    if (name.value.length!=0) {
      if (resultname) {
	    alert('The field "forename" should not contain numbers');
	    name.value="";
	    name.focus();
	    return false;
      } 
    } else {
	  alert("Please enter your forename");
	  name.value="";
	  name.focus();
	  return false;
    }  
  }
  if (surname!=null){
    var resultsurname = paternnumber.test(surname.value);
    if (surname.value.length!=0) {
	  if (resultsurname){
	    alert('The field "surname" should not contain numbers');
	    surname.value="";
	    surname.focus();
	    return false;
	  }
	} else {
	  alert("Please enter your surname");
	  surname.focus();
	  return false;
	}
  }
  return true;
} 



// Validate an account number

function validatecardnumber(AccountNumber){
  if (AccountNumber.value.length!=0) {
    dotaccount = AccountNumber.value.lastIndexOf('.');
    if(isNaN(AccountNumber.value) || AccountNumber.value<0 || AccountNumber.value.length!=16 || dotaccount !=-1){
      AccountNumber.value="";
      AccountNumber.focus();
      return false;
    } 
  }
  return true;
}



//Checkout Address function duplication
function selectAddressType(type) {

	switch (type) {
		case "invoice":
			hide("OldAddress");
			show("NewAddress");
			document.AddressForm.nextAction.value = 'addInvoice';
			var messageDiv = document.getElementById('newMessage');
			messageDiv.innerHTML = 'New Invoice Address';
			document.AddressForm.useBillingAddress.checked 		= false;
			document.AddressForm.DeliveryAddressSelect.disabled = false;
			document.AddressForm.InvoiceAddressSelect.options[0].selected = true;
			//update the action so we can create a new address
			//document.AddressForm.action ='AddressAdd';
			//strip the address id so we can create one
			//FIXME
			//document.AddressForm.addressId.parentNode.removeChild(document.AddressForm.addressId);

			//update the URL so we come back to this page when we've created the new address
			document.AddressForm.URL.value='OrderItemUpdate?URL=SingleShippingAddressView?orderItemId*=&quantity*=';

			break;

		case "delivery":
			hide("OldAddress");
			show("NewAddress");
			var messageDiv = document.getElementById('newMessage');
			messageDiv.innerHTML = 'New Delivery Address';
			document.AddressForm.nextAction.value = 'addDelivery';
			document.AddressForm.useBillingAddress.checked 		= false;
			document.AddressForm.DeliveryAddressSelect.disabled = false;
			document.AddressForm.DeliveryAddressSelect.options[0].selected = true;
			//update the action so we can create a new address
			//document.AddressForm.action ='AddressAdd';
			//strip the address id so we can create one

			//document.AddressForm.addressId.parentNode.removeChild(document.AddressForm.addressId);

			//update the URL so we come back to this page when we've created the new address
			document.AddressForm.URL.value='OrderItemUpdate?URL=SingleShippingAddressView?orderItemId*=&quantity*=';
			break;

		case "both":
			if(document.AddressForm.useBillingAddress.checked == true){

				document.AddressForm.DeliveryAddressSelect.disabled = true;
			} else {

				document.AddressForm.useBillingAddress.checked 		= false;
				document.AddressForm.DeliveryAddressSelect.disabled = false;
			}
			break;
	}


}

function categoryChange(thisFormName){
	thisFormName.categoryList.value = thisFormName.WCParamCategoryList.value +","+ thisFormName.categoryId.value;
	thisFormName.submit();
}

function addressChange(selectbox){
	var addressType;

	//update the URL so we come back to this page when we've updated the addresses using the drop downs.
	document.AddressForm.URL.value='OrderItemUpdate?URL=SingleShippingAddressView?orderItemId*=&quantity*=';

	//Find out which select box changed
	switch (selectbox.id) {
		case "InvoiceAddressSelect":
		addressType = "Invoice";
		document.AddressForm.nextAction.value = 'displayInvoice';
		document.AddressForm.action = 'OrderSaveAddresses';
		break;

		case "DeliveryAddressSelect":
		addressType = "Delivery";
		document.AddressForm.nextAction.value = 'displayDelivery';
		document.AddressForm.action = 'OrderSaveAddresses';
		break;
	}

	//Compose the address string
	if(selectbox.value != "-23") {
		document.AddressForm.submit();
	}
}

//This is the Shipping Address form onsubmit handler.
function validateAddressForm() {
		
		if (document.AddressForm.nextAction.value.match("add") != null)
		{
	
			//we have the creation form, ready to submit it.
			if (validateCreateAddressForm(document.AddressForm))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	    else if (document.AddressForm.shipInstructions_.value == "") {
		alert("To assist with deliveries during school holidays please indicate opening times on all orders. If this is not applicable, please enter N/A");
		return false;
	}
		return true;

}

function validateShippingForm() {
	if (document.AddressForm.shipInstructions_.value == "") {
		alert("To assist with deliveries during school holidays please indicate opening times on all orders. If this is not applicable, please enter N/A");
		return false;
	} else {
		if (document.AddressForm.nextAction.value.match("add") != null)
		{
	
			//we have the creation form, ready to submit it.
			if (validateCreateAddressForm(document.AddressForm))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	
		return true;
	}

}

//Validate the create address form
function validateCreateAddressForm(thisform){
	with (thisform){

		if(thisform.name=="EmailForm"){
			if (validate_email(email1,"Not a valid e-mail address!")==false){
				email1.focus();
				return false
			}
		}
		else if(thisform.name=="PasswordForm"){
			if (LogonPassword.value==""){
				alert("Please enter your current password");
				LogonPassword.focus();
				return false
			}
			if (NewLogonPassword.value==""){
				alert("Please enter your new current password");
				NewLogonPassword.focus();
				return false
			}
			if (NewLogonPasswordVerify.value==""){
				alert("Please confirm your new password");
				NewLogonPasswordVerify.focus();
				return false
			}
			if (NewLogonPasswordVerify.value!=NewLogonPassword.value){
				alert("Your new password and the confirmation do not match");
				NewLogonPasswordVerify.focus();
				return false
			}
		}
		else if(thisform.name=="AddressForm" || thisform.name=="DeliveryForm" || thisform.name=="ShipAddressForm"){


			if (nickName.value=='' || nickName.value=='e.g. John Home Address' ){
				alert('Please enter your easily identifable address name in the Address Name field.');
				nickName.value='';
				nickName.focus();
				return false
			}
            trimer(nickName);
			trimer(firstName);
			trimer(lastName);
			trimer(company);
			trimall(phone1);
			trimer(address1);
			trimer(address2);
			trimer(City);
			trimer(County);
			trimer(ZipCode);
			trimer(Country);
			if (personTitle.value==-23){
				alert("Please select your title");
				personTitle.focus();
				return false
			}
			if (validatenamesurname(firstName, lastName)==false){
			  return false;
			}
			if (company.value==""){
				alert("Please enter your Company/Establishment");
				company.focus();
				return false
			} 
			if (phone1.value==""){
				alert("Please enter your contact telephone number");
				phone1.focus();
				return false;
			} else {	
			  if(validatephonefax(phone1, null)==false){
			    return false;
			  }
            }
			if (address1.value==""){
				alert("Please enter your building name or number");
				address1.focus();
				return false
			}
			if (address2.value==""){
				alert("Please enter the first line of your address");
				address2.focus();
				return false
			}
			if (City.value==""){
				alert("Please enter your city");
				City.focus();
				return false
			}
			if (validateparam(City)==false){
			   alert('The field "City" should not contain numbers');
			   return false;
			}						
			if (County.value==""){
				alert("Please enter your county");
				County.focus();
				return false
			}
			if (validateparam(County)==false){
			   alert('The field "county" should not contain numbers');
			   return false;
			}			
			if (ZipCode.value==""){
				alert("Please enter your postcode");
				ZipCode.focus();
				return false
			}
			if (Country.value==-23){
				alert("Please select your country");
				Country.focus();
				return false
			}


			var useStatus = document.getElementById('useBillingAddress').checked;
			var newDeli = document.getElementById('savedNewDelivery2').checked;

			if(useStatus == false && newDeli == true){
					//Delivery side
					if (DeliveryTitle.value==-23){
						alert("Please select your title");
						DeliveryTitle.focus();
						return false
					}
					if (DeliveryFirstName.value==""){
						alert("Please enter your forename..");
						DeliveryFirstName.focus();
						return false
					}
					if (DeliveryLastName.value==""){
						alert("Please enter your surname");
						DeliveryLastName.focus();
						return false
					}
					if (DeliveryBuilding.value==""){
						alert("Please enter your building name or number");
						DeliveryBuilding.focus();
						return false
					}
					if (DeliveryAddress1.value==""){
						alert("Please enter the first line of your address");
						DeliveryAddress1.focus();
						return false
					}
					if (DeliveryCity.value==""){
						alert("Please enter your city");
						DeliveryCity.focus();
						return false
					}
					if (DeliveryCounty.value==""){
						alert("Please enter your county");
						DeliveryCounty.focus();
						return false
					}
					if (DeliveryZipCode.value==""){
						alert("Please enter your postcode");
						DeliveryZipCode.focus();
						return false
					}
					if (DeliveryCountry.value==-23){
						alert("Please select your country");
						DeliveryCountry.focus();
						return false
					}
			}


		}
	}
}


function validateInteger(intToCheck,alertTxt){
	if(isNaN(intToCheck.value)){
		alert(alertTxt);
	}
}

//Validates product code feild and submits form.
function basicValidate(thisFormName, thisElementID,alertTxt) {


	//##debug##
	//alert(thisFormName + ' \n' + thisElementID);

	if(document.getElementById(thisElementID).value==""){
		alert(alertTxt);
		document.getElementById(thisElementID).focus();
		return false
	}

	document.getElementById(thisFormName).submit();

}


/*window.onload = function() {
	alert("running");
	(document.all && !window.print) ? null : setButtons();
}
function setButtons() {
	alert("setting buttons");
	var butts = document.getElementsByTagName('input');
	for (var i = 0; i < butts.length; i++) {
		if (i.className == "button"	) {
			alert("button");
		}
	}
}*/