// Product page scripts

/* START of MD5 hashing js - minified - use hex_md5(str) to get hashed version of str */
var hexcase=0;function hex_md5(a){return rstr2hex(rstr_md5(str2rstr_utf8(a)))}function rstr_md5(a){return binl2rstr(binl_md5(rstr2binl(a),a.length*8))}function rstr2hex(c){try{hexcase}catch(g){hexcase=0}var f=hexcase?"0123456789ABCDEF":"0123456789abcdef";var b="";var a;for(var d=0;d<4;d++){a=c.charCodeAt(d);b+=f.charAt((a>>>4)&15)+f.charAt(a&15)}return b}function str2rstr_utf8(c){var b="";var d=-1;var a,e;while(++d<c.length){a=c.charCodeAt(d);e=d+1<c.length?c.charCodeAt(d+1):0;if(55296<=a&&a<=56319&&56320<=e&&e<=57343){a=65536+((a&1023)<<10)+(e&1023);d++}if(a<=127){b+=String.fromCharCode(a)}else{if(a<=2047){b+=String.fromCharCode(192|((a>>>6)&31),128|(a&63))}else{if(a<=65535){b+=String.fromCharCode(224|((a>>>12)&15),128|((a>>>6)&63),128|(a&63))}else{if(a<=2097151){b+=String.fromCharCode(240|((a>>>18)&7),128|((a>>>12)&63),128|((a>>>6)&63),128|(a&63))}}}}}return b}function rstr2binl(b){var a=Array(b.length>>2);for(var c=0;c<a.length;c++){a[c]=0}for(var c=0;c<b.length*8;c+=8){a[c>>5]|=(b.charCodeAt(c/8)&255)<<(c%32)}return a}function binl2rstr(b){var a="";for(var c=0;c<b.length*32;c+=8){a+=String.fromCharCode((b[c>>5]>>>(c%32))&255)}return a}function binl_md5(p,k){p[k>>5]|=128<<((k)%32);p[(((k+64)>>>9)<<4)+14]=k;var o=1732584193;var n=-271733879;var m=-1732584194;var l=271733878;for(var g=0;g<p.length;g+=16){var j=o;var h=n;var f=m;var e=l;o=md5_ff(o,n,m,l,p[g+0],7,-680876936);l=md5_ff(l,o,n,m,p[g+1],12,-389564586);m=md5_ff(m,l,o,n,p[g+2],17,606105819);n=md5_ff(n,m,l,o,p[g+3],22,-1044525330);o=md5_ff(o,n,m,l,p[g+4],7,-176418897);l=md5_ff(l,o,n,m,p[g+5],12,1200080426);m=md5_ff(m,l,o,n,p[g+6],17,-1473231341);n=md5_ff(n,m,l,o,p[g+7],22,-45705983);o=md5_ff(o,n,m,l,p[g+8],7,1770035416);l=md5_ff(l,o,n,m,p[g+9],12,-1958414417);m=md5_ff(m,l,o,n,p[g+10],17,-42063);n=md5_ff(n,m,l,o,p[g+11],22,-1990404162);o=md5_ff(o,n,m,l,p[g+12],7,1804603682);l=md5_ff(l,o,n,m,p[g+13],12,-40341101);m=md5_ff(m,l,o,n,p[g+14],17,-1502002290);n=md5_ff(n,m,l,o,p[g+15],22,1236535329);o=md5_gg(o,n,m,l,p[g+1],5,-165796510);l=md5_gg(l,o,n,m,p[g+6],9,-1069501632);m=md5_gg(m,l,o,n,p[g+11],14,643717713);n=md5_gg(n,m,l,o,p[g+0],20,-373897302);o=md5_gg(o,n,m,l,p[g+5],5,-701558691);l=md5_gg(l,o,n,m,p[g+10],9,38016083);m=md5_gg(m,l,o,n,p[g+15],14,-660478335);n=md5_gg(n,m,l,o,p[g+4],20,-405537848);o=md5_gg(o,n,m,l,p[g+9],5,568446438);l=md5_gg(l,o,n,m,p[g+14],9,-1019803690);m=md5_gg(m,l,o,n,p[g+3],14,-187363961);n=md5_gg(n,m,l,o,p[g+8],20,1163531501);o=md5_gg(o,n,m,l,p[g+13],5,-1444681467);l=md5_gg(l,o,n,m,p[g+2],9,-51403784);m=md5_gg(m,l,o,n,p[g+7],14,1735328473);n=md5_gg(n,m,l,o,p[g+12],20,-1926607734);o=md5_hh(o,n,m,l,p[g+5],4,-378558);l=md5_hh(l,o,n,m,p[g+8],11,-2022574463);m=md5_hh(m,l,o,n,p[g+11],16,1839030562);n=md5_hh(n,m,l,o,p[g+14],23,-35309556);o=md5_hh(o,n,m,l,p[g+1],4,-1530992060);l=md5_hh(l,o,n,m,p[g+4],11,1272893353);m=md5_hh(m,l,o,n,p[g+7],16,-155497632);n=md5_hh(n,m,l,o,p[g+10],23,-1094730640);o=md5_hh(o,n,m,l,p[g+13],4,681279174);l=md5_hh(l,o,n,m,p[g+0],11,-358537222);m=md5_hh(m,l,o,n,p[g+3],16,-722521979);n=md5_hh(n,m,l,o,p[g+6],23,76029189);o=md5_hh(o,n,m,l,p[g+9],4,-640364487);l=md5_hh(l,o,n,m,p[g+12],11,-421815835);m=md5_hh(m,l,o,n,p[g+15],16,530742520);n=md5_hh(n,m,l,o,p[g+2],23,-995338651);o=md5_ii(o,n,m,l,p[g+0],6,-198630844);l=md5_ii(l,o,n,m,p[g+7],10,1126891415);m=md5_ii(m,l,o,n,p[g+14],15,-1416354905);n=md5_ii(n,m,l,o,p[g+5],21,-57434055);o=md5_ii(o,n,m,l,p[g+12],6,1700485571);l=md5_ii(l,o,n,m,p[g+3],10,-1894986606);m=md5_ii(m,l,o,n,p[g+10],15,-1051523);n=md5_ii(n,m,l,o,p[g+1],21,-2054922799);o=md5_ii(o,n,m,l,p[g+8],6,1873313359);l=md5_ii(l,o,n,m,p[g+15],10,-30611744);m=md5_ii(m,l,o,n,p[g+6],15,-1560198380);n=md5_ii(n,m,l,o,p[g+13],21,1309151649);o=md5_ii(o,n,m,l,p[g+4],6,-145523070);l=md5_ii(l,o,n,m,p[g+11],10,-1120210379);m=md5_ii(m,l,o,n,p[g+2],15,718787259);n=md5_ii(n,m,l,o,p[g+9],21,-343485551);o=safe_add(o,j);n=safe_add(n,h);m=safe_add(m,f);l=safe_add(l,e)}return Array(o,n,m,l)}function md5_cmn(h,e,d,c,g,f){return safe_add(bit_rol(safe_add(safe_add(e,h),safe_add(c,f)),g),d)}function md5_ff(g,f,k,j,e,i,h){return md5_cmn((f&k)|((~f)&j),g,f,e,i,h)}function md5_gg(g,f,k,j,e,i,h){return md5_cmn((f&j)|(k&(~j)),g,f,e,i,h)}function md5_hh(g,f,k,j,e,i,h){return md5_cmn(f^k^j,g,f,e,i,h)}function md5_ii(g,f,k,j,e,i,h){return md5_cmn(k^(f|(~j)),g,f,e,i,h)}function safe_add(a,d){var c=(a&65535)+(d&65535);var b=(a>>16)+(d>>16)+(c>>16);return(b<<16)|(c&65535)}function bit_rol(a,b){return(a<<b)|(a>>>(32-b))};
/* END of MD5 hashing js - minified - use hex_md5(str) to get hashed version of str */

