var prod_field_reg = /^prod_(.+)_var_(\d*?)_(\d*?)$/;
var forms = new Array();
document.dAProducts = new Array();
var loc_field_reg = /^(.+)_(country|region)$/;
document.dACountries = new Array();
var country = "";
var region = "";

// Create a discount manager object
function dADiscountManager() {
	this.discounts = new Array();
}
document.dADiscMgr = new dADiscountManager();

function dADiscount(id, title, description, image, page, discount_method, discount_amount) {
	this.id = id;
	this.title = title;
	this.description = description;
	this.image = image;
	this.page = page;
	this.discount_method = discount_method;
	this.discount_amount = discount_amount;
	this.exclusions = new Array();
	this.groups = new Array();
	return this;
}

function dACreateDiscount(id, title, description, image, page, discount_method, discount_amount) {
	document.dADiscMgr.discounts[document.dADiscMgr.discounts.length] = new dADiscount(id, title, description, image, page, discount_method, discount_amount);
}
function dAAddDiscountExclusion(id, product_code) {
	if (document.dADiscMgr.discounts) {
		for (var i=0;i<document.dADiscMgr.discounts.length;i++) {
			if (document.dADiscMgr.discounts[i].id == id) {
				document.dADiscMgr.discounts[i].exclusions[document.dADiscMgr.discounts[i].exclusions.length] = product_code;
				break;
			}
		}
	}
}
function dAAddDiscountGroup(discount_id, id, discount_method, discount_amount) {
	if (document.dADiscMgr.discounts) {
		for (var i=0;i<document.dADiscMgr.discounts.length;i++) {
			if (document.dADiscMgr.discounts[i].id == discount_id) {
				var p = document.dADiscMgr.discounts[i].groups.length;
				document.dADiscMgr.discounts[i].groups[p] = new Array();
				document.dADiscMgr.discounts[i].groups[p].id = id;
				document.dADiscMgr.discounts[i].groups[p].discount_method = discount_method;
				document.dADiscMgr.discounts[i].groups[p].discount_amount = discount_amount;
				document.dADiscMgr.discounts[i].groups[p].exceptions = new Array();
				break;
			}
		}
	}
}
function dAAddDiscountException(discount_id, id, product_code) {
	if (document.dADiscMgr.discounts) {
		for (var i=0;i<document.dADiscMgr.discounts.length;i++) {
			if (document.dADiscMgr.discounts[i].id == discount_id) {
				for(var p=0;p<document.dADiscMgr.discounts[i].groups.length;p++) {
					if (document.dADiscMgr.discounts[i].groups[p].id == id) {
						document.dADiscMgr.discounts[i].groups[p].exceptions[document.dADiscMgr.discounts[i].groups[p].exceptions.length] = product_code;
						var done = true;
						break;
					}
				}
				if (done == true) {
					break;
				}
			}
		}
	}
}

// Returns the best discount from our discount objects for the given product data:
function calcDiscount(product_code, price) {
	var disc_price = 0;
	var values = new Array();
	var best_values = new Array();
	// Check for the best-priced discount object for this product
	if (document.dADiscMgr.discounts) {
		for (var i=0;i<document.dADiscMgr.discounts.length;i++) {
			if (values = checkDiscount(document.dADiscMgr.discounts[i], product_code, price)) {
				if (values.disc_price > disc_price) {
					disc_price = values.disc_price;
					best_values = values;
				}
			}
		}
	}
	return best_values;
}

