// shopping javacript
function confirmBuy(itemForm) {
	return modifiedConfirmBuy(itemForm, addProduct);
}

function confirmFinishedUploading(itemForm) {
	return modifiedConfirmBuy(itemForm, finishedProduct);
}

function modifiedConfirmBuy(itemForm, confirmMessage) {

	var prMessage = requiredProperty;
	var bIsEmpty = basketIsEmpty;
	var prIDs = '';
	
	var CalendarType = '';
	// Validate any personal dates the user has entered.
	if (typeof(uses_calendar_dates) != 'undefined') {
		var eventErrors = validate_events(document.getElementsByName('property_56')[0].options[document.getElementsByName('property_56')[0].selectedIndex].text);
		if (eventErrors > 0) {
			return false;
		} else {
			// Merge all events into a single field so they can be recorded
			// in the ViArt database (or elsewhere).
			refresh_tb_all_events();
		}
	}
	
	// Check to make sure the basket is blank
	if (basketIsEmpty > 0) {
		alert('You can only process a single calendar in an order. Please complete this order before ordering another. Thank you.');
		return false;
	}
	
	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 prRequired = itemForm.elements['property_required_' + prID].value;
			
/*
			// Put in an extra part to make the start month required *if* the calendar type
			// is 'UPLOAD'. - Oliver Pereira, Thu 17/04/2008
			// Update: This bit is no longer required. - Oliver Pereira, Thu 06/11/2008
			if (itemForm.elements['property_name_' + prID].value == 'Start Month') {
				prRequired = (CalendarType == 'UPLOAD');
			}
*/
			
			// Put in an extra bit for the unbranded product options page only
			// that checks that the Order Number is two letters followed by numbers.
			// - Oliver Pereira, Tue 14/10/2008 and Wed 15/10/2008
			if (prID == 59) {
				orderNumber = itemForm.elements['property_59'].value;
				var propertyName = itemForm.elements['property_name_59'].value;
				var orderNumberPattern = new RegExp('^[A-Za-z][A-Za-z][0-9]+$');
				if (orderNumber == '') {
					prMessage = prMessage.replace("\{property_name\}", propertyName);
					prMessage = prMessage.replace("\{product_name\}", productName);
					alert(prMessage);
					itemForm.elements['property_59'].focus();
					return false;
				} else if (!orderNumberPattern.test(orderNumber)) {
					var orderNumberInvalidMessage = '{property_name} for {product_name} must be two letters followed by numbers.';
					orderNumberInvalidMessage = orderNumberInvalidMessage.replace("\{property_name\}", propertyName);
					orderNumberInvalidMessage = orderNumberInvalidMessage.replace("\{product_name\}", productName);
					alert(orderNumberInvalidMessage);
					itemForm.elements['property_59'].focus();
					return false;
				}
			}

/*
			// Put in an extra bit for the unbranded product options page only
			// that checks that the e-mail address is of a valid format.
			// Based on JavaScript code found on the following page:
			// http://www.webreference.com/js/column5/form.html
			// - Oliver Pereira, Tue 14/10/2008 and Wed 15/10/2008
			if (prID == 61) {
				var emailAddress = itemForm.elements['property_61'].value;
				if (emailAddress != '' && getEmailAddressError(emailAddress) != '') {
					alert('E-mail address appears to be of an invalid format. Please check it and try again.');
					itemForm.elements['property_61'].focus();
					return false;
				}
			}
*/

			if (prRequired == 1) {
				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 radioControlName = itemForm.elements['property_name_' + prID].value;
					
					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;
								if (prValue == 8 && radioControlName == 'Calendar Type') CalendarType = 'UPLOAD';
								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;
							}
						}
					} 
				} else {					
					prValue = itemForm.elements['property_' + prID].value;
				}
				if (prValue == '') {
					var propertyName = itemForm.elements['property_name_' + prID].value;
					prMessage = prMessage.replace("\{property_name\}", propertyName);
					prMessage = prMessage.replace("\{product_name\}", productName);
					alert(prMessage);
					if (prControl != 'RADIOBUTTON' && prControl != 'CHECKBOXLIST') {
						itemForm.elements['property_' + prID].focus();
					}
					return false;
				}
			}

/*
		if (CalendarType == 'UPLOAD') {
*/
			var imgUploadTest = itemForm.elements['property_control_' + prID].value;
				var prValue = itemForm.elements['property_' + prID].value;			
				if (imgUploadTest == 'IMAGEUPLOAD' && prValue == '') {
					alert('One or more months do not have images. Please fill all months with images.');
					return false;
				}	
			}
