// External JavaScript Resource for InmoUnidas.com
// Last modified 04MAY2002 by Julian Madle

function FSfncValidateEmailAddress(FormField,TheMessage,CheckTLD) {
	// CheckTLD is optional, it accepts values of true, false, and null.
	emailStr = FormField.value.toLowerCase()
	if (CheckTLD==null) {CheckTLD=true}
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|co|uk)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {alert(TheMessage); FormField.focus(); FormField.focus(); return false}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {if (user.charCodeAt(i)>127) {alert(TheMessage); return false}}
	for (i=0; i<domain.length; i++) {if (domain.charCodeAt(i)>127) {alert(TheMessage); FormField.focus(); return false}}
	if (user.match(userPat)==null) {alert(TheMessage); FormField.focus(); return false}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {for (var i=1;i<=4;i++) {if (IPArray[i]>255) {alert(TheMessage); FormField.focus(); return false}}; return true}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) {alert(TheMessage); FormField.focus(); return false}}
	if ((CheckTLD) && (domArr[domArr.length-1].length!=2) && (domArr[domArr.length-1].search(knownDomsPat)==-1)) {alert(TheMessage); FormField.focus(); return false}
	if (len<2) {alert(TheMessage); FormField.focus(); return false}
	return true;
	}

function ReadCookie (key, skips) {
	if (skips == null) {skips = 0}
	var cookie_string = '' + document . cookie;
	var cookie_array = cookie_string . split ('; ');
	for (var i = 0; i < cookie_array . length; ++ i) {
		var single_cookie = cookie_array [i] . split ('=');
		if (single_cookie . length != 2) {continue}
		var name  = unescape (single_cookie [0]);
		var value = unescape (single_cookie [1]);
		if (key == name && skips -- == 0) {return value}
		}
	return 'None';
	}

function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + '=' + escape (value) +
		((expires == null) ? '' : ('; expires=' + expires.toGMTString())) +
		((path == null) ? '' : ('; path=' + path)) +
		((domain == null) ? '' : ('; domain=.oneclickhr-systems.com')) +
		((secure == true) ? '; secure' : '');
	}

function checkCommonForm(formRef, checkName) {
	if ((checkName=true) && (formRef.ContactName.value=="")) {alert("Please enter your name");formRef.ContactName.focus();return false}
	if (emailCheck(formRef.ContactEmailAddress.value)==false) {formRef.ContactEmailAddress.focus();return false}
	return true;
	}

function emailCheck (emailStr) {
	emailStr = emailStr.toLowerCase(); // Validate email address
	var checkTLD=1; // Verify that the address ends in a two-letter country or well-known TLD.  1 means check it, 0 means don't.
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|co|uk)$/; // Known TLDs that an e-mail address must end with.
	var emailPat=/^(.+)@(.+)$/; // Pattern to check if the entered e-mail address fits the user@domain format, also used to separate the username from the domain.
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; // Pattern for matching all special characters. Do not allow special characters in address. These include ( ) < > @ , ; : \ " . [ ]
	var validChars="\[^\\s" + specialChars + "\]"; //Range of characters allowed in username or domainname (really states which chars aren't allowed).
	var quotedUser="(\"[^\"]*\")"; // Pattern applies if "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't).  E.g. "jiminy cricket"@disney.com is a legal e-mail address.
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; // Pattern applies for domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal e-mail address (square brackets are required).
	var atom=validChars + '+'; // Represents an atom (basically a series of non-special characters).
	var word="(" + atom + "|" + quotedUser + ")"; // Represents one word in the typical username. Eg. in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string.
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); // Pattern describes the structure of the user
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); // Pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above.

	// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		// Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address.
		alert("The Email address you entered seems incorrect (check @ and .'s)");
		return false;
		}
	var user=matchArray[1];
	var domain=matchArray[2];
	// Check that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {if (user.charCodeAt(i)>127) {alert("The username you entered contains invalid characters. Please try again.");return false}}
	for (i=0; i<domain.length; i++) {if (domain.charCodeAt(i)>127) {alert("The domain name you entered contains invalid characters. Please try again.");return false}}
	// See if "user" is valid
	if (user.match(userPat)==null) {alert("The username you entered doesn't seem to be valid.");return false}
	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {if (IPArray[i]>255) {alert("Destination IP address is invalid!");return false}}
		return true;
		}
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {if (domArr[i].search(atomPat)==-1) {alert("The domain name does not seem to be valid.");return false}}
	// Make sure domain name ends in a known top-level domain or a two-letter word representing country (uk, nl)
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {alert("The email address you enter must end in a well-known domain or two letter " + "country.");return false}
	// Make sure there's a host name preceding the domain.
	if (len<2) {alert("This address is missing a hostname!");return false}
	// Email address is valid!
	return true;
	}
	