// Called from calcDiscount above - returns a set of discount values if it runs with a valid discount for the given product
// Otherwise returns false.
function checkDiscount(discount, product_code, price) {
	values = new Array();
	values.disc_price = 0;
	// Make sure this product isn't excluded:
	if (discount.exclusions) {
		for (var i=0;i<discount.exclusions.length;i++) {
			if (discount.exclusions[i] == product_code) {
				return values;
			}
		}
	}
	// Check to see if this product is included in any of this discount's groups:
	if (discount.groups) {
		for (var i=0;i<discount.groups.length;i++) {
			if (discount.groups[i].exceptions) {
				for (var p=0;p<discount.groups[i].exceptions.length;p++) {
					// Is this product excepted by this group?
					if (discount.groups[i].exceptions[p] == product_code) {
						if (discount.groups[i].discount_method == "constant") {
							values.disc_price = discount.groups[i].discount_amount;
						} else if (discount.groups[i].discount_method == "percentage") {
							values.disc_price = price * (discount.groups[i].discount_amount/100);
						}
						values.disc_title = discount.title;
						values.disc_desc = discount.description;
						values.disc_image = discount.image;
						values.disc_page = discount.page;
						return values;
					}
				}
			}
		}
	}
	if (discount.discount_method == "constant") {
		values.disc_price = discount.discount_amount;
	} else if (discount.discount_method == "percentage") {
		values.disc_price = price * (discount.discount_amount/100);
	}
	values.disc_title = discount.title;
	values.disc_desc = discount.description;
	values.disc_image = discount.image;
	values.disc_page = discount.page;
	return values;
}

// Creates a Country object
function dACartCreateCountry(country, s_zone, t_zone) {
	if (!document.dACountries) {
		document.dACountries = new Array();
	}
	document.dACountries[document.dACountries.length] = new dACountry(country, s_zone, t_zone);
	return true;
}

function dACountry(country, s_zone, t_zone) {
	this.id = country;
	if (s_zone != "") {
		this.s_zone = s_zone;
	}
	if (t_zone != "") {
		this.t_zone = t_zone;
	}
	this.regions = new Array();
	return this;
}

// Adds a region object inside a Country object
function dACartAddRegion(country, region, s_zone, t_zone) {
	if (document.dACountries) {
		for (var i=0;i<document.dACountries.length;i++) {
			if (document.dACountries[i].id == country) {
				var curr_region = document.dACountries[i].regions.length;
				document.dACountries[i].regions[curr_region] = new Array();
				document.dACountries[i].regions[curr_region].region = region;
				if (s_zone != "") {
					document.dACountries[i].regions[curr_region].s_zone = s_zone;
				}
				if (t_zone != "") {
					document.dACountries[i].regions[curr_region].t_zone = t_zone;
				}
				return true;
			}
		}
		return false;
	} else {
		return false;
	}
}

function dACartFindLocationForm() {
	for(i=0;i<document.forms.length;i++) {
		if (document.forms[i].elements) {
			for(p=0;p<document.forms[i].elements.length; p++) {
				var test = loc_field_reg.exec(document.forms[i].elements[p].name);
				if (test) {
					var form = document.forms[i];
					return form;
				}
			}
		}
	}
	return false;
}