/*
		}
*/
	}

	if (confirmAdd == '1') {
		return confirm(confirmMessage);
	} 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 imageUpload(uploadUrl) {
	var uploadWin = window.open(uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=600,height=450,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 qImageUpload(uploadUrl) {
	var uploadWin = window.open(uploadUrl, 'uploadWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=600,height=450,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 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;
}


// Additional function- Michael Summers 27-06-08
// Edited by Oliver Pereira
// Used to hide or show the uploads block & personal dates block on the calendar website

function showHideBlock(request) {
	var mySheet = document.styleSheets[0];
	var cssRulesLength;
	if (request == 'SHOW') {
		// Check whether browser uses Mozilla's or Internet Exlorer's language
		if (mySheet.cssRules) {
			// Mozilla's language
			for (i = 0; i < mySheet.cssRules.length; i++) {
				if (mySheet.cssRules[i].selectorText == '.uploads') {
					mySheet.deleteRule(i);
				}
			}
		} else {
			// Internet Explorer's language
			for (i = 0; i < mySheet.rules.length; i++) {
				if (mySheet.rules[i].selectorText == '.uploads') {
					mySheet.removeRule(i);
				}
			}
		}
		switchNotesBox('upload');
	} else {
		if (mySheet.insertRule) {
			mySheet.insertRule('.uploads {display: none;}', 0);
		} else if (mySheet.addRule) {
			mySheet.addRule('.uploads', 'display: none;');
		}
		switchNotesBox('post-pack');
	}
	if (typeof resizeLeftHeaderImage == 'function' ||
				typeof resizeLeftHeaderImage == 'object') {
		resizeLeftHeaderImage();
	}
}

/*********************************************************************
   * Get an object, this function is cross browser
   * *** Please do not remove this header. ***
   * This code is working on my IE7, IE6, FireFox, Opera and Safari
   * 
   * Usage: 
   * var object = getObject(elementId);
   *
   * @Author Hamid Alipour Codehead @ webmaster-forums.code-head.com  
**/
function getObject(id) {
	var object = null;
	if (document.layers) {   
		object = document.layers[id];
	} else if (document.all) {
		object = document.all[id];
	} else if (document.getElementById) {
		object = document.getElementById(id);
	}
	return object;
}

// The function switchNotesBox() was added by Oliver Pereira, Tue 01/07/2008
function switchNotesBox(mode) {
	var uploadNotesDiv = new getObject('upload-notes');
	var postPackNotesDiv = new getObject('post-pack-notes');
	if (uploadNotesDiv.style !== void 0 && postPackNotesDiv.style !== void 0) {
		if (mode == 'post-pack') {
			uploadNotesDiv.style.display = 'none';
			postPackNotesDiv.style.display = 'block';
		} else {
			postPackNotesDiv.style.display = 'none';
			uploadNotesDiv.style.display = 'block';
		}
	}
}

// The following function validates e-mail addresses, and is based on
// the JavaScript code found on the following page:
// http://javascript.internet.com/forms/email-address-validation.html
// Included here by Oliver Pereira, Wed 15/10/2008
function getEmailAddressError(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	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) {
		return 'The e-mail address appears to be incorrect. (Check @ symbols and dots.)';
	}

	var user = matchArray[1];
	var domain = matchArray[2];

	for (i = 0; i < user.length; i++) {
		if (user.charCodeAt(i) > 127) {
			return 'The username in the e-mail address contains invalid characters.';
		}
	}

	for (i = 0; i < domain.length; i++) {
		if (domain.charCodeAt(i) > 127) {
			return 'The domain name in the e-mail address contains invalid characters.';
		}
	}

	if (user.match(userPat) == null) {
		return 'The username in the e-mail address appears to be invalid.';
	}

	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
		for (var i = 1; i <= 4; i++) {
			if (IPArray[i]>255) {
				return 'The destination IP address in the e-mail address is invalid.';
			}
		}
		return '';
	}

	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) {
			return 'The domain name in the e-mail address appears to be invalid.';
		}
	}

	if (checkTLD && domArr[domArr.length-1].length != 2 &&
				domArr[domArr.length - 1].search(knownDomsPat) == -1) {
		return 'The e-mail address must end in a valid domain or two-letter country code.';
	}

	if (len < 2) {
		return 'The e-mail address is missing a hostname.';
	}

	return '';
}

// Javascript trim, ltrim, and rtrim functions taken from the following page:
// http://www.somacon.com/p355.php
// Included here by Oliver Pereira, Wed 15/10/2008
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// The following function is for executing JavaScript on page load, and is taken from
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