function swapPhoto(PHID,ImgWidth,ImgHeight,ImgFolder) {
	if (document.getElementById) {
		var Photo=document.getElementById("MainPhoto")
		if (Photo.filters) {Photo.filters.blendTrans.Apply()}
		Photo.src=ImgFolder + "/fullsize/" + PHID + ".jpg";
		Photo.width=ImgWidth;
		Photo.height=ImgHeight;
		if (Photo.filters) {Photo.filters.blendTrans.play()}
		//if (document.getElementById("PhotoBrowser")) {document.getElementById("PhotoBrowser").style.width=(ImgWidth<300 ? "300px" : ImgWidth + "px")}
		if (document.getElementById("MainPhotoToggle")) {document.getElementById("MainPhotoToggle").style.display="block"}
		}
	}

function removeOptions(SelectRef) {SelectRef.options.length=0}

function addOption(SelectRef,TheText,TheValue) {SelectRef.options[SelectRef.options.length] = new Option(TheText,TheValue)}

function StockObject(STID,OriginalPrice,OriginalPriceIncl,CurrentPrice,CurrentPriceIncl,FromAge,ToAge,Label,LabelUS,ClientLabel,ListItem,ClientLabel2,ListItem2,StockDays,LEID1,LEID2,DefaultLEID1,DefaultLEID2) {
	this.STID=STID;
	this.OriginalPrice=OriginalPrice;
	this.OriginalPriceIncl=OriginalPriceIncl;
	this.CurrentPrice=CurrentPrice;
	this.CurrentPriceIncl=CurrentPriceIncl;
	if (FromAge!="") {this.FromAge=parseInt(FromAge)}
	if (ToAge!="") {this.ToAge=parseInt(ToAge)}
	this.Label=Label;
	this.LabelUS=LabelUS;
	this.ClientLabel=ClientLabel;
	this.ListItem=ListItem;
	this.ClientLabel2=ClientLabel2;
	this.ListItem2=ListItem2;
	this.StockDays=StockDays;
	this.LEID1=LEID1;
	this.LEID2=LEID2;
	this.DefaultLEID1=DefaultLEID1;
	this.DefaultLEID2=DefaultLEID2;
	}

function locateStockItem(STID) {for (var i=0; i<ProductArray.length; i++) {if (STID==ProductArray[i].STID) {return ProductArray[i]}}}

function setupProduct() {
	if (document.BuyForm) {
		if (RequiresJS) {
			if (HasSizes) {populateSize()}
			else if (HasOptions) {populateOption1()}
			else if (HasOptions2) {populateOption2()}
			}
		else {showPrices(ProductArray[0])}
		}
	}

function makeAgeDisplay(ProductItem) {
	var thisLabel,thisUnit;
	if ((Region=="US") && (ProductItem.LabelUS!="")) {thisLabel=ProductItem.LabelUS} else {thisLabel=ProductItem.Label}
	if (thisLabel!="") {return thisLabel}
	// Special cases
	if (ProductItem.FromAge<1) {
		switch (ProductItem.FromAge) {
			case -2 : return "Premature 3-5 lbs";
			case -1 : return "Small Baby 5-8 lbs";
			case 0 : return "Newborn"; break;
			}
		}
	// Set from age
	if (ProductItem.FromAge<24) {thisLabel=ProductItem.FromAge; thisUnit=" months"}
	else {thisLabel=(Math.floor(ProductItem.FromAge / 12)); thisUnit=" years"}
	// Set to age
	if ((ProductItem.ToAge<24) || (thisUnit==" months")) {if (ProductItem.ToAge>ProductItem.FromAge) {thisLabel=thisLabel + " - " + ProductItem.ToAge}}
	else {if (Math.floor(ProductItem.ToAge / 12)>thisLabel) {thisLabel=thisLabel + " - " + (Math.floor(ProductItem.ToAge / 12))}}
	return thisLabel + thisUnit;
	}

