// Product page scripts

function RecentlyViewed(page, containerId, varName) {
	var cookie = new Cookie('__viewed'),
	j = 2,
	container = document.createElement('div'),
	mainPanel = document.getElementById('main-panel'),
	bottomCrumbs = document.getElementById('breadcrumbs_bottom'),
	
	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 + '.opticsforyou.com/cart/' + obj.id + '.gif';
		}
		div.innerHTML = '<a href="' + obj.id + '.html"><img src="' + obj.i + '" width="70" height="70" alt="' + obj.n + '">' + obj.n + '</a><div>$' + 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 + '.opticsforyou.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);
			mainPanel.insertBefore(container, bottomCrumbs);
		}
	};
	
	// init
	if (mainPanel && bottomCrumbs) {
		container.id = containerId;
		container.className = 'no-yahoo-related';
		container.innerHTML = '<div style="clear:both;"></div>';
		handleCookie();
	}
}

function OptionHandler() {
	var tables, i, l, inputOpts, labelOpts, specSets = [], pmodSets = [], j, k, x, pmodValues = [], bundle = null, selectOpt, pmodPercent, tempSets, sets = [], set, longestName = [], tooLowTip = false,
	optionDiv = document.getElementById('options'),
	variantInput = document.createElement('input'),
	form = document.getElementById('addToCartForm'),
	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'),
	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, variantId) {
		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) {
			if (override > 0) {
				saleEl.innerHTML = '<a class="toolow">too low to show</a>';
				if (tooLowTip) {
					tooLowTip.resetTip(saleEl.getElementsByTagName('a')[0]);
				} else {
					tooLowTip = new TipBox(saleEl.getElementsByTagName('a')[0], 'This indicates an additional discount is in effect. Due to MAP (Minimum Advertised Price) Policy we cannot display the discounted price here.', false);
				}
			} else {
				saleEl.innerHTML = currency(sale).replace('.', '<span>') + '</span>';
			}
		}
		if (priceEl) {
			if (regPrice === 0) {
				priceEl.parentNode.style.visibility = 'hidden';
			} else {
				priceEl.parentNode.style.visibility = 'visible';
				priceEl.innerHTML = currency(price);
			}
		}
		if (youSaveEl) {
			if (override > 0 || regPrice === 0) {
				youSaveEl.parentNode.style.visibility = 'hidden';
			} else {
				youSaveEl.parentNode.style.visibility = 'visible';
				youSaveEl.innerHTML = currency(youSave) + ' (' + savePercent + '%)';
			}
		}
		if (rebateEl) {
			if (override > 0) {
				rebateEl.parentNode.style.visibility = 'hidden';
			} else {
				rebateEl.parentNode.style.visibility = 'visible';
				rebateEl.innerHTML = currency(sale - rebate);
			}
		}
		if (prodCode) {
			prodCode.innerHTML = code;
		}
		if (prodUpc) {
			if (upc) {
				prodUpc.parentNode.style.visibility = 'visible';
				prodUpc.innerHTML = upc;
			} else {
				prodUpc.parentNode.style.visibility = 'hidden';
			}
		}
		if (prodSku) {
			if (sku) {
				prodSku.parentNode.style.visibility = 'visible';
				prodSku.innerHTML = sku;
			} else {
				prodSku.parentNode.style.visibility = 'hidden';
			}
		}
		if (variantId) {
			variantInput.value = variantId;
		}
		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.visibility = (sale < 29.95 || override > 0) ? 'hidden' : 'visible';
		}
	},
	
	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]) {
						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 {
							if (specSets[i].labels[j]) {
								specSets[i].labels[j].innerHTML = '<img src="http://layout.opticsforyou.com/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].getAttribute('rel') && thisSet.inputs[i].getAttribute('rel').match(/%\d+/)) {
					thisSet.inputs[i].getAttribute('rel') = thisSet.inputs[i].getAttribute('rel').replace(/%\d+/, currency(newVal));
				} else if (thisSet.inputs[i].getAttribute('rel') && thisSet.inputs[i].getAttribute('rel').match(/\$\d+(\.\d{1,2})?/)) {
					thisSet.inputs[i].getAttribute('rel') = thisSet.inputs[i].getAttribute('rel').replace(/\$\d+(\.\d{1,2})?/, currency(newVal));
				}
			}
		}
		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]) {
					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.opticsforyou.com/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, optionJson[current.sorted].variant_id);
			if (optionJson[current.sorted].override > 0) {
				clearLabels(current);
			} else {
				if (updateOpts) {
					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) {
		enableOptions('input');
		enableOptions('select');
		form.className = 'js-enabled';
		if (bundlesTable) {
			bundle = getBundleInfo();
		}
		variantInput.type = 'hidden';
		variantInput.name = 'variant_id';
		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 (labelOpts[j] && ieVersion > 7) {
							labelOpts[j] = labelOpts[j].parentNode;
						}
					}
					if (inputOpts[j].getAttribute('rel') && inputOpts[j].getAttribute('rel').match(/%\d+/)) {
						pmodPercent[inputOpts[j].id] = inputOpts[j].getAttribute('rel').match(/%\d+/)[0].replace('%', '');
						pmodPercent[inputOpts[j].id] = pmodPercent[inputOpts[j].id] / 100;
					} else {
						pmodPercent[inputOpts[j].id] = 0;
					}
					if (inputOpts[j].getAttribute('rel') && inputOpts[j].getAttribute('rel').match(/\$\d+(\.\d{1,2})?/)) {
						pmodValues[inputOpts[j].id] = inputOpts[j].getAttribute('rel').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
					};
				}
			}
		}
		if (specSets.length > 0 || pmodSets.length > 0) {
			updateDisplay(true, true);
			for (set in pmodSets) {
				if (pmodSets[set] && pmodSets[set].inputs) {
					setPmods(pmodSets[set], pmodSets[set].inputs[0], true, set);
				}
			}
		}
	}
}