// Check to see if we need to select a region to get valid shipping and tax zone selections.
function dACartSelectCountry(country, process) {
	// Find the form that submitted this request:
	if (form = dACartFindLocationForm()) {
		if (document.dACountries) {
			// Find the selected country:
			for (var i=0; i<document.dACountries.length;i++) {
				if (document.dACountries[i].id == country.options[country.options.selectedIndex].value) {
					// If we've got all the shipping and tax zone data from the country, or we don't have any regions anyway, submit the form.
					if ((document.dACountries[i].s_zone && document.dACountries[i].t_zone) || (!document.dACountries[i].regions || document.dACountries[i].regions.length == 0)) {
						// Disable the region selector:
						// Need name of country field to know which region field to populate (b_region or s_region)!
						if (country.name == "s_country") {
							var r_field = "s_region";
						} else if (country.name == "b_country") {
							var r_field = "b_region";
						}
						// Loop again to find target field:
						for (var p=0;p < form.elements.length; p++) {
							if (form.elements[p].name == r_field) {
								tag = form.elements[p];
								// Enable the region selector if it's disabled:
								tag.disabled = true;
								// Remove any current options that might be in there.
								tag.options.length = 0;
								tag.options[0] = new Option("Region not required", "Region not required");
							}
						}
						if (process == "cart") {
							form.submit();
							return true;
						} else {
							return true;
						}
					// Otherwise, display the region selector.
					} else {
						// Need name of country field to know which region field to populate (b_region or s_region)!
						if (country.name == "s_country") {
							var r_field = "s_region";
						} else if (country.name == "b_country") {
							var r_field = "b_region";
						}
						// Re-enable the region selector:
						// Loop again to find target field:
						for (var p=0;p < form.elements.length; p++) {
							if (form.elements[p].name == r_field) {
								tag = form.elements[p];
								// Enable the region selector if it's disabled:
								tag.disabled = false;
								// Remove any current options that might be in there.
								tag.options.length = 0;
								// Insert the region options for this country.
								for (var n=0;n<document.dACountries[i].regions.length;n++) {
									tag.options[n] = new Option(document.dACountries[i].regions[n].region, document.dACountries[i].regions[n].region);
								}
							}
						}
						return true;
					}
				}
			}
			// No country selected - disable region selector
			// Need name of country field to know which region field to populate (b_region or s_region)!
			if (country.name == "s_country") {
				var r_field = "s_region";
			} else if (country.name == "b_country") {
				var r_field = "b_region";
			}
			// Loop again to find target field:
			for (var p=0;p < form.elements.length; p++) {
				if (form.elements[p].name == r_field) {
					tag = form.elements[p];
					// Enable the region selector if it's disabled:
					tag.disabled = true;
					// Remove any current options that might be in there.
					tag.options.length = 0;
					// Insert the region options for this country.
					tag.options[0] = new Option("Choose Region", "Choose Region");
					break;
				}
			}
			return false;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

// Submit data
function dACartSelectRegion(region, process) {
	if (process == "cart") {
		// Find the form that submitted this request:
		if (form = dACartFindLocationForm()) {
			form.submit();
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}


function dACreateProduct(product_code) {
	if (!document.products) {
		document.products = new Array();
	}
	document.products[document.products.length] = new dAProduct(product_code);
	return true;
}

function dAProduct(product_code) {
	this.product_code = product_code;
	this.perms = new Array();
	return this;
}

function dAAddVariation(product_code, variations, price, price_inc, in_stock) {
	if (document.products) {
		for (var i=0;i<document.products.length;i++) {
			if (document.products[i].product_code == product_code) {
				var curr_perm = document.products[i].perms.length;
				document.products[i].perms[curr_perm] = new Array();
				document.products[i].perms[curr_perm].variations = variations;
				document.products[i].perms[curr_perm].price = price;
				document.products[i].perms[curr_perm].price_inc = price_inc;
				document.products[i].perms[curr_perm].in_stock = in_stock;
				return true;
			}
		}
	} else {
		return false;
	}
}

function dAInitProducts() {
	for(i=0;i<document.forms.length;i++) {
		if (document.forms[i].elements) {
			for(p=0;p<document.forms[i].elements.length; p++) {
				var test = prod_field_reg.exec(document.forms[i].elements[p].name);
				if (test) {
					var tag = dAReadProductForm(document.forms[i]);
					dAUpdateProduct(tag);
					break;
				}
			}
		}
	}
	return true;
}

function dAReadProductForm(tag) {
	if (tag.action) {
		var newtag = null;
		for (var i=0;i < tag.elements.length; i++) {
			if (tag.elements[i].type == "select-one") {
				var var_dat = prod_field_reg.exec(tag.elements[i].name);
				if (var_dat) {
					if (typeof forms[var_dat[1]] == "undefined") {
						forms[var_dat[1]] = new Array();
					}
					forms[var_dat[1]][tag.elements[i].name] = {type:tag.elements[i].type, name:tag.elements[i].name};
					if (tag.elements[i].options) {
						forms[var_dat[1]][tag.elements[i].name]['options'] = new Array();
						for(var n=0; n < tag.elements[i].options.length; n++) {
							forms[var_dat[1]][tag.elements[i].name]['options'][n] = {text:tag.elements[i].options[n].text, value:tag.elements[i].options[n].value};
						}
					}
				}
			}
			if (newtag==null && (tag.elements[i].type == "select-one" || tag.elements[i].type == "checkbox" || tag.elements[i].type == "radio")) {
				var test = prod_field_reg.exec(tag.elements[i].name);
				if (test) {
					newtag = tag.elements[i];
				}
			}
		}
		return newtag;
	}
}

function dAUpdateProduct(tag) {
	var form = tag.form;	
	var result = tag;
	while (!result['choices']) {
		result = dACheckProductPermutations(result);
		if (result == true) {
			return false;
		}
	}
	var choices = result['choices'];
	var product = result['product'];
	var selected = new Array();
	selected.product = product.product_code;
	var price = 0;
	var price_inc = 0;
	
	for (var i=0;i < form.elements.length; i++) {
		var var_dat = prod_field_reg.exec(form.elements[i].name);
		if (var_dat) {
			if (form.elements[i].type == "select-one") {
				form.elements[i].options.length = 0;
			} else if (form.elements[i].type == "radio") {
				form.elements[i].disabled = true;
			} else if (form.elements[i].type == "checkbox") {
				form.elements[i].disabled = true;
			}
		}
	}
	var statuses = new Array();
	var fst_chunks = new Array();
	var snd_chunks = new Array();
	
	for (var p=0;p<product.perms.length;p++) {
		if (product.perms[p].in_stock == true) {
			product.perms[p].invalid = false;
			var chunks = product.perms[p].variations.split('_');
			if (chunks[1]) {
				if (!statuses[chunks[0]]) {
					statuses[chunks[0]] = new Array();
				}
				for (var n=1; n<chunks.length; n+=2) {
					if (!statuses[chunks[0]][chunks[n]]) {
						statuses[chunks[0]][chunks[n]] = new Array();
					}
					fst_chunks = {0: chunks[0], 1: chunks[n], 2: chunks[n+1]};
					if (chunks[n+2]) {
						snd_chunks = {0: chunks[0], 1: chunks[n+2], 2: chunks[n+3]};
						if (!statuses[chunks[0]][chunks[n+2]]) {
							statuses[chunks[0]][chunks[n+2]] = new Array();
						}
					}
					if (choices[chunks[0]][chunks[n]] == chunks[n+1]) {					
						if (n == 1) {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n], statuses, fst_chunks, true, true);
						} else {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n], statuses, fst_chunks, false, true);
						}
						if (chunks[n+2]) {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n+2], statuses, snd_chunks, true, false);
						}

					} else {
						if (n == "1") {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n], statuses, fst_chunks, true, false);
						} else {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n], statuses, fst_chunks, false, false);
						}
						if (chunks[n+2]) {
							statuses = dASetPermutationStatus(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[n+2], statuses, snd_chunks, false, false);
						}
						product.perms[p].invalid = true;
						break;
					}
				}
				if (!product.perms[p].invalid) {
					price += (product.perms[p].price * 1.0);
					price_inc += (product.perms[p].price_inc * 1.0);
				}
			} else if (chunks[0] == "default") {
				price += (product.perms[p].price * 1.0);
				price_inc += (product.perms[p].price_inc * 1.0);
			}
		}

	}
	
	// Get discount details if there is an appropriate discount for this product:
	//var discount_vals = new Array();
	var discount_vals = calcDiscount(product.product_code, price, price_inc);
	if (discount_vals.disc_price && discount_vals.disc_price != "") {
		// We have a discounted price.
		// Recalc the tax-inclusive price:
		var tax_rate = (price_inc - price) / price;
		discount_vals.disc_price = price - discount_vals.disc_price;
		
		price_inc = (discount_vals.disc_price * tax_rate) + discount_vals.disc_price;		
	}
	//		<p><b><span id="discount_price_{ product_code }">{ discount_price }</span></b></p>
	//		<p><img id="discount_image_{ product_code }" src="{discount_image}" border="0"></p>
	//		<p><b><span id="discount_title_{ product_code }">{ discount_title }</span></b></p>
	//		<p><b><span id="discount_description_{ product_code }">{ discount_desc }</span></b></p>
	//		<p><a id="discount_page_{product_code}" href="{discount_page">Click here for more information</a></p>
	
	price += "";
	var ip = price.indexOf(".");
	if (ip == -1) {
		price += ".00";
	} else {
		price += "00";
		price = price.substring(0, ip+3);
	}
	if (document.getElementById("price_" + selected.product)) {
		document.getElementById("price_" + selected.product).innerHTML = price;
	}
	price_inc += "";
	var ipi = price_inc.indexOf(".");
	if (ipi == -1) {
		price_inc += ".00";
	} else {
		price_inc += "00";
		price_inc = price_inc.substring(0, ipi+3);
	}

	// If price_inc is zero, set it to "":
	if (price_inc == "0.00") {
		price_inc = "";
	}
	if (document.getElementById("price_inc_" + selected.product)) {
		document.getElementById("price_inc_" + selected.product).innerHTML = price_inc;
		
		// Hide any price_incs that are empty:
		// 
		if (price_inc == "") {
			document.getElementById("markup_price_inc_" + selected.product).style.visibility = "hidden";
		} else {
			document.getElementById("markup_price_inc_" + selected.product).style.visibility = "visible";
		}
	}
	
	if (discount_vals.disc_price && discount_vals.disc_price != "") {
		discount_vals.disc_price += "";
		var ipi = discount_vals.disc_price.indexOf(".");
		if (ipi == -1) {
			discount_vals.disc_price += ".00";
		} else {
			discount_vals.disc_price += "00";
			discount_vals.disc_price = discount_vals.disc_price.substring(0, ipi+3);
		}
		if (document.getElementById("discount_price_" + product.product_code)) {
			var pricefield = document.getElementById("discount_price_" + product.product_code);
			pricefield.innerHTML = discount_vals.disc_price;
			pricefield.style.visibility = "visible";
		}

		// Also update the other discount-related page elements if they exist:
		if (document.getElementById("discount_title_" + product.product_code)) {
			var titlefield = document.getElementById("discount_title_" + product.product_code);
			titlefield.innerHTML = discount_vals.disc_title;
			titlefield.style.visibility = "visible";
		}
		if (document.getElementById("discount_description_" + product.product_code)) {
			var descfield = document.getElementById("discount_description_" + product.product_code);
			descfield.innerHTML = discount_vals.disc_desc;
			descfield.style.visibility = "visible";
		}
		if (document.getElementById("discount_page_" + product.product_code)) {
			var pagefield = document.getElementById("discount_page_" + product.product_code);
			pagefield.href = discount_vals.disc_page;
			pagefield.style.visibility = "visible";
		}
		if (document.getElementById("discount_image_" + product.product_code)) {
			var imagefield = document.getElementById("discount_image_" + product.product_code);
			imagefield.src = discount_vals.disc_image;
			imagefield.style.visibility = "visible";
		}
	} else {
		// Disappear the discount fields if they exist:
		if (document.getElementById("discount_price_" + product.product_code)) {
			var pricefield = document.getElementById("discount_price_" + product.product_code);
			pricefield.style.visibility = "hidden";
		}

		// Also update the other discount-related page elements if they exist:
		if (document.getElementById("discount_title_" + product.product_code)) {
			var titlefield = document.getElementById("discount_title_" + product.product_code);
			titlefield.style.visibility = "hidden";
		}
		if (document.getElementById("discount_description_" + product.product_code)) {
			var descfield = document.getElementById("discount_description_" + product.product_code);
			descfield.style.visibility = "hidden";
		}
		if (document.getElementById("discount_page_" + product.product_code)) {
			var pagefield = document.getElementById("discount_page_" + product.product_code);
			pagefield.style.visibility = "hidden";
		}
		if (document.getElementById("discount_image_" + product.product_code)) {
			var imagefield = document.getElementById("discount_image_" + product.product_code);
			imagefield.style.visibility = "hidden";
		}
	}
	return true;
}	