function showPrices(StockItem) {
	if (document.getElementById) {
		var ThePriceField=document.getElementById("PriceField");
		if (StockItem.CurrentPrice!=StockItem.OriginalPrice) {ThePriceField.innerHTML="<NOBR>was " + formatPrice(StockItem.OriginalPrice, StockItem.OriginalPriceIncl) + "</NOBR> <NOBR><B>now " + formatPrice(StockItem.CurrentPrice, StockItem.CurrentPriceIncl) + "</B></NOBR>"}
		else {ThePriceField.innerHTML="<B>" + formatPrice(StockItem.CurrentPrice, StockItem.CurrentPriceIncl) + "</B>"}
		if (document.getElementById("LeadTimeField")) {
			strExtrMsg="";
			if ((StockItem.StockDays!="") && (parseInt(StockItem.StockDays)>0)) {
				StockDays=parseInt(StockItem.StockDays) + parseInt(ProductDays);
				if (parseInt(StockItem.StockDays)>10) {strExtrMsg="<DIV STYLE='color:red; font-size:11px'>Order now and we'll ship<BR>when it's back in stock</DIV"}
				}
			else {StockDays=ProductDays}
			document.getElementById("LeadTimeField").innerHTML=(StockDays<=1) ? "24 hours" : "Within " + StockDays + " days" + strExtrMsg;
			document.BuyForm.LeadTime.value=StockDays;
			}
		}
	}

function formatPrice(Price,PriceIncl) {
	switch (Region) {
		case "US" : return SymbolUS + Round(Price * RateUS, 2);
		case "ROW" : return SymbolWorld + Round(Price * RateWorld,2);
		case "Euro" : return SymbolEuro + Round(PriceIncl * RateEuro,2);
		default : return SymbolUK + Round(PriceIncl,2);
		}
	}

function Round(Number,DecimalPlaces) {
	var Rounded=(Math.round(Number * Math.pow(10,DecimalPlaces)) / Math.pow(10,DecimalPlaces)).toString();
	switch (Rounded.indexOf(".")) {
		case -1 : return Rounded + ".00";
		case Rounded.length - 2 : return Rounded + "0";
		default : return Rounded
		}
return Rounded
	}

function changeRegion(FieldRef) {Region=FieldRef[FieldRef.selectedIndex].value; showPrices(locateStockItem(FieldRef.form.STID.value))}

function populateSize() {
	var thisLabel,lastLabel;
	var ThisSelected=0;
	removeOptions(document.BuyForm.ItemSize);
	for (var i=0; i<ProductArray.length; i++) {
		thisLabel=makeAgeDisplay(ProductArray[i]);
		if (lastLabel!=thisLabel) {lastLabel=thisLabel; addOption(document.BuyForm.ItemSize,thisLabel,ProductArray[i].STID)}
		if ((SearchSize!="") && (SearchSize>=ProductArray[i].FromAge) && (SearchSize<=ProductArray[i].ToAge)) {ThisSelected=document.BuyForm.ItemSize.options.length - 1}
		}
	document.BuyForm.ItemSize.selectedIndex=ThisSelected;
	sizeChanged(document.BuyForm.ItemSize);
	}

function populateOption1() {
	var thisLabel,lastLabel;
	removeOptions(document.BuyForm.ItemOption);
	var SelectedIndex=0;
	for (var i=0; i<ProductArray.length; i++) {
		if (((HasSizes) && (makeAgeDisplay(ProductArray[i])==CurrentSize)) || (!HasSizes)) {
			thisLabel=ProductArray[i].ListItem;
			if (ProductArray[i].LEID1==ProductArray[i].DefaultLEID1) {SelectedIndex=document.BuyForm.ItemOption.length}
			if (lastLabel!=thisLabel) {lastLabel=thisLabel; addOption(document.BuyForm.ItemOption,thisLabel,ProductArray[i].STID)}
			}
		}
	document.BuyForm.ItemOption.selectedIndex=SelectedIndex;
	option1Changed(document.BuyForm.ItemOption);
	}

