// JavaScript version of html_entity_decode()
function htmlEntityDecode(str) {
	var ta = document.createElement('textarea');
	ta.innerHTML = str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	return ta.value;
}

// shopping javacript
function confirmBuy(itemForm, mode) {
	var prMessage = requiredProperty;
	if (mode == 'old') {
		var confirmationMessage = addProductOld;
	} else {
		var confirmationMessage = addProduct;
	}
	var mrgPropertySet = false;
	var emptyOptions = '';
	var prIDs = '';
	if (itemForm.properties) {
		prIDs = itemForm.properties.value;
	}
	if (prIDs != '') {
		var properties = prIDs.split(',');
		var productName = itemForm.elements['item_name'].value;
		for (var i = 0; i < properties.length; i++) {
			var prID = properties[i];
			var mrgPrPos = prID.indexOf('mrg_');
			var propertyName = itemForm.elements['property_name_' + prID].value;
			var prRequired = itemForm.elements['property_required_' + prID].value;
			if (prRequired == 1 || mrgPrPos > 0) {
				var prValue = '';
				var prControl = itemForm.elements['property_control_' + prID].value;
				if (prControl == 'LISTBOX') {
					prValue = itemForm.elements['property_' + prID].options[itemForm.elements['property_' + prID].selectedIndex].value;
				} else if (prControl == 'RADIOBUTTON') {
					var radioControl = itemForm.elements['property_' + prID];
					if (radioControl.length) {
						for (var ri = 0; ri < radioControl.length; ri++) {
							if (radioControl[ri].checked) {
								prValue = radioControl[ri].value;
								break;
							}
						}
					} else {
						if (radioControl.checked) {
							prValue = radioControl.value;
						}
					}
				} else if (prControl == 'CHECKBOXLIST') {
					if (itemForm.elements['property_total_' + prID]) {
						var totalOptions = parseInt(itemForm.elements['property_total_' + prID].value);
						for (var ci = 1; ci <= totalOptions; ci++) {
							if (itemForm.elements['property_' + prID + '_' + ci].checked) {
								prValue = 1;
								break;
							}
						}
					}
				// *** Begin code added by Oliver Pereira, Wed 27/05/2009 ***
				} else if (prControl == 'CHECKBOX_AGREE') {
					if (itemForm.elements['property_' + prID]) {
						if (itemForm.elements['property_' + prID + '_1'].checked) {
							prValue = 'Yes';
						} else {
							prValue = 'No';
						}
					}
				// *** End code added by Oliver Pereira, Wed 27/05/2009 ***
				} else {
					prValue = itemForm.elements['property_' + prID].value;
				}
				// Check whether the property is empty.
				if (prValue == '') {
					// Check whether the property is required.
					if (prRequired == 1) {
						prMessage = prMessage.replace('{property_name}', propertyName);
						prMessage = prMessage.replace('{product_name}', productName);
						alert(prMessage);
						if (prControl != 'RADIOBUTTON' && prControl != 'CHECKBOXLIST') {
							// Additional checking added by Oliver Pereira, Fri 07/11/2008
							if (itemForm.elements['property_' + prID].style.visibility != 'hidden') {
								itemForm.elements['property_' + prID].focus();
							}
						}
						clearMergedDataFields(itemForm);
						return false;
					} else {
						// The property is not required, but we want to
						// warn the customer that it is empty anyway.
						// (New code by Oliver Pereira, Tue 22/09/2009.)
						if (emptyOptions != '') {
							emptyOptions += ', ';
						}
						emptyOptions += propertyName;
					}
				}
			}
			// Update the merged data field, if there is one.
			if (mrgPrPos > 0) {
				var mrgPrID = prID.substr(0, mrgPrPos - 1);
				var mrgProperty = document.getElementById('property_' + mrgPrID);
				// *** Begin code added by Oliver Pereira, Fri 27/03/2009 ***
				// Get the value that we want to add to the merged data field.
				var strValue = '';
				if (prControl == 'LISTBOX') {
					var propertyElement = document.getElementById('property_' + prID);
					if (propertyElement != null) {
						var optionID = propertyElement.value;
						var optionElement = document.getElementById('option_' + optionID);
						if (optionElement != null) {
							strValue = optionElement.innerHTML;
						}
					}
				} else {
					// Get the value that the ViArt code has already worked out.
					strValue = prValue;
				}
				// To do: Work out how to deal with checkboxes and text areas, if necessary.
				// *** End code added by Oliver Pereira, Fri 27/03/2009 ***

				// Update the value in the hidden field.
				if (mrgProperty.value != '') {
					// Use the bar character to separate this option from the last.
					mrgProperty.value += '|';
				}
				// Just remove all bar characters from the option value.
				// (To do: escape the bar characters properly!)
				mrgProperty.value += propertyName + ': ' + strValue.replace('|', '');
				mrgPropertySet = true;
			}
		}
	}

	if (mode != 'old' && !mrgPropertySet) {
		alert('Sorry, your browser seems to be using an old or cut-down version of JavaScript that this website does not support. Please phone us on 01245 363131 for assistance.');
		return false;
	}

	if (emptyOptions != '') {
		confirmationMessage = 'The following optional fields are blank: ' + emptyOptions + '. If you don\'t want them to appear blank, please cancel this message and fill them in.' + "\n\n" + confirmationMessage;
	}

	if (confirmAdd == '1') {
		var confirmation = confirm(confirmationMessage);
		if (!confirmation) {
			clearMergedDataFields(itemForm);
		}
		return confirmation;
	} else {
		return true;
	}
}