function verifyCartSubmit() {
	var verif,
	golfState = document.getElementById('state-course-1'),
	golfCity = document.getElementById('city-course-1'),
	golfCourse = document.getElementById('name-course-1');
	
	for (verif in verifs) {
		if (!document.getElementById(verif).checked) {
			alert(verifs[verif]);
			return false;
		}
	}
	if (golfState && golfCity && golfCourse) {
		if (!/[a-z]{2}/i.test(golfState.value) || !/\w+/i.test(golfCity.value) || !/\w+/i.test(golfCourse.value)) {
			alert('Please add a golf course');
			return false;
		}
	}
	return CartSubmit();
}

function adderIsDone() {
	document.getElementById('addToCartForm').submit();
}

function CartSubmit() {
	if (firstCartSubmitRun) {
		firstCartSubmitRun = false;
		var inputs = document.getElementsByTagName('input');
		var submitUrl = 'http://order.store.yahoo.net/cgi-bin/wg-order?vwcatalog=yhst-59525373201481';
		var bundlePatt = /bundle(-)?(\s)?sale/i;
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].type === 'text') {
				inputs[i].value = inputs[i].value.replace(/[:\r\n]+/g, ' ');
			}
			if (bundlePatt.test(inputs[i].name)) {
				if (inputs[i].checked && inputs[i].value !== '' && inputs[i].value !== 'none') {
					inputs[i].value = inputs[i].value.replace(/\s?\([\+|\-]\$\d+(\.\d+)?\)/, ''); // removes the dollar amount
					var opSidb = document.getElementById('op-sidb');
					var prodSku = document.getElementById('product-sku').innerHTML;
					var bundleSku = inputs[i].id.replace(/crosssell-bundle-\d{6}/, '');
					var hashCode = hex_md5(prodSku + bundleSku);
					submitUrl += '&vwitem=' + inputs[i].id.replace('crosssell-', '') + '&OPBC=' + hashCode;
					if (opSidb) {
						submitUrl += '&OPSIDB=' + opSidb.value;
					}
					var newInput = document.createElement('input');
					newInput.type = 'hidden';
					newInput.name = 'OPBP';
					newInput.value = hashCode;
					document.getElementById('addToCartForm').appendChild(newInput);
				}
			}
		}
		if (submitUrl === 'http://order.store.yahoo.net/cgi-bin/wg-order?vwcatalog=yhst-59525373201481') {
			return true;
		} else {
			document.getElementById('addercontainer').innerHTML = '<img onerror="adderIsDone();" src="' + submitUrl + '">';
		}
	} else {
		var inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].type === 'text') {
				inputs[i].value = inputs[i].value.replace(/:/g, ' ');
			}
		}
		return true;
	}
	return false;
}