function populateOption2() {
	var thisLabel,lastLabel;
	removeOptions(document.BuyForm.ItemOption2);
	var SelectedIndex=0;
	for (var i=0; i<ProductArray.length; i++) {
		if (((HasSizes) && (makeAgeDisplay(ProductArray[i])==CurrentSize)) || (!HasSizes)) {
			if (((HasOptions) && (ProductArray[i].ListItem==CurrentOption)) || (!HasOptions)) {
				thisLabel=ProductArray[i].ListItem2;
				if (ProductArray[i].LEID2==ProductArray[i].DefaultLEID2) {SelectedIndex=document.BuyForm.ItemOption2.length}
				if (lastLabel!=thisLabel) {lastLabel=thisLabel; addOption(document.BuyForm.ItemOption2,thisLabel,ProductArray[i].STID)}
				}
			}
		}
	document.BuyForm.ItemOption2.selectedIndex=SelectedIndex;
	option2Changed(document.BuyForm.ItemOption2);
	}

function sizeChanged(FieldRef) {
	FieldRef.form.STID.value=FieldRef[FieldRef.selectedIndex].value;
	CurrentSize=FieldRef[FieldRef.selectedIndex].text;
	if (HasOptions) {populateOption1()}
	else if (HasOptions2) {populateOption2()}
	else {showPrices(locateStockItem(FieldRef.form.STID.value))}
	}

function option1Changed(FieldRef) {
	FieldRef.form.STID.value=FieldRef[FieldRef.selectedIndex].value;
	CurrentOption=FieldRef[FieldRef.selectedIndex].text;
	if (HasOptions2) {populateOption2()}
	else {showPrices(locateStockItem(FieldRef.form.STID.value))}
	}

function option2Changed(FieldRef) {
	FieldRef.form.STID.value=FieldRef[FieldRef.selectedIndex].value;
	showPrices(locateStockItem(FieldRef.form.STID.value));
	}

function setupRange() {
	if (document.AddForm.STIDlist) {for (var i=0; i<document.AddForm.STIDlist.length; i++) {document.AddForm.STIDlist[i].checked=false}}
	}

function setStockAndPrice(RangeItem,RolldownRef,CheckboxNumber) {
	var itemData=RolldownRef[RolldownRef.selectedIndex].value.split("::");
	if (document.getElementById) {
		//document.getElementById("PriceCell_" + RangeItem).innerHTML=RolldownRef[RolldownRef.selectedIndex].value.substring(RolldownRef[RolldownRef.selectedIndex].value.indexOf("::") + 2,RolldownRef[RolldownRef.selectedIndex].value.length);
		document.getElementById("PriceCell_" + RangeItem).innerHTML=itemData[1];
		document.getElementById("DispatchCell_" + RangeItem).innerHTML=itemData[2];
		}
	RolldownRef.form.STIDlist[CheckboxNumber].value=itemData[0];
	}

function checkRangeForm(FormRef) {
	var SelectedPID=0;
	var ProductRow=0;
	var SomethingChecked=false;
	var PrimarySelected=false;
	if (FormRef.STIDlist) {
		for (var i=0; i<FormRef.length; i++) {
			if (FormRef.elements[i].name=="STIDlist") {
				if (FormRef.elements[i].checked==true) {
					SelectedPID=FormRef["PID_" + ProductRow].value;
					for (var j=0; j<PrimaryIDs.length; j++) {
						// Check whether a primary is ticked
						if (SelectedPID==PrimaryIDs[j]) {PrimarySelected=true}
						// Check whether a primary is already in basket
						for (var k=0; k<BasketIDs.length; k++) {if (PrimaryIDs[j]==BasketIDs[j]) {PrimarySelected=true}}
						}
					}
				ProductRow++;
				}
			}
		if (PrimarySelected) {FormRef.submit()}
		else if (SelectedPID>0) {alert("This product cannot be purchased on its own")}
		else {alert("Please tick the boxes for products you would like to purchase")}
		}
	}