function changeProperty(itemForm) {
	var priceControl = '';
	var htmlControl = false;
	var prIDs = '';
	var itemId = '';
	var priceEdit = 0;
	var taxPercent = 0;
	var taxPrices = 1;
	if (itemForm.pe) {
		priceEdit = itemForm.pe.value;
		if (priceEdit == '1') {
			return;
		}
	}
	if (itemForm.tax_percent && itemForm.tax_percent.value != '') {
		taxPercent = parseFloat(itemForm.tax_percent.value);
		if (isNaN(taxPercent)) { taxPercent = 0; }
	}
	if (itemForm.tax_prices && itemForm.tax_prices.value != '') {
		taxPrices = parseFloat(itemForm.tax_prices.value);
		if (isNaN(taxPrices)) { taxPrices = 1; }
	}
	if (itemForm.add_id) {
		itemId = itemForm.add_id.value;
	} else if (itemForm.item_id) {
		itemId = itemForm.item_id.value;
	}
	if (itemForm.sales_price) {
		priceControl = itemForm.sales_price;
	} else if (itemForm.price) {
		priceControl = itemForm.price;
	} else if (itemId != '' && document.getElementById) {
		htmlControl = true;
		priceControl = document.getElementById('sales_price_' + itemId);
		if (!priceControl) {
			priceControl = document.getElementById('price_' + itemId);
		}
	} 

	var totalAdditionalPrice = 0;
	if (itemForm.properties) {
		prIDs = itemForm.properties.value;
	}
	if (prIDs != '') {
		var properties = prIDs.split(',');
		for (var i = 0; i < properties.length; i++) {
			var prID = properties[i];
			var prValue = '';
			var additionalPrice = 0;
			var prControl = itemForm.elements['property_control_' + prID].value;
			if (prControl == 'LISTBOX') {
				prValue = itemForm.elements['property_' + prID].options[itemForm.elements['property_' + prID].selectedIndex].value;
			} else if (prControl == 'RADIOBUTTON') {
				var radioControl = itemForm.elements['property_' + prID];
				if (radioControl.length) {
					for (var ri = 0; ri < radioControl.length; ri++) {
						if (radioControl[ri].checked) {
							prValue = radioControl[ri].value;
							break;
						}
					}
				} else {
					if (radioControl.checked) {
						prValue = radioControl.value;
					}
				}
			} else if (prControl == 'CHECKBOXLIST') {
				if (itemForm.elements['property_total_' + prID]) {
					var totalOptions = parseInt(itemForm.elements['property_total_' + prID].value);
					for (var ci = 1; ci <= totalOptions; ci++) {
						if (itemForm.elements['property_' + prID + '_' + ci].checked) {
							var checkedValue = itemForm.elements['property_' + prID + '_' + ci].value;
							if (itemForm.elements['option_price_' + checkedValue]) {
								var checkedPrice = parseFloat(itemForm.elements['option_price_' + checkedValue].value);
								if (!isNaN(checkedPrice) && checkedPrice!= 0) {
									additionalPrice += parseFloat(checkedPrice);
								}
							} 
						}
					}
				} 
			}
			if (prValue != '') {
				if (itemForm.elements['option_price_' + prValue]) {
					var optionPrice = itemForm.elements['option_price_' + prValue].value;
					if (optionPrice != '') {
						additionalPrice = parseFloat(optionPrice);
					}
				}
			} 

			if (!isNaN(additionalPrice) && additionalPrice != 0) {
				totalAdditionalPrice += additionalPrice;
			}
		}
	}

	if (itemForm.base_price) {
		var cl = ''; var cr = '';
		var basePrice = parseFloat(itemForm.base_price.value);
		if (itemForm.cl) { cl = itemForm.cl.value; }
		if (itemForm.cr) { cr = itemForm.cr.value; }
		var compPrice = 0; var compTax = 0;
		if (itemForm.comp_price && itemForm.comp_price.value != '') { 
			compPrice = parseFloat(itemForm.comp_price.value); 
		}
		if (itemForm.comp_tax && itemForm.comp_tax.value != '') { 
			compTax = parseFloat(itemForm.comp_tax.value); 
		}

		// check product quantity
		var quantity = 1;
		if (itemForm.quantity) {
			if (itemForm.quantity.selectedIndex) {
				quantity = parseInt(itemForm.quantity.options[itemForm.quantity.selectedIndex].value);
			} else {
				quantity = parseInt(itemForm.quantity.value);
			}
			if (isNaN(quantity)) { quantity = 1; } 
		}
		if (itemForm.quantity_price) { 
			var prices = itemForm.quantity_price.value; 
			if (prices != '') {
				prices = prices.split(',');
				for (var p = 0; p < prices.length; p = p + 4) {
					var minQuantity = parseInt(prices[p]);
					var maxQuantity = parseInt(prices[p + 1]);
					if (quantity >= minQuantity && quantity <= maxQuantity) {
						basePrice = parseFloat(prices[p + 2]);
						var propertiesDiscount = parseFloat(prices[p + 3]);
						if (propertiesDiscount > 0) {
							totalAdditionalPrice -= (Math.round(totalAdditionalPrice * propertiesDiscount) / 100);
						}
						break;
					}
				}
			}
		}
		
		var price = basePrice + totalAdditionalPrice;
		var taxAmount = (Math.round(price * taxPercent) / 100); 
		var productPrice = price + compPrice;
		var taxPrice = Math.round((productPrice + taxAmount + compTax) * 100) / 100; 
		if (taxPrices == 2) {
			productPrice = taxPrice;
			taxPrice = price + compPrice;
		} else if (taxPrices == 3) {
			productPrice = taxPrice;
		}

		if (priceControl) {
			if (htmlControl) {
				priceControl.innerHTML = cl + formatNumber(productPrice) + cr;
			} else {
				priceControl.value = cl + formatNumber(productPrice) + cr;
			}
		}
		taxPriceControl = document.getElementById('tax_price_' + itemId);
		if (taxPriceControl) {
			taxPriceControl.innerHTML = cl + formatNumber(taxPrice) + cr;
		}

	}
}