function RecentlyViewed(page, containerId, varName) {
	var cookie = new Cookie('__viewed'),
	j = 2,
	container = document.getElementById(containerId),
	yahooUrl = 'http://yhst-59525373201481.csell.store.yahoo.net/cs/recommend?itemids=' + page.id + '&location=p&callback=' + varName + '.getYahooInfo&noCacheIE=' + Math.random(),
	
	buildProd = function (obj) {
		var div = document.createElement('div');
		div.className = 'product-box';
		j = (j === 2) ? 1 : 2;
		if (!obj.i) {
			obj.i = 'http://images' + j + '.tacticalstore.com/cart/' + obj.id + '.gif';
		}
		div.innerHTML = '<a href="http://www.tactical-store.com/' + obj.id + '.html"><img src="' + obj.i + '" width="70" height="70" alt="' + obj.n + '">' + obj.n + '</a><div>' + (obj.p === 'cto' ? '<span class="cto-tip-me">Call To Order' : '$' + obj.p.replace(/\./, '<span>')) + '</span></div>';
		return div;
	},
	
	buildGroup = function (divId, headerTxt, prods) {
		var i, l, prodDiv,
		header = document.createElement('h3'),
		mainDiv = document.createElement('div'),
		borderDiv = document.createElement('div');
		mainDiv.id = divId;
		borderDiv.className = 'border-box';
		mainDiv.appendChild(borderDiv);
		header.innerHTML = headerTxt;
		mainDiv.appendChild(header);
		for (i = 0, l = prods.length; i < l; i++) {
			prodDiv = buildProd(prods[i]);
			mainDiv.appendChild(prodDiv);
		}
		container.insertBefore(mainDiv, container.firstChild);
	},
	
	handleCookie = function () {
		var pieces, i, l, guts, newValue = '', recent = [],
		cookieInfo = cookie.getValue();
		if (cookieInfo) {
			pieces = cookieInfo.split('||');
			for (i = 0, l = pieces.length; i < l; i++) {
				guts = pieces[i].split('|');
				j = (j === 2) ? 1 : 2;
				if (guts[0] !== page.id) {
					recent.push({
						'id' : guts[0],
						'n' : guts[1],
						'p' : guts[2],
						'i' : 'http://images' + j + '.tacticalstore.com/80-80-ffffff' + (guts[3] === '-no-image' ? '-no-image.png' : '/' + guts[3] + '.gif')
					});
					newValue = pieces[i] + (newValue === '' ? '' : '||') + newValue;
				}
			}
			pieces = newValue.split('||');
			if (pieces.length > 5) {
				i = newValue.lastIndexOf('||');
				newValue = newValue.substring(0, i);
			}
		}
		newValue = page.id + '|' + page.name + '|' + page.price + '|' + page.image + (newValue === '' ? '' : '||') + newValue;
		cookie.setValue(newValue);
		if (recent.length > 0) {
			buildGroup('recently-viewed', 'Recently Viewed Products', recent);
		} else {
			container.className += ' no-recently-viewed';
		}
	};
	
	this.getYahooInfo = function (json) {
		var recent = document.getElementById('recently-viewed');
		if (json.r && json.r.length > 0) {
			buildGroup('yahoo-related', 'You May Also Like...', json.r);
			if (recent) {
				if (recent.offsetHeight < document.getElementById('yahoo-related').offsetHeight) {
					container.className += 'yahoo-border';
				}
			}
		} else {
			container.className += ' no-yahoo-related';
		}
	};
	
	// init
	if (container) {
		container.className = '';
		handleCookie();
		addScriptToHead(yahooUrl, '', 'js');
	}
}