function dASetPermutationStatus(form, element, statuses, chunks, enable, select) {
	if (!statuses[chunks[0]][chunks[1]][chunks[2]]) {
		statuses[chunks[0]][chunks[1]][chunks[2]] = {enabled: enable, selected: select};
	} else {
		if (select == true && statuses[chunks[0]][chunks[1]][chunks[2]]['selected'] != true) {
			statuses[chunks[0]][chunks[1]][chunks[2]]['selected'] = true;
		} else if (select == false && (!statuses[chunks[0]][chunks[1]][chunks[2]]['selected'] || statuses[chunks[0]][chunks[1]][chunks[2]]['selected'] != true)) {
			statuses[chunks[0]][chunks[1]][chunks[2]]['selected'] = false;
		}
		if (enable == true && (!statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] || statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] != true)) {
			statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] = true;
		} else if (enable == false && (!statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] || statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] != true)) {
			statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'] = false;
		}
	}
	if (form[element].type == "checkbox") {
		if (statuses[chunks[0]][chunks[1]][0] && statuses[chunks[0]][chunks[1]][1]) {
			if (statuses[chunks[0]][chunks[1]][0]['enabled'] == true && statuses[chunks[0]][chunks[1]][1]['enabled'] == true) {
				dAModifyProductField(form, element, chunks[2], statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'], statuses[chunks[0]][chunks[1]][chunks[2]]['selected']);
			}
		}
	} else {
		dAModifyProductField(form, element, chunks[2], statuses[chunks[0]][chunks[1]][chunks[2]]['enabled'], statuses[chunks[0]][chunks[1]][chunks[2]]['selected']);
	}
	return statuses;
}