function changeQuantity(itemForm) {
	changeProperty(itemForm);
}

function properyImageUpload(uploadUrl) {
	// I don't think this function is used any more,
	// as I have replaced it with imageUpload().
	// However, I won't delete this one, just in case.
	/*var uploadWin = window.open (uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=300,titlebar=yes'); */
	var uploadWin = window.open (uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=300,titlebar=no');
}

function imageUpload(uploadUrl) {
	var uploadWin = window.open(uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=440,height=330,titlebar=no');
	if (uploadWin == null) {
		alert('Upload Window could not be opened. Your browser may be blocking pop-ups. Please check, and make sure that pop-up windows are allowed, so that you can upload your images.');
	}
}

function selectDesign(selectDesignUrl) {
	var uploadWin = window.open(selectDesignUrl, 'selectDesignWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=970,height=600,titlebar=no');
	if (uploadWin == null) {
		alert('Design selection window could not be opened. Your browser may be blocking pop-ups. Please check, and make sure that pop-up windows are allowed, so that you can select your designs.');
	}
}

function selectPhoto(selectPhotoUrl) {
	var uploadWin = window.open(selectPhotoUrl, 'selectPhotoWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=970,height=600,titlebar=no');
	if (uploadWin == null) {
		alert('Photo selection window could not be opened. Your browser may be blocking pop-ups. Please check, and make sure that pop-up windows are allowed, so that you can select your designs.');
	}
}

function openPreviewWin(previewUrl, width, height) {
	var previewWin = window.open (previewUrl, 'previewWin', 'left=0,top=0,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height);
	previewWin.focus();
	return false;
}

function openSuperImage(imageUrl, width, height) {
	var scrollbars = 'no';
	// add margins to image size
	if (width > 0 && height > 0) {
		width += 30; height += 30;
	}
	// check available sizes
	var availableHeight = window.screen.availHeight - 60;
	var availableWidth = window.screen.availWidth - 20;
	if (isNaN(availableHeight)) { availableHeight = 520; } 
	if (isNaN(availableWidth)) { availableWidth = 760; } 
	if (height > availableHeight || height == 0) { 
		height = availableHeight;
		scrollbars = 'yes'; 
	}
	if (width > availableWidth || width == 0) {
		width = availableWidth;
		scrollbars = 'yes';
	}
	var superImageWin = window.open(imageUrl, 'superImageWin', 'left=0,top=0,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=' + scrollbars + ',resizable=yes,width=' + width + ',height=' + height);
	superImageWin.focus();
	return false;
}

function setFilePath(filepath, filetype, controlName, formId) {
	if (filepath != '' && controlName != '' && formId != '') {
		var formName = 'form_' + formId;
		document.forms[formName].elements[controlName].value = filepath;
		document.forms[formName].elements[controlName].focus();
	}
}


function formatNumber(numberValue) {
	var numberParts = '';
	var numberText = new String(numberValue);
	if (numberText.indexOf('.') == -1) {
		numberText += '.00';
	} else if (numberText.indexOf('.') == (numberText.length - 2)) {
		numberText += '0';
	} else {
		var numberParts = numberText.split('.');
		if (numberParts[1].length > 2) {
			numberText = numberParts[0] + '.' + numberParts[1].substring(0, 2);
		}
	}
	var numberLength = numberText.length;
	if (numberLength >= 10) {
		numberText = numberText.substring(0, numberLength - 9) + ',' + numberText.substring(numberLength - 9, numberLength - 6) + ',' + numberText.substring(numberLength - 6, numberLength);
	} else if (numberLength >= 7) {
		numberText = numberText.substring(0, numberLength - 6) + ',' + numberText.substring(numberLength - 6, numberLength);
	}
	return numberText;
}

// Function added by Oliver Pereira, Fri 13/02/2009 and updated on various later dates
function updateProperty(propertyID, valueNumber, previewVariableName, isFromViArt) {
	var strValue = '';
	if (document.getElementById) {
		var mrgPrPos = propertyID.indexOf('mrg_');
		var strFontColour;
		var controlElement = document.getElementById('property_control_' + propertyID);
		if (controlElement != null) {
			if (isFromViArt || mrgPrPos > 0) {
				// This is either a control that has either been generated by
				// ViArt in the normal way or a control generated from Oliver Pereira's
				// additional code whose value is to be added to a merged field.
				var propertyControlType = controlElement.value;
				if (propertyControlType == 'LISTBOX') {
					// Get the value that we want to send to the Flash preview.
					var propertyElement = document.getElementById('property_' + propertyID);
					if (propertyElement != null) {
						var optionID = propertyElement.value;
						var optionElement = document.getElementById('option_' + optionID);
						if (optionElement != null) {
							strValue = optionElement.innerHTML;
						}
					}
				} else if (propertyControlType == 'RADIOBUTTON' || propertyControlType == 'CHECKBOXLIST') {
					// Get the string that we want to send to the Flash preview.
					var propertyElement = document.getElementById('property_' + propertyID);
					if (propertyElement != null) {
						strValue = propertyElement.value; // value to be replaced, if possible
					}
					// Get the image location to send to the Flash preview object.
					var prvImgElement = document.getElementById('prv_img_' + propertyID + '_' + valueNumber);
					if (prvImgElement != null) {
						strValue = prvImgElement.value;
					}
					// Get the font colour to send to the Flash preview object.
					var prvFCrElement = document.getElementById('prv_fcr_' + propertyID + '_' + valueNumber);
					if (prvFCrElement != null) {
						strFontColour = prvFCrElement.value;
					}
				} else if (propertyControlType == 'CHECKBOX_AGREE') {
					// We don't need to send anything to the Flash preview.
					var propertyElement = document.getElementById('property_' + propertyID);
					if (propertyElement != null) {
						strValue = propertyElement.value; // value to be replaced, if possible
					}
				} else if (propertyControlType == 'TEXTBOX') {
					// Get the value that we want to send to the Flash preview.
					var valueElement = document.getElementById('property_' + propertyID);
					if (valueElement != null) {
						strValue = valueElement.value;
					}
				}
				// To do: Work out how to deal with checkboxes and
				// text areas, if necessary.
			} else {
				// This is a control generated by ViArt but then altered using
				// Oliver Pereira's additional code. (So far, these can only
				// be sets of radio buttons.)
				// Update the property.
				var sourceProperty = document.getElementById('property_' + propertyID + '_' + valueNumber);
				var targetProperty = document.getElementById('property_' + propertyID);
				if (sourceProperty != null && targetProperty != null) {
					targetProperty.value = sourceProperty.value;
				}
				// Get the value that we want to send to the Flash preview.
				valueElement = document.getElementById('prv_img_' + propertyID + '_' + valueNumber);
				if (valueElement != null) {
					strValue = valueElement.value;
				}
			}
		}
/*
		// Update the hidden property value field, if it exists.
		if (mrgPrPos > 0) {
			var valProperty = document.getElementById('value_' + propertyID);
			valProperty.value = strValue;
		}
*/
		// Update the Flash preview, if it exists.
		var flashObject;
		 if (navigator.appName.indexOf('Microsoft') != -1) {
             flashObject = document['preview'];
         } else {
             flashObject = document['preview'];
         }
		if (flashObject != null &&
				controlElement != null && propertyControlType != 'CHECKBOX_AGREE') {	
			if (strFontColour != null) {
				//alert('flashObject.updatePreview(' + previewVariableName + '=' + customEscape(strValue) + '&font_colour=' + strFontColour + ');'); // remove
				flashObject.updatePreview(previewVariableName + '=' + customEscape(strValue) + '&font_colour=' + strFontColour);
			} else {
				//alert('flashObject.updatePreview(' + previewVariableName + '=' + customEscape(strValue) + ');'); // remove
				flashObject.updatePreview(previewVariableName + '=' + customEscape(strValue));
			}
		}
		// Update the e-card object, if it exists.
		if (eCardObject != null) {
			eCardObject.update(previewVariableName, customEscape(strValue));
			if (strFontColour != null) {
				eCardObject.update('font_colour', strFontColour);
			}
		}
	} else {
		alert('Sorry, your browser seems to be using an old or cut-down version of JavaScript that this website does not support. Please phone us on 01245 363131 for assistance.');
	}
}

// Function added by Oliver Pereira, Thu 05/03/2009
function showProductsOfType(productTypeID) {
	if (document.getElementById) {
		var productTypeTDElement = document.getElementById('typ_' + productTypeID);
		var productTypeNameElement = productTypeTDElement.childNodes[0];
		var productTypeLabelElement = document.getElementById('product_type_name');
		if (productTypeNameElement != null && productTypeLabelElement != null) {
			productTypeLabelElement.innerHTML = productTypeNameElement.innerHTML;
		}
		var parentElement = document.getElementById('product_list');
		var childElements = parentElement.childNodes;
		var childElementsLength = childElements.length;
		var childElement, childElementIDPartsArray, currentProductTypeID;
		for (var i = 0; i < childElementsLength; i++) {
			childElement = childElements[i];
			if (childElement.id.substr(0, 4) == 'prd_') {
				childElementIDPartsArray = childElement.id.split('_');
				currentProductTypeID = childElementIDPartsArray[1];
				childElement.style.display =
						(currentProductTypeID == productTypeID ? '' : 'none');
			}
		}
	}
}

function toggleExtraDescription() {
	var fh = document.getElementById('extra_description_hidden').style;
	fh.display = (fh.display == '' ? 'block' : '');
	var fdtl = document.getElementById('extra_description_toggle_link');
	fdtl.innerHTML = (fdtl.innerHTML == 'Show additional details' ? 'Hide additional details' : 'Show additional details');
}

function clearMergedDataFields(itemForm) {
	// Clear all the merged data fields in the given form.
	var prIDs = '';
	if (itemForm.properties) {
		prIDs = itemForm.properties.value;
	}
	if (prIDs != '') {
		var properties = prIDs.split(',');
		for (var i = 0; i < properties.length; i++) {
			var prID = properties[i];
			var mrgPrPos = prID.indexOf('mrg_');
			var propertyName = itemForm.elements['property_name_' + prID].value;
			if (propertyName == 'Merged Options') {
				itemForm.elements['property_' + prID].value = '';
			}
		}
	}
}

// Function added by Oliver Pereira, Thu 30/04/2009
function customEscape(str) {
		// Replace the word "(Blank)".
		str = str.replace('(Blank)', '');

		// Do various other replacements. To do: Uncomment this, later.
		str = str.replace('%', '%'); //str = str.replace('%', '%25');
		str = str.replace('&', 'and'); //str = str.replace('&', '%26');
		str = str.replace('=', 'equals'); //str = str.replace('=', '%3D');
		str = str.replace('’', '\''); //str = str.replace('’', '%92');
		return str;
}

// Function to toggle the display of an element on a page
function toggleElementByID(elementID) {
	var elem, vis;
	if (document.getElementById) {
		// Standards-compliant
		elem = document.getElementById(elementID);
	} else if (document.all) {
		// Old versions of Internet Explorer
		elem = document.all[elementID];
	} else if (document.layers) {
		// Netscape Navigator 4
		elem = document.layers[elementID];
	}
	vis = elem.style;
	// If the style.display value is blank, try to work it out here.
	if (vis.display == '' && elem.offsetWidth != undefined && elem.offsetHeight != undefined) {
		vis.display = (elem.offsetWidth != 0 && elem.offsetHeight != 0) ? 'block' : 'none';
	}
	vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}