function OptionHandler() {
	var tables, i, l, inputOpts, labelOpts, specSets = [], pmodSets = [], j, k, x, pmodValues = [], bundle = null, selectOpt, pmodPercent, tempSets, sets = [], set, longestName = [],
	optionDiv = document.getElementById('options'),
	variantInput = document.createElement('input'),
	form = document.getElementById('addToCartForm'),
	specialDiscount = document.getElementById('special-discount'),
	priceEl = document.getElementById('priceDisplay'),
	saleEl = document.getElementById('salePriceDisplay'),
	youSaveEl = document.getElementById('youSaveDisplay'),
	rebateEl = document.getElementById('priceAfterRebateDisplay'),
	prodCode = document.getElementById('product-code'),
	prodUpc = document.getElementById('product-upc'),
	prodSku = document.getElementById('product-sku'),
	cartButton = document.getElementById('add-to-cart-button'),
	bundlesTable = document.getElementById('bundles-table'),
	headblockRight = document.getElementById('headblock-right'),
	codeBlock = document.getElementById('product-code-block'),
	freeShip = document.getElementById('free-shipping-img'),
	ieVersion = getIEVersion(),
	
	currency = function (n) {
		var x = n.toFixed(2) + '',
		rgx = /(\d+)(\d{3})/;
		while (rgx.test(x)) {
			x = x.replace(rgx, '$1,$2');
		}
		return '$' + x;
	},
	
	numberSort = function (a, b) {
		return a - b;
	},
	
	getVariant = function () {
		var unsorted, variant, tempArr = [];
		if (specSets.length > 0) {
			for (i = 0, l = specSets.length; i < l; i++) {
				tempArr.push(specSets[i].selected);
			}
			unsorted = '-' + tempArr.join('-') + '-';
			tempArr = tempArr.sort(numberSort);
			variant = '-' + tempArr.join('-') + '-';
		} else {
			for (variant in optionJson) {
				if (/-\d+-/.test(variant)) {
					unsorted = variant;
					break;
				}
			}
		}
		return {'sorted' : variant, 'unsorted' : unsorted};
	},
	
	setPrices = function (salePrice, regPrice, rebate, code, pmod, override, upc, sku) {
		var sale = salePrice + pmod - override,
		price = (regPrice === 0) ? 0 : regPrice + pmod,
		youSave = regPrice - salePrice + rebate,
		savePercent = Math.round(youSave / regPrice * 100.00),
		newSale = 0;
		if (saleEl) {
			saleEl.innerHTML = (override > 0) ? '<a class="toolow">too low to show</a>' : currency(sale).replace('.', '<span>') + '</span>';
		}
		if (priceEl) {
			if (regPrice === 0) {
				priceEl.parentNode.style.display = 'none';
			} else {
				priceEl.parentNode.style.display = '';
				priceEl.innerHTML = currency(price);
			}
		}
		if (youSaveEl) {
			if (override > 0 || regPrice === 0) {
				youSaveEl.parentNode.style.display = 'none';
			} else {
				youSaveEl.parentNode.style.display = '';
				youSaveEl.innerHTML = currency(youSave) + ' (' + savePercent + '%)';
			}
		}
		if (rebateEl) {
			if (override > 0) {
				rebateEl.parentNode.style.display = 'none';
			} else {
				rebateEl.parentNode.style.display = '';
				rebateEl.innerHTML = currency(sale - rebate);
			}
		}
		if (prodCode) {
			prodCode.innerHTML = code;
		}
		if (prodUpc) {
			if (upc) {
				prodUpc.parentNode.style.display = '';
				prodUpc.innerHTML = upc;
			} else {
				prodUpc.parentNode.style.display = 'none';
			}
		}
		if (prodSku) {
			if (sku) {
				prodSku.parentNode.style.display = '';
				prodSku.innerHTML = sku;
			} else {
				prodSku.parentNode.style.display = 'none';
			}
		}
		if (code) {
			newSale = salePrice - override;
			if (newSale > optionJson.baseSale) {
				newSale = newSale - optionJson.baseSale;
				variantInput.value = code + ' (+$' + newSale.toFixed(2) + ')';
			} else if (optionJson.baseSale > newSale) {
				newSale = optionJson.baseSale - newSale;
				variantInput.value = code + ' (-$' + newSale.toFixed(2) + ')';
			} else {
				variantInput.value = code;
			}
		}
		if (bundle) {
			for (i = 0, l = bundle.labels.length; i < l; i++) {
				bundle.labels[i].innerHTML = currency(bundle.values[i] + sale);
			}
		}
		if (freeShip) {
			freeShip.style.display = (sale < 29.95 || override > 0) ? 'none' : '';
		}
		if (specialDiscount) {
			if (override > 0) {
				specialDiscount.disabled = false;
				specialDiscount.value = currency(override);
			} else {
				specialDiscount.disabled = true;
			}
		}
	},
	
	setOptions = function (current, salePrice) {
		var input, tempVariant, priceDiff = 0, dropPrefix, spaces;
		for (i = 0, l = specSets.length; i < l; i++) {
			input = specSets[i].inputs;
			for (j = 0, k = input.length; j < k; j++) {
				if (input[j].title) {
					spaces = (longestName[i] - input[j].title.length) + 3;
					dropPrefix = input[j].title;
					for (x = 0; x < spaces; x++) {
						dropPrefix += '&nbsp;';
					}
				} else {
					dropPrefix = '';
				}
				if (input[j].id.replace('spec-', '') === specSets[i].selected) {
					specSets[i].labels[j].innerHTML = dropPrefix + 'Included in Price';
				} else {
					tempVariant = current.unsorted.slice(1, current.unsorted.length - 1).split('-');
					tempVariant[i] = input[j].id.replace('spec-', '');
					tempVariant = tempVariant.sort(numberSort);
					tempVariant = '-' + tempVariant.join('-') + '-';
					if (optionJson[tempVariant]) {
						if (optionJson[tempVariant].override > 0) {
							specSets[i].labels[j].innerHTML = dropPrefix + ' Too low to show';
						} else {
							priceDiff = optionJson[tempVariant].sale - salePrice;
							if (priceDiff > 0) {
								specSets[i].labels[j].innerHTML = dropPrefix + 'Add ' + currency(priceDiff);
							} else if (priceDiff < 0) {
								specSets[i].labels[j].innerHTML = dropPrefix + 'Subtract ' + currency(-priceDiff);
							} else {
								specSets[i].labels[j].innerHTML = dropPrefix + '--';
							}
						}
					} else {
						if (input[j].title) {
							specSets[i].labels[j].innerHTML = dropPrefix + '!';
						} else {
							specSets[i].labels[j].innerHTML = '<img src="http://layout.tacticalstore.com/tactical-store/images/warning-icon.png" width="22" height="19" align="right" alt="Unavailable with current selection">';
						}
					}
				}
			}
		}
	},
	
	setPmods = function (thisSet, thisOpt, update, setNum) {
		var variant, dropPrefix, priceDiff, pmodVal, pmodPercent, newVal, spaces,
		current = getVariant();
		pmodVal = thisSet.values[thisOpt.id] - thisSet.values[thisSet.selected];
		pmodPercent = thisSet.percent[thisOpt.id] - thisSet.percent[thisSet.selected];
		thisSet.selected = thisOpt.id;
		for (variant in optionJson) {
			if (optionJson[variant].sale) {
				if (!optionJson[variant].pmod) {
					optionJson[variant].pmod = 0;
				}
				optionJson[variant].pmod += pmodVal + parseFloat((optionJson[variant].sale * pmodPercent).toFixed(2));
			}
		}
		for (i = 0, l = thisSet.inputs.length; i < l; i++) {
			if (thisSet.inputs[i].title) {
				spaces = (longestName[setNum] - thisSet.inputs[i].title.length) + 3;
				dropPrefix = thisSet.inputs[i].title;
				for (j = 0; j < spaces; j++) {
					dropPrefix += '&nbsp;';
				}
			} else {
				dropPrefix = '';
			}
			if (thisSet.inputs[i].id === thisSet.selected) {
				thisSet.labels[i].innerHTML = dropPrefix + 'Included in Price';
			} else {
				priceDiff = thisSet.values[thisSet.inputs[i].id] - thisSet.values[thisSet.selected];
				pmodPercent = thisSet.percent[thisSet.inputs[i].id] - thisSet.percent[thisSet.selected];
				priceDiff += parseFloat((pmodPercent * (optionJson[current.sorted].sale - optionJson[current.sorted].override)).toFixed(2));
				if (priceDiff > 0) {
					thisSet.labels[i].innerHTML = dropPrefix + 'Add ' + currency(priceDiff);
				} else if (priceDiff < 0) {
					thisSet.labels[i].innerHTML = dropPrefix + 'Subtract ' + currency(-priceDiff);
				} else {
					thisSet.labels[i].innerHTML = dropPrefix + '--';
				}
			}
			if (thisSet.percent[thisSet.inputs[i].id] > 0) {
				newVal = thisSet.percent[thisSet.inputs[i].id] * (optionJson[current.sorted].sale - optionJson[current.sorted].override);
				if (thisSet.inputs[i].value.match(/%\d+/)) {
					thisSet.inputs[i].value = thisSet.inputs[i].value.replace(/%\d+/, newVal.toFixed(2));
				} else if (thisSet.inputs[i].value.match(/\$\d+(\.\d{1,2})?/)) {
					thisSet.inputs[i].value = thisSet.inputs[i].value.replace(/\$\d+(\.\d{1,2})?/, newVal.toFixed(2));
				}
			}
		}
		if (update) {
			updateDisplay(false);
		}
	},
	
	clearLabels = function (current) {
		var set, tempVariant, dropPrefix, spaces;
		for (i = 0, l = specSets.length; i < l; i++) {
			set = specSets[i];
			for (j = 0, k = set.labels.length; j < k; j++) {
				if (set.inputs[j].title) {
					spaces = (longestName[i] - set.inputs[j].title.length) + 3;
					dropPrefix = set.inputs[j].title;
					for (x = 0; x < spaces; x++) {
						dropPrefix += '&nbsp;';
					}
				} else {
					dropPrefix = '';
				}
				tempVariant = current.unsorted.slice(1, current.unsorted.length - 1).split('-');
				tempVariant[i] = set.inputs[j].id.replace('spec-', '');
				tempVariant = tempVariant.sort(numberSort);
				tempVariant = '-' + tempVariant.join('-') + '-';
				if (optionJson[tempVariant]) {
					if (optionJson[tempVariant].override > 0) {
						specSets[i].labels[j].innerHTML = dropPrefix + ' Too low to show';
					} else {
						set.labels[j].innerHTML = dropPrefix + '--';
					}
				} else {
					if (set.inputs[j].title) {
						specSets[i].labels[j].innerHTML = dropPrefix + '!';
					} else {
						specSets[i].labels[j].innerHTML = dropPrefix + '<img src="http://layout.tacticalstore.com/tactical-store/images/warning-icon.png" width="22" height="19" align="right" alt="Unavailable with current selection">';
					}
				}
			}
		}
	},
	
	recurse = function (set, n, variant) {
		var i, l, code, final;
		n += 1;
		for (i = 0, l = set.length; i < l; i++) {
			variant += set[i];
			if (i > 0) {
				variant = variant.replace(set[i-1], '');
			}
			if (sets[n]) {
				final = recurse(sets[n], n, variant);
				if (final) {
					return final;
				}
			} else {
				for (code in optionJson) {
					if (code === variant) {
						variant = code.slice(1, code.length-1);
						return variant.split('-');
					}
				}
			}
		}
		return false;
	},
	
	fixStarterOpts = function () {
		var opt, firstOpts;
		if (sets[0]) {
			firstOpts = recurse(sets[0], 0, '-');
			if (firstOpts) {
				for (i = 0, l = firstOpts.length; i < l; i++) {
					opt = document.getElementById('spec-' + firstOpts[i]);
					if (opt) {
						opt.checked = true;
						opt.selected = 'selected';
						specSets[i].selected = firstOpts[i];
					}
				}
			}
		}
		updateDisplay(true);
	},
	
	updateDisplay = function (updateOpts, fix) {
		var current = getVariant();
		if (optionJson[current.sorted]) {
			if (!optionJson[current.sorted].pmod) {
				optionJson[current.sorted].pmod = 0;
			}
			setPrices(optionJson[current.sorted].sale, optionJson[current.sorted].price, optionJson.rebate, optionJson[current.sorted].variant, optionJson[current.sorted].pmod, optionJson[current.sorted].override, optionJson[current.sorted].upc, optionJson[current.sorted].sku);
			if (updateOpts) {
				if (optionJson[current.sorted].override > 0) {
					clearLabels(current);
				} else {
					setOptions(current, optionJson[current.sorted].sale);
				}
			}
			for (i = 0, l = pmodSets.length; i < l; i++) {
				if (pmodSets[i]) {
					setPmods(pmodSets[i], pmodSets[i].inputs[pmodSets[i].selected], false, i);
				}
			}
			if (cartButton && headblockRight) {
				cartButton.disabled = '';
				cartButton.parentNode.className = '';
				headblockRight.className = '';
			}
		} else {
			if (fix) {
				fixStarterOpts();
			} else {
				clearLabels(current);
				if (cartButton && headblockRight) {
					cartButton.disabled = 'disabled';
					cartButton.parentNode.className = 'fade-cart-button';
					headblockRight.className = 'invalid-options';
				}
			}
		}
	},
	
	updateSelected = function (set, type, dropdown) {
		return function () {
			var thisOpt, thisSet, dropPrefix;
			if (type === 'specs') {
				thisSet = specSets[set];
			} else {
				thisSet = pmodSets[set];
			}
			if (dropdown) {
				for (i = 0, l = thisSet.inputs.length; i < l; i++) {
					if (thisSet.inputs[i].selected) {
						thisOpt = thisSet.inputs[i];
						break;
					}
				}
			} else {
				thisOpt = this;
			}
			if (type === 'specs') {
				thisSet.selected = thisOpt.id.replace('spec-', '');
				updateDisplay(true);
			} else {
				setPmods(thisSet, thisOpt, true, set);
			}
		};
	},
	
	getBundleInfo = function () {
		var bObj, bValues = [], bLabels = [],
		inputs = bundlesTable.getElementsByTagName('input');
		for (i = 0, l = inputs.length; i < l; i++) {
			if (inputs[i].id !== 'crosssell-off') {
				if (inputs[i].value.match(/[\+|\-]\$\d+(\.\d{1,2})?/)) {
					bValues.push(parseFloat(inputs[i].value.match(/[\+|\-]\$\d+(\.\d{1,2})?/)[0].replace(/[\+|\-]\$/, '')));
				} else {
					bValues.push(0);
				}
				bLabels.push(document.getElementById(inputs[i].id.replace('crosssell-bundle', 'crossaddbundle')));
			}
		}
		bObj = {
			'values' : bValues,
			'labels' : bLabels
		};
		return bObj;
	},
	
	addErrorDiv = function () {
		var div = document.createElement('div'), div2 = document.createElement('div');
		div.id = 'options-error-msg';
		div.innerHTML = 'Selected combination is unavailable<p>Options unavailable with the currently selected combination are marked with warning icons. Please select a different combination of options.</p>';
		headblockRight.insertBefore(div, headblockRight.firstChild);
	},
	
	enableOptions = function (tag) {
		var opts = form.getElementsByTagName(tag);
		for (i = 0, l = opts.length; i < l; i++) {
			opts[i].disabled = false;
		}
	};
	
	// init
	if (optionDiv && form) {
		form.reset();
		enableOptions('input');
		enableOptions('select');
		form.className = 'js-enabled';
		if (bundlesTable) {
			bundle = getBundleInfo();
		}
		variantInput.type = 'hidden';
		variantInput.name = 'Variant';
		form.appendChild(variantInput);
		addErrorDiv();
		tables = optionDiv.getElementsByTagName('table');
		for (i = 0, l = tables.length; i < l; i++) {
			if (tables[i].className === 'specs' || tables[i].className === 'pmod') {
				labelOpts = [];
				pmodPercent = [];
				tempSets = [];
				longestName[i] = 0;
				selectOpt = tables[i].getElementsByTagName('select');
				if (selectOpt[0]) {
					inputOpts = selectOpt[0].getElementsByTagName('option');
					selectOpt[0].onchange = updateSelected(i, tables[i].className, true);
				} else {
					inputOpts = tables[i].getElementsByTagName('input');
				}
				for (j = 0, k = inputOpts.length; j < k; j++) {
					tempSets.push(inputOpts[j].id.replace('spec-', '') + '-');
					if (inputOpts[j].title) {
						labelOpts[j] = inputOpts[j];
						if (inputOpts[j].title.length > longestName[i]) {
							longestName[i] = inputOpts[j].title.length;
						}
					} else {
						inputOpts[j].onclick = updateSelected(i, tables[i].className, false);
						labelOpts[j] = document.getElementById('add' + inputOpts[j].id);
						if (ieVersion > 7) {
							labelOpts[j] = labelOpts[j].parentNode;
						}
					}
					if (inputOpts[j].value.match(/%\d+/)) {
						pmodPercent[inputOpts[j].id] = inputOpts[j].value.match(/%\d+/)[0].replace('%', '');
						pmodPercent[inputOpts[j].id] = pmodPercent[inputOpts[j].id] / 100;
					} else {
						pmodPercent[inputOpts[j].id] = 0;
					}
					if (inputOpts[j].value.match(/\$\d+(\.\d{1,2})?/)) {
						pmodValues[inputOpts[j].id] = inputOpts[j].value.match(/\$\d+(\.\d{1,2})?/)[0].replace('$', '');
						pmodValues[inputOpts[j].id] = parseFloat(pmodValues[inputOpts[j].id]);
					} else {
						pmodValues[inputOpts[j].id] = 0;
					}
				}
				if (tables[i].className === 'specs') {
					specSets[i] = {
						'selected' : inputOpts[0].id.replace('spec-', ''),
						'inputs' : inputOpts,
						'labels' : labelOpts
					};
					sets.push(tempSets);
				} else {
					pmodSets[i] = {
						'selected' : inputOpts[0].id,
						'inputs' : inputOpts,
						'values' : pmodValues,
						'labels' : labelOpts,
						'percent' : pmodPercent
					};
				}
			}
		}
		updateDisplay(true, true);
		for (set in pmodSets) {
			if (pmodSets[set]) {
				setPmods(pmodSets[set], pmodSets[set].inputs[0], true, set);
			}
		}
	}
}