function dACheckProductPermutations(tag) {	
	if (tag.form) {
		var arr = prod_field_reg.exec(tag.name);
		if (arr) {
			var selected = new Array();
			selected.product = arr[1];
			selected.grp = arr[2];
			selected.vnt = arr[3];
			var form = tag.form;
			if (tag.type == "select-one") {
				selected.val = tag.options[tag.options.selectedIndex].value;
			} else if (tag.type == "checkbox") {
				if (tag.checked == true) {
					selected.val = 1;
				} else {
					selected.val = 0;
				}
			} else if (tag.type == "radio") {
				if (tag.checked == true) {
					selected.val = tag.value;
				}
			}
			
			if (form.elements) {
				var choices = new Array();
				for(p=0;p<form.elements.length; p++) {
					var arr2 = prod_field_reg.exec(form.elements[p].name);
					if (arr2) {
						if (arr2[1] == selected.product) {
							if (!choices[arr2[2]]) {
								choices[arr2[2]] = new Array();
							}
							if (form.elements[p].type == "radio") {
								if (form.elements[p].checked == true) {
									choices[arr2[2]][arr2[3]] = form.elements[p].value;
								}
							} else if (form.elements[p].type == "select-one") {
								choices[arr2[2]][arr2[3]] = form.elements[p].options[form.elements[p].options.selectedIndex].value;
							} else if (form.elements[p].type == "checkbox") {
								if (form.elements[p].checked == true) {
									choices[arr2[2]][arr2[3]] = 1;
								} else {
									choices[arr2[2]][arr2[3]] = 0;
								}
							}
						}
					}
				}
			}
			
			if (document.products) {
				for (var i=0; i<document.products.length; i++) {
					if (document.products[i].product_code == selected.product) {
						if (document.products[i].perms) {
							var product = document.products[i];
							var fittest = new Array();
							fittest.length = 0;
							for (var p=0;p<product.perms.length;p++) {
								product.perms[p].score = 0;
								product.perms[p].valid = null;
								product.perms[p].invalids = new Array();
								product.perms[p].invalids.length = 0;
								var chunks = product.perms[p].variations.split('_');
								if (chunks[1]) {
									for (var n=1; n<chunks.length; n+=2) {
										if (choices[chunks[0]][chunks[n]] == chunks[n+1]) {
											product.perms[p].score++;
										} else {
											if (!product.perms[p].invalids) {
												product.perms[p].invalids = new Array();
											}
											product.perms[p].invalids[product.perms[p].invalids.length] = n;
										}
										if (chunks[0] == selected.grp && chunks[n] == selected.vnt && chunks[n+1] == selected.val && product.perms[p].in_stock == true) {
											product.perms[p].valid = true;
										} else if (chunks[0] != selected.grp && n==1 && chunks[n+1] == choices[chunks[0]][chunks[n]] && product.perms[p].in_stock == true) {
											product.perms[p].valid = true;
										}
									}
									if (!fittest[product.perms[p].variations.substring(0, 1)] && product.perms[p].in_stock == true) {
										fittest[product.perms[p].variations.substring(0, 1)] = product.perms[p];
									} else {
										if (fittest[product.perms[p].variations.substring(0, 1)]) {
											if (product.perms[p].score > fittest[product.perms[p].variations.substring(0, 1)].score) {
												if (fittest[product.perms[p].variations.substring(0, 1)].valid == "true" ) {
													if (product.perms[p].valid == "true") {
														fittest[product.perms[p].variations.substring(0, 1)] = product.perms[p];
													}
												} else {
													fittest[product.perms[p].variations.substring(0, 1)] = product.perms[p];
												}
											} else if (product.perms[p].score == fittest[product.perms[p].variations.substring(0, 1)].score) {
												if (fittest[product.perms[p].variations.substring(0, 1)].valid == "true" ) {
													if (product.perms[p].valid == "true") {
														var test = true;
													} else {
														var test = false;
													}
												} else {
													var test = true;
												}
												if (test == true && product.perms[p].invalids && fittest[product.perms[p].variations.substring(0, 1)].invalids) {
													var total1 = 0;
													for(var m=0; m<product.perms[p].invalids.length; m++) {
														total1 += product.perms[p].invalids[m];
													}
													var total2 = 0;
													for(var m=0; m<fittest[product.perms[p].variations.substring(0, 1)].invalids.length; m++) {
														total2 += fittest[product.perms[p].variations.substring(0, 1)].invalids[m];
													}
													if (total1 > total2) {
														fittest[product.perms[p].variations.substring(0, 1)] = product.perms[p];
													}
												}
											}
										}
									}
								}
							}
							if (fittest[selected.grp].invalids.length > 0) {
								for(var m=fittest[selected.grp].invalids.length-1; m>-1; m--) {
									chunks = fittest[selected.grp].variations.split('_');
									
									var newtag = dAModifyProductField(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[fittest[selected.grp].invalids[m]], chunks[fittest[selected.grp].invalids[m]+1], true, true);
									
									return newtag;
								}
							} else {
								var rerun = false;
								for (var n in fittest) {
									if (n != "d" && fittest[n].invalids.length > 0) {
										rerun = true;
										for(var m=fittest[n].invalids.length-1; m>-1; m--) {
											chunks = fittest[n].variations.split('_');
											var newtag = dAModifyProductField(form, "prod_" + product.product_code + "_var_" + chunks[0] + "_" + chunks[fittest[n].invalids[m]], chunks[fittest[n].invalids[m]+1], true, true);
											return newtag;
										}
									}
								}
							}
							var result = new Array();
							result.choices = choices;
							result.product = product;
							result.form = form;
							return result;
						} else {
							return true;
						}
						break;
					}
				}
			} else {
				return true;
			}
		} else {
			return true;
		}
	} else {
		return true;
	}
}

function dAModifyProductField(form, element, value, enable, select) {
	var tag = form.elements[element];
	if (tag) {
		if (tag.name) {
			if (tag.type == "select-one") {
				var done = false;
				for(var i=0; i < tag.options.length; i++) {
					if (tag.options[i].value == value) {
						if (enable == false) {
							tag.options[i] = null;
						}
						if (select == true) {
							tag.options[i].selected = true;
						} else if (select == false) {
							tag.options[i].selected = false;
						}
						done = true;
					}
				}
				if (done != true && (enable == true || select == true)) {
					var var_dat = prod_field_reg.exec(element);
					if (var_dat) {
						for(var n=0; n < forms[var_dat[1]][element]['options'].length; n++) {
							if (forms[var_dat[1]][element]['options'][n].value == value) {
								// Add this element to the form:
								tag.options[tag.options.length] = new Option(forms[var_dat[1]][element]['options'][n].text, forms[var_dat[1]][element]['options'][n].value);
								if (select == true) {
									tag.options[tag.options.length-1].selected = true;
								}
							}
						}
					}
				}
				return tag;
				
			} else if (tag.type == "checkbox") {
				if (enable == true) {
					tag.disabled = false;
				} else if (enable == false) {
					tag.disabled = true;
				}
				if (select == true && value == 0) {
					tag.checked = false;
				} else if (select == true && value == 1) {
					tag.checked = true;
				}
				return tag;
			}
		} else if (tag[value]) {
			tag = tag[value];
			if (enable == true) {
				tag.disabled = false;
			} else if (enable == false) {
				tag.disabled = true;
			}
			if (select == true) {
				tag.checked = true;
			} else if (select == false) {
				tag.checked = false;
			}
			return tag;
		}
	}
}
