var oldIE = false, jsonVoorhees = [], searchBoxHelp, cookiesForBridge = [], headerBanners;

function getIEVersion() {
	var version = -1, usrAgt, regExp;
	if (navigator.appName === 'Microsoft Internet Explorer') {
		usrAgt = navigator.userAgent;
		regExp = new RegExp('MSIE ([0-9]{1,}[.0-9]{0,})');
		if (regExp.exec(usrAgt) !== null) {
			version = parseFloat(regExp.exec(usrAgt)[1]);
		}
	}
	return version;
}

// returns an array of all tags of a certain class
function getElementsByClassName(obj, theClass, theTag) {
	var allTagsWithClass = [],
		thisTag, i;
	
	for (i = 0; (thisTag = obj.getElementsByTagName(theTag ? theTag : '*')[i]); i++) {
		if (thisTag.className === theClass) {
			allTagsWithClass.push(thisTag);
		}
	}
	return allTagsWithClass;
}

function createEl(elType, elExtras, elParent) {
	var attribute,
	el = document.createElement(elType);
	for (attribute in elExtras) {
		if (elExtras[attribute] !== '') {
			if (attribute === 'class') {
				el.setAttribute('className', elExtras[attribute]);
			}
			el.setAttribute(attribute, elExtras[attribute]);
		}
	}
	if (elParent) {
		elParent.appendChild(el);
	}
	return el;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g, '');
}

function stripTags(str) {
	return str.replace(/(<([^>]+)>)/ig, '').replace(/\&amp;/g, '&');
}

// Adds script tag to head of the page
function addScriptToHead(source, code, type) {
	var script = document.createElement('script');
	if (type === 'js') {
		script.setAttribute('type', 'text/javascript');
	}
	if (source !== '') {
		script.setAttribute('src', source);
	}
	if (code !== '') {
		if (document.all && !window.opera)	{
			script.text = code;
		} else {
			script.innerHTML = code;
		}
	}
	document.getElementsByTagName('head')[0].appendChild(script);
}

// Cookie handling
function Cookie(name) {
	this.setValue = function (value, hours, bridge) {
		var cookieString, date;
		cookieString = name + "=" + escape(value);
		if (hours) {
			date = new Date();
			date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
			cookieString += "; expires=" + date.toGMTString();
		}
		cookieString += "; path=/";
		document.cookie = cookieString;
		if (bridge) {
			// send cookie info to check in
			cookiesForBridge.push(cookieString);
		}
	};
	
	this.getValue = function () {
		var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
		return results ? unescape(results[2]) : null;
	};
	
	this.remove = function () {
		this.setValue("", -1);
	};
}

/// Question and Answer
function QNA() {
	var lastHash, containers, page, cookie, checkHash, eventOverOut, eventClick, qNaCurrent, theQuestion, i, objectList, cookieVal, num;
	lastHash = null;
	containers = [];
	page = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
	cookie = new Cookie(page);

	// Check if we need to follow an anchor
	checkHash = function () {
		return function () {
			var sectionToDisplay;
			if (document.location.hash && lastHash !== document.location.hash) {
				lastHash = document.location.hash;
				sectionToDisplay = document.getElementById(document.location.hash.split('#')[1]);
				if (sectionToDisplay && sectionToDisplay.className === 'collapsible-content-question hide-answer') {
					sectionToDisplay.className = sectionToDisplay.className.replace(new RegExp(" hide-answer\\b"), "");
				}
			}
		};
	};
	
	// returns an event handler for Q&A mouse over and out events
	eventOverOut = function () {
		return function (e) {
			if (this.className === 'qna-question') {
				this.className += ' qna-hover';
			} else {
				this.className = this.className.replace(new RegExp(" qna-hover\\b"), "");
			}
		};
	};
	
	// returns an event handler for Q&A click
	eventClick = function () {
		return function (e) {
			var i, newValue;
			if (this.parentNode.className === 'collapsible-content-question') {
				this.parentNode.className += ' hide-answer';
				if (document.location.hash) {
					if (this.parentNode.id === document.location.hash.split("#")[1]) {
						document.location.hash = '';
					}
				}
			} else {
				this.parentNode.className = this.parentNode.className.replace(new RegExp(" hide-answer\\b"), "");
			}
			
			// sets a cookie to tell us which qna's were open
			newValue = '|';
			for (i = 0; i < containers.length; i += 1) {
				if (containers[i].className === 'collapsible-content-question') {
					if (i < 10) {
						newValue += '0';
					}
					newValue += i + '|';
				}
			}
			cookie.setValue(newValue);
		};
	};
	
	// init this thing
	objectList = document.getElementById('object-list');
	if (objectList) {
		containers = getElementsByClassName(objectList, 'collapsible-content-question', 'div');
		containers = containers.concat(getElementsByClassName(objectList, 'collapsible-content-question', 'span'));
		if (containers.length > 0) {
			// checks cookie to see which qna's were left open last time they were on this page
			cookieVal = cookie.getValue();
			for (i = 0; i < containers.length; i += 1) {
				qNaCurrent = containers[i];
				if (cookieVal) {
					num = (i < 10) ? '0' + i : i;
					qNaCurrent.className += (cookieVal.match(num)) ? '' : ' hide-answer';
				} else {
					qNaCurrent.className += ' hide-answer';
				}
				
				theQuestion = getElementsByClassName(qNaCurrent, 'qna-question', 'div');
				if (theQuestion.length > 0) {
					theQuestion = theQuestion[0];
					theQuestion.innerHTML = theQuestion.innerHTML.replace("<span>", "").replace("</span>", ""); // temp fix for Chrome
					theQuestion.onmouseover = eventOverOut();
					theQuestion.onmouseout = eventOverOut();
					theQuestion.onclick = eventClick();
				}
			}
			window.setInterval(checkHash(), 200);
		}
	}
}

// Recently Viewed History
function History() {
	var rightPanel, rightPanelBox, currentPage, pageHeader, menuBox, urls, titles, urlCookie, titleCookie, currentUrl, currentTitle, theList, checkCookies, newCookies, eventOverOut, createList, createButton, collapseMe, changeButton, fixIE6, listStart, collapseAfter;
	urls = [];
	titles = [];
	urlCookie = new Cookie('_historyUrl');
	titleCookie = new Cookie('_historyTitle');
	currentUrl = location.href;
	currentTitle = '';
	theList = null;
	listStart = 0;
	collapseAfter = 4;
	
	// Look for cookies, if exist then grab the info from them
	checkCookies = function () {
		var titleValue, urlValue, i;
		urlValue = urlCookie.getValue();
		titleValue = titleCookie.getValue();
		if (urlValue && titleValue) {
			urls = urlValue.split('|\/|');
			titles = titleValue.split('|\/|');
			
			for (i = 0; i < urls.length; i++) {
				if (urls[i] === currentUrl) {
					urls.splice(i, 1);
					titles.splice(i, 1);
				}
			}
	
			if (urls.length > 8) {
				urls.splice(8, urls.length - 8);
				titles.splice(8, titles.length - 8);
			}
		}
	};
	
	// Set new cookies with updated info
	newCookies = function () {
		var newUrls, newTitles, i;
		for (i = 0; i < urls.length; i++) {
			if (i === 0) {
				newUrls = urls[i];
				newTitles = titles[i];
			} else {
				newUrls += '|\/|';
				newUrls += urls[i];
				newTitles += '|\/|';
				newTitles += titles[i];
			}
		}
		newTitles = newTitles.replace(new RegExp('&amp;', 'g'), '&');
		urlCookie.setValue(newUrls, false, true);
		titleCookie.setValue(newTitles, false, true);
	};
	
	// Mouse over/out event for list items and more-less button
	eventOverOut = function () {
		return function (e) {
			var itemToChange;
			if (this.href) {
				itemToChange = this.parentNode.parentNode;
				itemToChange.className = (itemToChange.className === 'history-hover') ? '' : 'history-hover';
			} else {
				itemToChange = this.childNodes[0];
				itemToChange.className = (itemToChange.className === 'bundles-button') ? 'bundles-button-hover' : 'bundles-button';
			}
		};
	};
	
	// Creates the list of links and places them into the page
	createList = function () {
		var listItem, listLink, i;
		theList = document.getElementById('recently-viewed-list');
		if (theList) {
			for (i = listStart; i < urls.length; i++) {
				listItem = document.createElement('li');
				
				listLink = document.createElement('a');
				listLink.innerHTML = titles[i];
				listLink.href = urls[i];
				
				listLink.onmouseover = eventOverOut();
				listLink.onmouseout = eventOverOut();
				
				listItem.appendChild(listLink);
				theList.appendChild(listItem);
			}
		}
	};
	
	// Creates the more-less button and places it into bottom of list
	createButton = function () {
		if (theList) {
			var buttonLi, buttonSpan, buttonSpan2;
			buttonLi = document.createElement('li');
			buttonLi.className = 'history-button';
			buttonLi.onclick = changeButton();
			buttonLi.onmouseover = eventOverOut();
			buttonLi.onmouseout = eventOverOut();
			
			buttonSpan = document.createElement('span');
			buttonSpan.className = 'bundles-button';
			
			buttonSpan2 = document.createElement('span');
			buttonSpan2.className = 'selectors-button-more';
			buttonSpan2.innerHTML = 'More';
			
			buttonSpan.appendChild(buttonSpan2);
			buttonLi.appendChild(buttonSpan);
			theList.appendChild(buttonLi);
		}
	};
	
	// Collapses any links after the first 4
	collapseMe = function () {
		var listItems, i;
		listItems = theList.childNodes;
		for (i = 4; i < listItems.length - 1; i++) {
			listItems[i].className = (listItems[i].className === 'history-hide') ? '' : 'history-hide';
		}
	};
	
	// Switches the more-less button and calls for the collapse
	changeButton = function () {
		return function (e) {
			var button = this.childNodes[0].childNodes[0];
			if (button) {
				button.className = (button.className === 'selectors-button-more') ? 'selectors-button-less' : 'selectors-button-more';
				button.innerHTML = (button.innerHTML === 'More') ? 'Less' : 'More';
			}
			collapseMe();
		};
	};
	
	// Handles max-height issue for ie6
	fixIE6 = function () {
		var listItems, i;
		listItems = theList.childNodes;
		for (i = 0; i < listItems.length; i++) {
			listItems[i].style.height = (listItems[i].offsetHeight > 15) ? '30px' : '15px';
		}
	};
	
	// init
	rightPanel = document.getElementById('right-panel');
	if (rightPanel) {
		rightPanelBox = getElementsByClassName(rightPanel, 'menu-box', 'div')[0];
		if (rightPanelBox) {
			currentPage = document.getElementById('main-panel');
			pageHeader = currentPage ? currentPage.getElementsByTagName('h1')[0] : null;
			currentTitle = pageHeader ? pageHeader.innerHTML : document.title;
			checkCookies();
			if (currentTitle !== 'Error, page not found') {
				urls.unshift(currentUrl);
				titles.unshift(currentTitle);
				listStart = 1;
				collapseAfter = 5;
			}
			newCookies();
			if (urls.length > 1) {
				menuBox = document.createElement('div');
				menuBox.className = 'menu-box menu-box-multiline';
				menuBox.innerHTML = '<ul><li>Recently Viewed<ul id="recently-viewed-list"></ul></li></ul>';
				rightPanel.insertBefore(menuBox, rightPanelBox.nextSibling);
				
				createList();
				if (urls.length > collapseAfter) {
					createButton();
					collapseMe();
				}
				if (oldIE) {
					fixIE6();
				}
			}
		}
	}
}

// Called by cookie bridge
function op_bridgeCrossed(json) {
	var cookie, recentlyViewedHistory;
	for (cookie in json) {
		if (cookie) {
			document.cookie = cookie + '=' + json[cookie];
		}
	}
	recentlyViewedHistory = new History();
	
	// load up google analytics
	addScriptToHead((('https:' === document.location.protocol) ? 'https://ssl.' : 'http://www.') + 'google-analytics.com/ga.js', '', 'js');
	googleAnalytics();
}

// Top Nav Dropdown
function DropTop() {
	var navBar, linkTopPos, navLinks, dropLinks, button, theList, timer, hideMe, lastWidth, cloneWars, eventOverOut, hideList, createButton, createList, showAndTell;
	navBar = document.getElementById('header-nav-bar');
	navLinks = [];
	dropLinks = [];
	button = document.createElement('a');
	theList = document.createElement('ul');
	timer = null;
	hideMe = false;
	lastWidth = null;
	
	// Hides the dropdown after timer goes off if mouse is not still over
	hideList = function () {
		return function () {
			theList.className = hideMe ? 'top-nav-hidden' : '';
		};
	};
	
	// Mouse over and out event to show and hide dropdown
	eventOverOut = function () {
		return function (e) {
			if (theList.className === 'top-nav-hidden' || timer !== null) {
				window.clearTimeout(timer);
				timer = null;
				hideMe = false;
				theList.className = '';
			} else {
				timer = window.setTimeout(hideList(), 700);
				hideMe = true;
			}
		};
	};
	
	// Sets dropdown list items to hide or show based on its clone's location in nav bar
	showAndTell = function () {
		return function () {
			if (lastWidth !== document.body.offsetWidth) {
				lastWidth = document.body.offsetWidth;
				var listItems, showDrop, hideMeLinks, i;
				hideMeLinks = [];
				listItems = theList.childNodes;
				showDrop = false;
				for (i = 0; i < navLinks.length; i++) {
					navLinks[i].className = '';
					if (navLinks[i].offsetTop > linkTopPos) {
						if (!showDrop && i !== 0) {
							hideMeLinks.push(navLinks[i - 1]);
							listItems[i - 1].className = '';
							showDrop = true;
						}
						hideMeLinks.push(navLinks[i]);
						listItems[i].className = '';
					} else {
						listItems[i].className = 'top-nav-hidden';
					}
				}
				for (i = 0; i < hideMeLinks.length; i++) {
					hideMeLinks[i].className = 'top-nav-hidden';
				}
				button.className = showDrop ? '' : 'top-nav-hidden';
				theList.style.left = button.offsetLeft + 150 + 'px';
			}
		};
	};
	
	// Creates the list and places in page hidden until needed
	createList = function () {
		var listItem, i, footer;
		theList.id = 'top-nav-dd-list';
		theList.className = 'top-nav-hidden';
		
		for (i = 0; i < dropLinks.length; i++) {
			listItem = document.createElement('li');
			listItem.appendChild(dropLinks[i]);
			listItem.onmouseover = eventOverOut();
			listItem.onmouseout = eventOverOut();
			theList.appendChild(listItem);
		}
		
		footer = document.getElementById('footer');
		if (footer) {
			footer.appendChild(theList);
		} else {
			navBar.appendChild(theList);
		}
		showAndTell();
		window.setInterval(showAndTell(), 500);
	};
	
	// Create more button and place in top nav hidden until needed
	createButton = function () {
		button.id = 'top-nav-more-button';
		button.className = 'top-nav-hidden';
		button.innerHTML = 'More';
		button.onmouseover = eventOverOut();
		button.onmouseout = eventOverOut();
		navBar.appendChild(button);
		createList();
	};
	
	// Clone the nav links to use in dropdown
	cloneWars = function () {
		var navBarKids, i, navKids = [];
		navBarKids = navBar.childNodes;
		for (i = 0; i < navBarKids.length; i++) {
			if (navBarKids[i].style) {
				navKids.push(navBarKids[i]);
			}
		}
		linkTopPos = navKids[0].offsetTop;
		for (i = 6; i < navKids.length; i++) {
			navLinks.push(navKids[i]);
			dropLinks.push(navKids[i].cloneNode(true));
		}
		createButton();
	};
	
	// super clean looking init lol
	if (navBar) {
		cloneWars();
	}
}

// Bundle hide and seek
function Bundles() {
	var table, i, tbody, rows, span1, span2, hideShow, eventOverOut, createButtonRow;
	tbody = null;
	rows = null;
	span1 = document.createElement('span');
	span2 = document.createElement('span');
	
	// Hides and shows the extra rows in bundles table
	hideShow = function () {
		return function () {
			var i;
			for (i = 4; i < rows.length - 2; i++) {
				rows[i].className = (rows[i].className === 'top-nav-hidden') ? '' : 'top-nav-hidden';
			}
			span1.className = (span1.className === 'selectors-button-more') ? 'selectors-button-less' : 'selectors-button-more';
			span1.innerHTML = (span1.innerHTML === 'More') ? 'Less' : 'More';
		};
	};
	
	// Mouse over event
	eventOverOut = function () {
		return function (e) {
			span2.className = (span2.className === 'bundles-button') ? 'bundles-button-hover' : 'bundles-button';
		};
	};
	
	// Creates the row, and its contents, for the more-less button
	createButtonRow = function () {
		var row, padCell, cell;
		span1.className = 'selectors-button-more';
		span1.innerHTML = 'More';
		
		span2.className = 'bundles-button';
		span2.appendChild(span1);
		
		cell = document.createElement('td');
		cell.className = 'optioninput';
		cell.colSpan = '2';
		cell.appendChild(span2);
		
		padCell = document.createElement('td');
		padCell.className = 'optioninputbox';
		padCell.innerHTML = '&nbsp;';
		
		row = document.createElement('tr');
		row.appendChild(padCell);
		row.appendChild(padCell.cloneNode(true));
		row.appendChild(cell);
		
		row.onclick = hideShow();
		row.onmouseover = eventOverOut();
		row.onmouseout = eventOverOut();
		
		tbody.insertBefore(row, rows[rows.length - 1]);
	};
	
	// init
	table = document.getElementById('bundles-table');
	if (table) {
		tbody = table.getElementsByTagName('tbody')[0];
		if (tbody) {
			rows = tbody.getElementsByTagName('tr');
			if (rows.length > 6) {
				for (i = 4; i < rows.length - 1; i++) {
					rows[i].className = 'top-nav-hidden';
				}
				createButtonRow();
			}
		}
	}
}

// Creates the tip boxes and handles the hiding and showing
function TipBox(tipParent, tipText, specialCase) {
	var tipBody, tipPointer, container, timer = null, showTip = false, x, y,
	parent = tipParent,
	text = tipText,
	
	hideShow = function () {
		return function () {
			if (showTip) {
				container.className = 'tip-container';
				x = (specialCase) ? x - 240 : x;
				container.style.top = y + 'px';
				container.style.left = x + 'px';
			} else {
				container.className = 'tip-container-hidden';
			}
			timer = null;
		};
	},
	
	// mouse over event
	eventOverOut = function () {
		return function (e) {
			if (container.className === 'tip-container-hidden') {
				if (timer === null) {
					if (!e) {
						e = window.event;
					}
					if (e.pageX || e.pageY) {
						x = e.pageX;
						y = e.pageY;
					} else if (e.clientX || e.clientY) {
						x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
						y = e.clientY + document.body.scrollTop	+ document.documentElement.scrollTop;
					}
					x -= 30;
					y += 10;
					showTip = true;
					timer = window.setTimeout(hideShow(), 300);
				} else {
					showTip = false;
					window.clearTimeout(timer);
					timer = null;
				}
			} else {
				if (timer === null) {
					showTip = false;
					timer = window.setTimeout(hideShow(), 300);
				} else {
					showTip = false;
					window.clearTimeout(timer);
					timer = null;
				}
			}
		};
	},
	
	// Wrap a parent in a span for styling
	wrapParent = function () {
		var guts, tipSpan;
		guts = parent.innerHTML;
		tipSpan = document.createElement('span');
		tipSpan.className = 'tip';
		tipSpan.innerHTML = guts;
		parent.innerHTML = '';
		parent.appendChild(tipSpan);
	},
	
	// Creates tip
	createTip = function () {
		var footer = document.getElementById('footer');
		
		tipBody = document.createElement('div');
		tipBody.className = 'tip-body';
		tipBody.innerHTML = text;
	
		tipPointer = document.createElement('div');
		tipPointer.className = 'tip-pointer';
		if (specialCase) {
			tipPointer.style.left = '250px';
		}
		
		container = document.createElement('div');
		container.className = 'tip-container-hidden';
		container.appendChild(tipBody);
		container.appendChild(tipPointer);
		container.onmouseover = eventOverOut();
		container.onmouseout = eventOverOut();
		
		footer.appendChild(container);
		
		parent.onmouseover = eventOverOut();
		parent.onmouseout = eventOverOut();
	};
	
	this.resetTip = function (newParent) {
		parent = newParent;
		wrapParent();
		parent.onmouseover = eventOverOut();
		parent.onmouseout = eventOverOut();
	};
	
	// init
	if (parent && text) {
		wrapParent();
		createTip();
	}
}

// Set tips and find the object to use it on then pass to TipBox
function TipYourServer() {
	var sortByLists, checkPb, checkSortBy, checkOptions, checkMp, checkRp, addCtoTips,
	priceblock = document.getElementById('priceblock'),
	sortBy = document.getElementById('sort-by-navigation-top'),
	sortBy2 = document.getElementById('sort-by-navigation-bottom'),
	rightPanel = document.getElementById('right-panel'),
	mainPanel = document.getElementById('main-panel'),
	optionsDiv = document.getElementById('options'),
	shipping = 'We offer <a href="http://www.opticsplanet.net/free-shipping.html" target="_blank" style="text-decoration:underline;">Free UPS Ground Shipping</a> to the lower 48 U.S. States and <a href="http://www.opticsplanet.net/free-shipping.html" target="_blank" style="text-decoration:underline;">Free USPS Priority Mail Shipping</a> to all U.S. Military APO/FPO/DPO on most orders over $29.95',
	rebate = 'This product has an active manufacturer rebate, which may be found in our <a href="http://www.opticsplanet.net/rebate.html" style="text-decoration:underline;">rebate</a> section.',
	demo = '<a href="http://www.opticsplanet.net/demo.html" style="text-decoration:underline;">Demo</a> products are dealer demo models, open box, or factory reconditioned units that are sold at a significant discount, but come with a warranty and our 100% satisfaction guarantee. Limited quantity, while supply lasts.',
	rebates = 'For a limited time Mail-in Manufacturer <a href="http://www.opticsplanet.net/rebate.html" style="text-decoration:underline;">Rebates</a> are being offered for these items.',
	tooLowText = 'This indicates an additional discount is in effect. Due to <a href="http://www.opticsplanet.net/map.html">MAP</a> (Minimum Advertised Price) Policy we cannot display the discounted price here.';
	
	// Add tip boxes for Call To Order products in contents around the page
	addCtoTips = function () {
		var ctoTips = getElementsByClassName(document, 'cto-tip-me', 'span'), i, l, tips = [], special;
		for (i = 0, l = ctoTips.length; i < l; i++) {
			special = (ctoTips[i].parentNode.parentNode.className === 'right-panel-specials-item') ? true : false;
			tips[i] = new TipBox(ctoTips[i], 'Please call our phone sales department toll free at 800-504-5897 or go to the product page and click the Call To Order button to fill out the form for more information on this item.', special);
		}
	};
	
	// Check main panel for too low to show prices
	checkMp = function () {
		var i, boxes = [],
		tooLowToShow = getElementsByClassName(mainPanel, 'toolow', '');
		for (i = 0; i < tooLowToShow.length; i++) {
			if (tooLowToShow[i].getElementsByTagName('span').length < 1) {
				boxes[i] = new TipBox(tooLowToShow[i], tooLowText);
			}
		}
	};
	
	// Check right panel for too low to show prices
	checkRp = function () {
		var i, boxes = [],
		tooLowToShow = getElementsByClassName(rightPanel, 'toolow', '');
		for (i = 0; i < tooLowToShow.length; i++) {
			boxes[i] = new TipBox(tooLowToShow[i], tooLowText, true);
		}
	};
	
	// Check Priceblock for free shipping or rebates to tip
	checkPb = function () {
		var shipTip, pbrTip,
		freeShip = document.getElementById('priceblock-free-shipping'),
		pbRebate = getElementsByClassName(priceblock, 'rebate', 'tr')[0];
		if (freeShip) {
			shipTip = new TipBox(freeShip, shipping);
		}
		if (pbRebate) {
			pbRebate = pbRebate.getElementsByTagName('td')[0];
			pbRebate.innerHTML = 'Available Rebate';
			pbrTip = new TipBox(pbRebate, rebate);
		}
	};
	
	// Check Sort by lists to tip demos or rebates
	checkSortBy = function () {
		var thisSortBy, liLink, li, i, j, boxes = [];
		for (j = 0; (thisSortBy = sortByLists[j]); j++) {
			for (i = 0; (li = thisSortBy.getElementsByTagName('li')[i]); i++) {
				liLink = li.getElementsByTagName('a')[0];
				if (liLink && liLink.innerHTML === 'Demo') {
					boxes.push(new TipBox(li, demo));
				} else if (liLink && liLink.innerHTML === 'Rebates') {
					boxes.push(new TipBox(li, rebates));
				}
			}
		}
	};
	
	// Check Options area for demos to tip
	checkOptions = function () {
		var demoRegExp, cellGuts, results, newText, i, demoTips,
		optionCells = getElementsByClassName(optionsDiv, 'optioninput', 'td');
		if (optionCells.length > 0) {
			demoRegExp = /(^|[^a-z0-9])(DE?MO)($|[^a-z0-9])/i;
			for (i = 0; i < optionCells.length; i++) {
				cellGuts = optionCells[i].innerHTML;
				if (cellGuts.match(demoRegExp) !== null) {
					results = cellGuts.match(demoRegExp);
					if (results.length > 3) {
						newText = results[1] + '<span class="option-demo-tip-me">' + results[2] + '</span>' + results[3];
					} else {
						newText = results[1] + '<span class="option-demo-tip-me">' + results[2] + '</span>';
					}
					cellGuts = cellGuts.replace(demoRegExp, newText);
					optionCells[i].innerHTML = cellGuts;
				}
			}
		}
		optionCells = getElementsByClassName(optionsDiv, 'option-demo-tip-me', 'span');
		if (optionCells.length > 0) {
			demoTips = [];
			for (i = 0; i < optionCells.length; i++) {
				demoTips[i] = new TipBox(optionCells[i], demo);
			}
		}
	};
	
	// init
	addCtoTips();
	if (priceblock) {
		checkPb();
	}
	if (sortBy && sortBy2) {
		sortByLists = [sortBy, sortBy2];
		checkSortBy();
	}
	if (optionsDiv) {
		checkOptions();
	}
	if (rightPanel) {
		checkRp();
	}
	if (mainPanel) {
		checkMp();
	}
}

function Selectors(listNum) {
	var subList, subListItems, collapse, numNonCollapse, localCollapseAfter, button, i, j, trimHeight, resize, tick, singleClick, eventClick, eventOverOut, subListParent, parentWidth, imageInSelectors, subListItem, mainList, flashButton = false, linkOverOut, 
	container = document.getElementById('object-list'),
	subLists = null, // contains the sublists
	totalWidths = 20, // contains total width of all sublists
	eachWidth = [], // contains orig widths of each sublist
	maxWidth = 0, // contains lagest single width of the sublists
	collapseAfter = 5, // number to start collapsing items after
	currentList = null, // list the mouse is over
	lastList = null, // last list mouse was over
	tickout = 0, // tick count
	reqTicks = 66, // must be even
	lastWidth = 0; // width of window to check if resize code should run
	mainList = getElementsByClassName(container, 'sub-page-selector', 'ul')[listNum];
	
	// handles resizing the height of unfilled selectors
	trimHeight = function (start, end) {
		var subListItems, length, newHeight, i;
		length = 0;
		for (i = start; i < end; i++) {
			subListItems = subLists[i].getElementsByTagName('li');
			length = (subListItems.length > length) ? subListItems.length : length;
		}
		if (length < 6) {
			for (i = start; i < end; i++) {
				newHeight = 19;
				newHeight += length * 20;
				subLists[i].parentNode.style.maxHeight = newHeight + 'px';
				subLists[i].parentNode.style.minHeight = newHeight + 'px';
				subLists[i].parentNode.style.height = (oldIE) ? newHeight + 'px' : '';
			}
		} else {
			for (i = start; i < end; i++) {
				subLists[i].parentNode.style.maxHeight = '';
				subLists[i].parentNode.style.minHeight = '';
				subLists[i].parentNode.style.height = (oldIE) ? '135px' : '';
			}
		}
	};
	
	// handles resizing selectors
	resize = function () {
		return function () {
			var subList, single, lastTop, i, j;
			if (lastWidth !== document.body.offsetWidth) {
				lastWidth = document.body.offsetWidth;
				if (subLists.length > 1) {
					lastTop = 0;
					j = 0;
					for (i = 0; i < subLists.length; i++) {
						subList = subLists[i];
						subListParent = subList.parentNode;
						single = (subListParent.className === 'single-selectors-more' || subListParent.className === 'single-selectors-less') ? true : false;
						
						if (totalWidths < container.offsetWidth) {
							if (document.all && (i + 1) === subList.length) {
								subListParent.style.marginRight = '1';
							}
							subListParent.style.width = eachWidth[i] + 'px';
							if (single) {
								subListParent.style.backgroundPosition = eachWidth[i] - 10 + 'px 9px';
							}
						} else {
							if (document.all && (i + 1) === subList.length) {
								subListParent.style.marginRight = '10';
							}
							subListParent.style.width = maxWidth + 'px';
							if (single) {
								subListParent.style.backgroundPosition = maxWidth - 10 + 'px 9px';
							}
						}
						
						if (!single) {
							if (lastTop > 0) {
								if (subListParent.offsetTop !== lastTop) {
									trimHeight(j, i);
									j = i;
									lastTop = subListParent.offsetTop;
									if (j === subLists.length - 1) {
										trimHeight(j, subLists.length);
									}
								} else if (subListParent.offsetTop === lastTop && j !== i) {
									trimHeight(j, i + 1);
								}
							} else {
								lastTop = subListParent.offsetTop;
							}
						}
					}
				} else {
					subLists[0].parentNode.style.width = eachWidth[0] + 'px';
					if (subLists[0].className !== 'single-selectors-more' || subLists[0].className !== 'single-selectors-less') {
						trimHeight(0, 1);
					}
				}
			}
		};
	};
	
	// selectors tickout stuff
	tick = function () {
		return function () {
			var subListItems, button;
			if (currentList !== null) {
				subListItems = currentList.getElementsByTagName('li');
				button = subListItems[subListItems.length - 1];
				
				if (tickout <= reqTicks) {
					tickout++;
					if (tickout >= 50) {
						flashButton = !flashButton;
						button.className = 'sps-button sps-button-hover' + (flashButton ? ' sps-button-flash' : '');
					}

				}
				if (tickout === reqTicks) {
					tickout = 0;
					button.className = 'sps-button sps-button-hover';
					flashButton = false;
				}
			} else {
				if (tickout > 0) {
					tickout = 0;
				}
			}
		};
	};
	
	// single liners click event
	singleClick = function () {
		return function (e) {
			var currentList = this.getElementsByTagName('ul');
			if (this.className === 'single-selectors-more') {
				this.className = 'single-selectors-less';
				currentList[0].className = 'sps-ul-expanded';
			} else {
				this.className = 'single-selectors-more';
				currentList[0].className = '';
			}
		};
	};
	
	// multi liners click event
	eventClick = function () {
		return function (e) {
			var subListItems = this.getElementsByTagName('li');
			button = subListItems[subListItems.length - 1];
			if (this.className === '') {
				currentList = this;
				currentList.className = 'sps-ul-expanded';
				button.innerHTML = '<span class=selectors-button-less>Less</span>';
				currentList = null;
				lastList = null;
			} else {
				subListItems[subListItems.length - 1].innerHTML = '<span class=selectors-button-more>' + (subListItems.length - 6) + ' More</span>';
				this.className = '';
			}
		};
	};
	
	// multi liners mouse over and out event
	eventOverOut = function (mouse) {
		return function (e) {
			var subListItems;
			if (mouse === 'over') {
				if (this.className === '') {
					if (lastList !== this) {
						if (lastList !== null) {
							subListItems = lastList.getElementsByTagName('li');
							subListItems[subListItems.length - 1].style.backgroundPosition = '-400px 0';
						}
						tickout = 0;
					}
					currentList = this;
				}
				subListItems = this.getElementsByTagName('li');
				subListItems[subListItems.length - 1].className = 'sps-button sps-button-hover';
			} else {
				lastList = currentList;
				currentList = null;
				subListItems = this.getElementsByTagName('li');
				subListItems[subListItems.length - 1].className = 'sps-button';
			}
		};
	};
	
	linkOverOut = function (isOver, type) {
		return function (e) {
			if (type === 'single') {
				this.parentNode.parentNode.parentNode.onclick = (isOver) ? null : singleClick();
			} else if (this.parentNode.className.match('sps-li')) {
				this.parentNode.parentNode.onclick = (isOver) ? null : eventClick();
			}
		};
	};
	
	// init
	subLists = mainList.getElementsByTagName('ul');
	if (subLists.length > 0) {
		for (i = 0; i < subLists.length; i++) {
			subList = subLists[i];
			subListParent = subList.parentNode;
			
			// checks for image in selectors and adjusts accordingly
			imageInSelectors = getElementsByClassName(subListParent, 'sort-by-key-image', 'a')[0];
			if (imageInSelectors) {
				subList.style.paddingLeft = '95px';
				imageInSelectors.style.display = 'block';
			}
			
			// expand to get correct widths then collapse again
			subList.className = 'sps-ul-expanded';
			parentWidth = subListParent.offsetWidth + ((subListParent.className === 'single-selectors-more') ? 10 : 0);
			subList.className = '';
			
			if (subListParent.className === 'single-selectors-more') {				// for single liners
				totalWidths += parentWidth + 23;
				eachWidth[i] = parentWidth;
				
				for (j = 0; (subListItem = subList.getElementsByTagName('li')[j]); j++) {
					subListItem.className = 'sps-li-collapsible';
					subListItem.getElementsByTagName('a')[0].onmouseover = linkOverOut(true, 'single');
					subListItem.getElementsByTagName('a')[0].onmouseout = linkOverOut(false, 'single');
				}
				
				subListParent.style.backgroundPosition = eachWidth[i] - 10 + 'px 9px';
				subListParent.onclick = singleClick();
			} else {																// for multi liners
				if (document.all) { // IE hates me
					totalWidths += parentWidth + 14;
					eachWidth[i] = parentWidth - 8;
				} else { // all other browsers
					totalWidths += parentWidth + 10;
					eachWidth[i] = parentWidth - 12;
				}
				
				subListItems = subList.getElementsByTagName('li');
				collapse = false;
				numNonCollapse = 0;
				localCollapseAfter = collapseAfter + ((collapseAfter + 1 === subListItems.length) ? 1 : 0); // don't collapse just one item
				
				// set which items should be able to collapse
				for (j = subListItems.length - 1 ; j >= 0; j--) {
					if (subListItems[j].className === 'sps-li-non-collapsible' && numNonCollapse < localCollapseAfter) {
						numNonCollapse++;
					} else {
						if (localCollapseAfter - numNonCollapse <= j) {
							subListItems[j].className = 'sps-li-collapsible';
							collapse = true;
						}
					}
				}
				
				if (collapse) {
					for (j = subListItems.length - 1 ; j >= 0; j--) {
						subListItems[j].getElementsByTagName('a')[0].onmouseover = linkOverOut(true);
						subListItems[j].getElementsByTagName('a')[0].onmouseout = linkOverOut(false);
					}
					button = document.createElement('li');
					button.className = 'sps-button';
					button.innerHTML = '<span class=selectors-button-more>' + (subListItems.length - 5) + ' More</span>';
					subList.appendChild(button);
					
					subList.onmouseover = eventOverOut('over');
					subList.onmouseout = eventOverOut('out');
					subList.onclick = eventClick();
				}
			}
			
			// find who has the largest width as we loop through sublists
			if (parentWidth > maxWidth) {
				maxWidth = parentWidth;
			}
		}
		resize();
		window.setInterval(resize(), 300);
		window.setInterval(tick(), 50);
	}
}

// Grids with flexible number of columns
function FlexColGrid(name, minCellWidth) {
	this.redraw = function (gridContainer, minCellWidth) {
		var lastCols = 0, nodes, numNodes, gridWidth, numCols, boxWidth, extraWidth, lastWindowWidth = 0, pixelBoxWidth, primeIt = 3, i, pageContainer, panelWidth = 380;
		nodes = gridContainer.childNodes;
		numNodes = nodes.length;
		pageContainer = document.getElementById('page-container');
		if (pageContainer.className.match(/no-left-panel/)) {
			panelWidth -= 180;
		}
		if (pageContainer.className.match(/no-right-panel/)) {
			panelWidth -= 180;
		}
		return function () {
			if (lastWindowWidth !== document.body.offsetWidth &&  document.body.offsetWidth > 0) {
				lastWindowWidth = document.body.offsetWidth - primeIt;
				gridWidth = lastWindowWidth - panelWidth;
				numCols = Math.min(Math.floor(gridWidth / minCellWidth), numNodes);
				if (numCols === 0) {
					numCols = 1;
				} else {
					while ((Math.ceil(numNodes / numCols) === Math.ceil(numNodes / (numCols - 1))) && numCols > 1) {
						numCols--;
					}
				}
				gridContainer.style.width = (Math.ceil(gridWidth / numCols) * numCols) + 'px';
				if (lastCols !== numCols) {
					lastCols = numCols;
					boxWidth = Math.floor(100 / numCols);
					extraWidth = 100 - boxWidth * numCols;
					pixelBoxWidth = boxWidth + "%";
					for (i = 0; i < nodes.length; i++) {
						nodes[i].style.width = pixelBoxWidth;
					}
				}
				if (primeIt > 0) {
					primeIt -= 3;
				}
			}
		};
	};
	window.setInterval(this.redraw(document.getElementById(name), minCellWidth), 60);
}

// holds the min width on the body in IE6
function IE6MinWidthFix() {
	this.tick = function () {
		var oldPageWidth = -1;
		return function () {
			if (oldPageWidth !== document.documentElement.clientWidth) {
				document.body.style.width = document.documentElement.clientWidth > 768 ? '' : '768px';
				oldPageWidth = document.documentElement.clientWidth;
			}
		};
	};
	window.setInterval(this.tick(), 80);
}

function SortByBeGone(id) {
	var mainPanel, container, totalWidth, lastWidth, grabWidths, hideShow, button, theList, origItems, dropItems, timer, hideMe, eventOverOut, hideList, createButton, createList, selectedWidth, isIE, spansToHide, leftPos, selectedSpot, leftPanel, rightPanel, ieVersion;
	mainPanel = document.getElementById('main-panel');
	leftPanel = document.getElementById('left-panel');
	rightPanel = document.getElementById('right-panel');
	container = document.getElementById(id);
	totalWidth = 0;
	lastWidth = 0;
	leftPos = [];
	origItems = [];
	dropItems = [];
	timer = null;
	hideMe = false;
	isIE = (document.all && !window.opera) ? true : false;
	ieVersion = getIEVersion();
	
	// Mouse over and out event to show and hide dropdown
	eventOverOut = function () {
		return function (e) {
			var sortList, adjust;
			sortList = container.getElementsByTagName('ul')[0];
			if (theList.className === 'top-nav-hidden' || timer !== null) {
				window.clearTimeout(timer);
				timer = null;
				hideMe = false;
				theList.className = 'sort-by-more-menu';
				theList.style.right = (rightPanel) ? '195px' : '15px';
				adjust = (isIE && ieVersion !== 8) ? 114 : 28;
				if (sortList.offsetTop !== 0) {
					theList.style.top = sortList.offsetTop + adjust + 'px';
				} else {
					theList.style.top = container.offsetTop + adjust + 'px';
				}
			} else {
				timer = window.setTimeout(hideList(), 700);
				hideMe = true;
			}
		};
	};
	
	// Hides the dropdown after timer goes off if mouse is not still over
	hideList = function () {
		return function () {
			theList.className = hideMe ? 'top-nav-hidden' : 'sort-by-more-menu';
			timer = null;
		};
	};
	
	// Grab widths with sort by showing and fire up the interval
	grabWidths = function () {
		var li, i, j, smallerTotal;
		mainPanel.style.width = '100000px';
		smallerTotal = 0;
		for (i = 0; (li = container.getElementsByTagName('li')[i]); i++) {
			totalWidth += li.offsetWidth + 6;
			for (j = 0; j < spansToHide.length; j++) {
				spansToHide[j].style.display = 'none';
			}
			smallerTotal += li.offsetWidth + 6;
			if (!li.className.match('sort-by-selected')) {
				leftPos.push(smallerTotal);
				origItems.push(li);
				dropItems.push(li.cloneNode(true));
			} else {
				selectedWidth = li.offsetWidth + 6;
				selectedSpot = i;
			}
			for (j = 0; j < spansToHide.length; j++) {
				spansToHide[j].style.display = 'inline';
			}
		}
		if (oldIE) {
			for (i = 0; i < dropItems.length; i++) {
				dropItems[i].style.width = origItems[i].offsetWidth + 'px';
			}
		}
		mainPanel.style.width = '';
		createButton();
	};
	
	// Create more button and place in top nav hidden until needed
	createButton = function () {
		var buttonSpan, sortByList;
		buttonSpan = document.createElement('span');
		buttonSpan.innerHTML = 'More';
		buttonSpan.className = 'sort-by-span';
		
		button = document.createElement('li');
		button.className = 'top-nav-hidden';
		button.onmouseover = eventOverOut();
		button.onmouseout = eventOverOut();
		button.appendChild(buttonSpan);
		sortByList = container.getElementsByTagName('ul')[0];
		sortByList.insertBefore(button, sortByList.firstChild);
		createList();
	};
	
	// Creates the list and places in page hidden until needed
	createList = function () {
		var i, footer;
		theList = document.createElement('ul');
		theList.className = 'top-nav-hidden';
		theList.onmouseover = eventOverOut();
		theList.onmouseout = eventOverOut();
		
		for (i = 0; i < dropItems.length; i++) {
			theList.appendChild(dropItems[i]);
		}
		
		footer = document.getElementById('footer');
		if (footer) {
			footer.appendChild(theList);
		}
		hideShow();
		window.setInterval(hideShow(), 250);
	};
	
	// Hide or show sort by
	hideShow = function () {
		return function () {
			var mpWidth, i, hidingAlready, newWidth;
			if (lastWidth !== document.body.offsetWidth) {
				lastWidth = document.body.offsetWidth;
				mpWidth = (leftPanel && rightPanel) ? lastWidth - 420 : lastWidth - 40;
				if (spansToHide.length > 0) {
					for (i = 0; i < spansToHide.length; i++) {
						spansToHide[i].style.display = (totalWidth > mpWidth) ? 'none' : 'inline';
						hidingAlready = (totalWidth > mpWidth) ? true : false;
					}
				}
				newWidth = (selectedSpot === leftPos.length) ? mpWidth - selectedWidth : mpWidth;
				if (leftPos[leftPos.length - 1] > newWidth) {
					button.className = 'sort-by-more';
					mpWidth -= button.offsetWidth + 12;
				} else {
					button.className = 'top-nav-hidden';
				}
				for (i = 0; i < leftPos.length; i++) {
					newWidth = (i < selectedSpot) ? mpWidth - selectedWidth : mpWidth;
					if (leftPos[i] > newWidth) {
						origItems[i].className = 'top-nav-hidden';
						dropItems[i].className = '';
					} else {
						origItems[i].className = '';
						dropItems[i].className = 'top-nav-hidden';
					}
				}
			}
		};
	};
	
	// init
	if (mainPanel && container) {
		spansToHide = getElementsByClassName(container, 'hide-sort-by', 'span');
		grabWidths();
	}
}

function validateMailingListForm() {
	var mailingListContainer, mailingListForm;
	mailingListContainer = document.getElementById('mail-list-box');
	if (mailingListContainer) {
		mailingListForm = mailingListContainer.getElementsByTagName('form')[0];
		mailingListForm.onsubmit = function () {
			if (this.email.value === 'your@email.com') {
				this.email.focus();
				alert('Please enter your email address');
				return false;
			}
		};
	}
}

function copyNavigationElements(fromId, toId) {
	var fromNode, toNode, n;
	fromNode = document.getElementById(fromId);
	toNode = document.getElementById(toId);

	if (fromNode && toNode) {
		while (toNode.hasChildNodes()) {
			toNode.removeChild(toNode.firstChild);
		}
		for (n = 0; n < fromNode.childNodes.length; n++) {
			toNode.appendChild(fromNode.childNodes[n].cloneNode(true));
		}
	}
}

/* -- modify and call from initOpticsPlanetPage to change pricing w/o publishing -- 
function initPriceAdjust(){
	var priceBlock = document.getElementById('priceblock');
	if(priceBlock){
		if(priceBlock.getElementsByTagName('td')[2].innerHTML === 'CA-CD-2554B001'){
			var salePriceDisplay = document.getElementById('salePriceDisplay');
			if(salePriceDisplay.innerHTML = '$119.99'){
				var priceAdjustInput = document.createElement('input');
				priceAdjustInput.name = 'Retail Price';
				priceAdjustInput.value = '(+$110)';
				priceAdjustInput.type = 'hidden';
				priceBlock.parentNode.insertBefore(priceAdjustInput,priceBlock);
				salePriceDisplay.innerHTML = '$229.99';
				document.getElementById('youSaveDisplay').innerHTML = '$170.00 (43%)';
				var optionsDiv = document.getElementById('options');
				optionsDiv.parentNode.removeChild(optionsDiv);
				var inputs = document.getElementsByTagName('input');
				for (i = 0; i < inputs.length; i++){
					if(inputs[i].name === 'vwitem0'){
						inputs[i].name = 'vwitem';
					}
				}
			}
		}
	}
	var contents = getElementsByClassName(document, 'item-grid-cell','div');
	for(var i =  0; i < contents.length; i++){
		if(contents[i].getElementsByTagName('img')[0].alt.indexOf('Canon PowerShot SD790IS') === 0){
			var salePrice = getElementsByClassName(contents[i],'item-grid-sale-price-value','span')[0];
			if(salePrice.innerHTML === '$119.99'){
				salePrice.innerHTML	 = '$229.99';
			}
		}
	}
}

function initDisableAddToCart(){
	if (document.URL.match(/\/(zeiss-conquest-4-14x50bl-hunt-riflescopes|zeiss-conquest-4-14x50bl-riflescopes)\.html/)) { 
		document.getElementById('options').style.display = 'none';
		document.getElementById('headblock-right').style.display = 'none';
		document.getElementById('add-to-cart-button-container-with-options').style.display = 'none';
	}
}
--------------------------------------------------------------------------- */

function Velaro() {
	var vnt = 'yes', vrt = 'no', vt = 1, checkCookie, newCookie, grabRef, prodPage, addScript, rm, pm, custom;
	
	// checks for velaro cookies and sets varibles based on results
	checkCookie = function () {
		var cs, c_end;
		if (document.cookie.length > 0) { // check if cookies exist
			vnt = (document.cookie.indexOf('velaront5188=') !== -1) ? 'no' : 'yes'; // check if velaro 24 hour cookie exists 
			cs = document.cookie.indexOf('velaroret5188='); // sets cs to velaro 1 year cookie
			if (cs !== -1) { // checks if 1 year cookie exists
				vrt = 'yes'; 
				cs = cs + 11;
				c_end = document.cookie.indexOf(';', cs);
				c_end = (c_end === -1) ? document.cookie.length : c_end;
				vt = parseInt(unescape(document.cookie.substring(cs, c_end)));
				vt += (vnt === 'yes') ? 1 : 0;
			}
		}
		newCookie();
	};
	
	// this block sets new 24 hour and 1 year cookies
	newCookie = function () {
		var ed = new Date();
		ed.setHours(23);
		ed.setMinutes(59);
		ed.setSeconds(59); 
		document.cookie = 'velaront5188=yes;expires=' + ed.toGMTString();
		ed.setFullYear(ed.getFullYear() + 1);
		document.cookie = 'velaroret5188=' + vt + ';expires=' + ed.toGMTString();
		grabRef();
	};
	
	// grabs refering page and current page
	grabRef = function () {
		rm = escape(window.document.referrer.replace("&", "*"));
		pm = window.document.URL.replace("&", "*");
		prodPage();
	};
	
	// sets var with sku, price and cat if product page
	prodPage = function () {
		var sku, price, cat, priceBlock, priceDisplay, skuDisplay;
		priceBlock = document.getElementById('priceblock');
		if (priceBlock) {
			priceDisplay = document.getElementById('salePriceDisplay');
			skuDisplay = priceBlock.getElementsByTagName('td')[2];
			
			sku = (skuDisplay) ? skuDisplay.innerHTML : '';
			price = (priceDisplay) ? priceDisplay.innerHTML : '';
			if (price !== '') {
				price = price.replace('$', '');
				price = Number(price);
				price = price.toFixed(2);
				price = price.toString();
				while (price.length < 8) {
					price = '0' + price;
				}
			}
			cat = (sku !== '') ? sku.slice(3, 5) : '';
			
			custom = '&sku=' + sku + '&price=' + price + '&cat=' + cat;
		} else {
			custom = '';
		}
		addScript();
	};
	
	// puts it all together and creates the script element
	addScript = function () {
		var sm = 'http://visitors.velaro.com/visitor/monitor.aspx?siteid=5188&deptid=6930&autorefresh=yes&newtoday=' + vnt + custom + '&returning=' + vrt + '&origin=' + rm + '&pa=' + pm;
		addScriptToHead(sm, '', 'js');
	};
	
	// init
	checkCookie();
}

// Adds the msn ppc img to the footer for msn ppc tracking
function msnPpc() {
	var msnImage, footer, url;
	footer = document.getElementById('footer');
	msnImage = document.createElement('img');
	url = location.protocol.toLowerCase() + '//98783.r.msn.com/?type=1&cp=5050&sku=0&dedup=1';
	msnImage.setAttribute('src', url);
	msnImage.setAttribute('width', '1');
	msnImage.setAttribute('height', '1');
	if (footer) {
		footer.appendChild(msnImage);
	}
}

// Adds scripts needed to the head to load up google analytics
function googleAnalytics() {
	var searchBox, geoTracker, searchPage = null, gaCookie = '', headerTag, headerText, searchQuery, cookies, i;
	if (typeof(_gat) !== 'undefined') {
		geoTracker = _gat._getTracker('UA-138028-1');
		geoTracker._setDomainName('none');
		geoTracker._setAllowLinker(true);
		if (document.URL.match('opticsplanet.com/s/')) {
			searchBox = document.getElementById('smarty-search-page-text');
			if (searchBox.value !== 'Search' && searchBox.value !== '') {
				searchPage = '/s/?query=' + encodeURIComponent(searchBox.value).replace(/\%20/g, '+');
			}
		} else if (document.URL.match('opticsplanet.com/msgboard/search.php')) {
			headerTag = document.getElementsByTagName('h1')[0];
			if (headerTag) {
				headerText = headerTag.innerHTML;
				searchQuery = headerText.match(/\+.+/);
				if (searchQuery) {
					searchQuery = searchQuery[0].replace(/\+/g, '').replace(/\s{2,}/g, ' ');
					searchPage = '/msgboard/search.php?keywords=' + encodeURIComponent(searchQuery).replace(/\%20/g, '+');
				}
			}
		}
		if (searchPage !== null) {
			geoTracker._trackPageview(searchPage);
		} else {
			geoTracker._trackPageview();
		}
		cookies = document.cookie.split('; ');
		for (i = 0; i < cookies.length; i++) {
			if (cookies[i].match('__utm')) {
				gaCookie += cookies[i] + '&';
			}
		}
		cookiesForBridge.push(gaCookie);
	} else {
		window.setTimeout("googleAnalytics();", 200);
	}
}

function yahooAnalytics() {
	var searchQuery, results, pageName, path, pathPieces, headerTag, ywaTracker, headerText;
	if (typeof(YWA) !== 'undefined') {
		ywaTracker = YWA.getTracker("1000511331137"); // Yahoo Analytics account number
		if (document.URL.match('opticsplanet.com/s/')) {
			searchQuery = document.getElementById('smarty-search-page-text').value;
			results = document.getElementById('numResults');
			if (results) {
				results = results.innerHTML.replace(/[^0-9]/g, '');
			}
		} else if (document.URL.match('opticsplanet.com/msgboard/search.php')) {
			headerTag = document.getElementsByTagName('h1')[0];
			if (headerTag) {
				headerText = headerTag.innerHTML;
				results = headerText.match(/\s[0-9]+\s/);
				searchQuery = headerText.match(/\+.+/);
				if (results && searchQuery) {
					results = results[0].replace(/\s/g, '');
					searchQuery = searchQuery[0].replace(/\+/g, '').replace(/\s{2,}/g, ' ');
				}
			}
		}
		if (results && searchQuery) {
			ywaTracker.setAction('INTERNAL_SEARCH');
			ywaTracker.setISK(searchQuery);
			ywaTracker.setISR(results);
			ywaTracker.setDocumentGroup('Search');
			ywaTracker.setDocumentName('Search Results');
		} else {
			path = document.location.pathname;
			pathPieces = path.split('/');
			if (pathPieces.length > 1) {
				pageName = pathPieces[pathPieces.length - 1].split('.')[0];
				if (pageName === '') {
					pageName = pathPieces[pathPieces.length - 2];
				}
			} else {
				pageName = path.split('.')[0];
			}
			pageName = pageName.replace(/[^a-z,0-9]/gi, ' ');
			pageName = (pageName === '') ? 'index' : pageName;
			ywaTracker.setDocumentName(pageName);
			ywaTracker.setDocumentGroup('Dot Com');
		}
		ywaTracker.submit();
	} else {
		window.setTimeout('yahooAnalytics();', 333);
	}
}

function ImageSwapper() {
	var mainImg, links, i, bigUrl, eventOver, eventOut, eventClick, origMainImg, origMainAlt, currentImg, currentAlt, popDiv, popImg, hideImage, linksImg, faderDiv, centerPopDiv, myInterval = null, winH = 0, winW = 0, newImg, setOpacity, fadeIn, fadeOut, fadeOutOpac = [], nextDiv = null, prevDiv = null, nextPrev, popAlt, newText, closeImg, keyDownEvent, popIcons = [], getScroll, topPos, scrollFix, iconContainer, preLoader = [], loadingImg, preLoaded = [], popLoadingImg, setNewSizes, setSelected, setNewImage, switchBox, picButton, vidButton, moviePlayer, toggleSwitch, movieObject, playlist = [], addPlaylist, flashLink, lastItem = 0, movieNum = 0, movieFile, playlistSpot, flashVars, flashParams, flashAttributes, embedFlash, video, findMovie,
	picBlock = document.getElementById('pictureblock'),
	mainLink = document.getElementById('main-picture'),
	midUrl = 'http://images1.opticsplanet.com/180-180-ffffff/',
	objects = document.getElementsByTagName('object'),
	videoList = document.getElementById('caption-documents-flv'),
	specialPicBlock = document.getElementById('images-holder'),
	fadeInTimer = [null, null],
	fadeInOpac = [0, 0],
	fadeOutTimer = [null, null];
	
	// Gets any offset if the user has scrolled down the page
	getScroll = function () {
		var scrollY = 0;
		if (typeof(window.pageYOffset) === 'number') {
			scrollY = window.pageYOffset;
		} else if (document.body && document.body.scrollTop) {
			scrollY = document.body.scrollTop;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scrollY = document.documentElement.scrollTop;
		}
		return scrollY;
	};
	
	// All the calculating and size setting for centering on resize
	setNewSizes = function (imgW, imgH, popH, loadTop, loadLeft, colDivider) {
		var colAmt, newWidth, leftPos, top, left, height, width;
		popDiv.style.height = popH + 'px';
		if (mainLink || specialPicBlock) {
			if (mainLink) {
				bigUrl = 'http://images1.opticsplanet.com/' + imgW + '-' + imgH + '-ffffff/';
				if (!popImg.src.match(imgW + '-' + imgH)) {
					currentImg = bigUrl + popImg.src.split('-ffffff/')[1];
					popImg.src = bigUrl + popImg.src.split('-ffffff/')[1];
				}
			} else {
				height = (imgH < 402) ? imgH : 402;
				width = (imgW < 600) ? imgW : 600;
				top = (imgH - height) / 2;
				left = (imgW - width) / 2;
				popImg.style.width = width + 'px';
				popImg.style.height = height + 'px';
				popImg.style.top = (27 + top) + 'px';
				popImg.style.left = left + 'px';
			}
			iconContainer.style.height = imgH + 'px';
			iconContainer.style.left = imgW + 'px';
			popLoadingImg.style.top = loadTop + 'px';
			popLoadingImg.style.left = loadLeft + 'px';
			colAmt = (Math.ceil(popIcons.length / colDivider)) * 70;
			iconContainer.style.width = colAmt + 'px';
			newWidth = (popIcons.length > 1) ? imgW + colAmt : imgW;
		} else {
			newWidth = imgW;
		}
		popDiv.style.width = newWidth + 2 + 'px';
		topPos = (winH - popH) / 2 - 10;
		scrollFix = getScroll();
		popDiv.style.top = ((topPos + scrollFix) > 0) ? topPos + scrollFix + 'px' : '0px';
		leftPos = (winW - newWidth) / 2 - 10;
		popDiv.style.left = (leftPos > 0) ? leftPos + 'px' : '0px';
		if (playlist.length > 0) {
			if (!movieObject) {
				if (flashLink) {
					flashLink.style.width = newWidth + 'px';
					flashLink.style.height = popH - 27 + 'px';
				}
				movieObject = document.getElementById('flvMoviePlayer');
			}
			if (movieObject) {
				movieObject.style.width = newWidth + 4 + 'px';
				movieObject.style.height = popH - 26 + 'px';
			}
		}
	};
	
	addPlaylist = function () {
		return function () {
			if (movieObject && typeof(movieObject.sendEvent) === 'function') {
				movieObject.sendEvent('LOAD', playlist);
				movieObject.sendEvent('ITEM', movieNum);
				if (mainLink && vidButton.className !== 'selected') {
					movieObject.sendEvent('STOP', movieNum);
				}
			} else {
				window.setTimeout(addPlaylist(), 100);
			}
		};
	};
	
	// Determines the window size and calls the function above to resize
	centerPopDiv = function () {
		return function () {
			if (((document.all && !window.opera) ? document.documentElement.clientHeight : window.innerHeight) !== winH || ((document.all && !window.opera) ? document.body.offsetWidth : window.innerWidth) !== winW) {
				winH = (document.all && !window.opera) ? document.documentElement.clientHeight : window.innerHeight;
				winW = (document.all && !window.opera) ? document.body.offsetWidth : window.innerWidth;
				if (winW > 1170 && winH > 710) {
					setNewSizes(1020, 680, 707, 250, 420, 9);
				} else if (winW > 900 && winH > 530) {
					setNewSizes(750, 500, 527, 160, 285, 7);
				} else {
					setNewSizes(480, 320, 347, 70, 150, 4);
				}
			}
			if (playlist.length > 1) {
				if (movieObject && typeof(movieObject.getConfig) === 'function') {
					if (lastItem !== movieObject.getConfig()['item']) {
						lastItem = movieObject.getConfig()['item'];
						movieNum = lastItem;
						popAlt.innerHTML = playlist[lastItem].title;
					}
				}
			}
		};
	};
	
	setOpacity = function (el, opacity) {
		opacity = '' + (opacity / 5);
		el.style.opacity = opacity;		// For CSS 3 compliant browsers
		el.style["-moz-opacity"] = opacity;	// For old FF
		el.style.filter = 'alpha(opacity=' + opacity * 100 + ')';	// For IE
	};
	
	fadeIn = function (obj, fadeStop, a) {
		return function () {
			if (fadeInTimer[a] !== null && fadeInOpac[a] < fadeStop) {
				setOpacity(obj, fadeInOpac[a]);
				obj.className = '';
				fadeInOpac[a]++;
			} else {
				setOpacity(obj, fadeStop);
				window.clearInterval(fadeInTimer[a]);
				fadeInTimer[a] = null;
				fadeOutOpac[a] = fadeStop;
				if (a === 1 && playlist.length > 1) {
					window.setTimeout(addPlaylist(), 100);
				}
			}
		};
	};
	
	fadeOut = function (obj, fadeStop, a) {
		return function () {
			if (fadeOutTimer[a] !== null && fadeOutOpac[a] > fadeStop) {
				setOpacity(obj, fadeOutOpac[a]);
				fadeOutOpac[a]--;
			} else {
				setOpacity(obj, fadeStop);
				obj.className = 'hidden-object';
				window.clearInterval(fadeOutTimer[a]);
				fadeOutTimer[a] = null;
				fadeInOpac[a] = fadeStop;
				for (i = 0; i < objects.length; i++) {
					if (objects[i].id !== 'flvMoviePlayer') {
						objects[i].style.visibility = '';
					}
				}
				if (moviePlayer) {
					moviePlayer.style.visibility = 'hidden';
				}
			}
		};
	};
	
	// Handles all image changes for mouseovers and clicks, includes preload
	setNewImage = function (img, popArea, changeCurrent) {
		var imgSrc, skip = false, url, setImg, setAlt, tempImg;
		if (mainLink) {
			imgSrc = img.src.split('/');
			imgSrc = imgSrc[imgSrc.length - 1].split('.', 1);
			setImg = bigUrl + imgSrc + '.jpg';
		} else {
			setImg = img.src.replace('-m.jpg', '.jpg');
		}
		setAlt = img.alt;
		if (popArea || changeCurrent) {
			tempImg = popImg;
			popAlt.innerHTML = setAlt;
		} else {
			tempImg = mainImg;
			mainImg.alt = setAlt;
		}
		for (url in preLoaded) {
			if (setImg === preLoaded[url]) {
				skip = true;
				break;
			}
		}
		setImg = (popArea || changeCurrent) ? setImg : midUrl + imgSrc + '.jpg';
		if (!skip) {
			tempImg.className = 'top-nav-hidden';
			preLoader[setImg] = new Image();
			preLoader[setImg].onload = function () {
				tempImg.src = this.src;
				tempImg.className = '';
				preLoaded.push(this.src);
				winH = winW = 0;
			};
			preLoader[setImg].src = setImg;
		} else {
			tempImg.src = setImg;
		}
		if (changeCurrent) {
			currentImg = setImg;
			currentAlt = setAlt;
		}
	};
	
	// Sets class names to properly show currently selected image and adjust next/prev buttons
	setSelected = function () {
		var popName, currentName;
		for (i = 0; i < popIcons.length; i++) {
			popName = (mainLink) ? popIcons[i].src.split('-ffffff')[1] : popIcons[i].src.replace('-m.jpg', '.jpg'),
			currentName = (mainLink) ? currentImg.split('-ffffff')[1].replace('.jpg', '.gif') : currentImg;
			if (popName === currentName) {
				popIcons[i].className = 'selected-image';
				prevDiv.className = (i > 0) ? '' : 'disable-me';
				prevDiv.onclick = (i > 0) ? nextPrev('back') : null;
				nextDiv.className = (i < (popIcons.length - 1)) ? '' : 'disable-me';
				nextDiv.onclick = (i < (popIcons.length - 1)) ? nextPrev('forward') : null;
			} else {
				popIcons[i].className = '';
			}
		}
	};
	
	// Hides pop up window and fader div and stops interval that centers pop up window on resize
	hideImage = function () {
		return function (e) {
			if (myInterval !== null) {
				window.clearInterval(myInterval);
				myInterval = null;
			}
			if (fadeInTimer[1] === null && fadeInTimer[0] === null && fadeOutTimer[0] === null && fadeOutTimer[1] === null) {
				if (movieObject && typeof(movieObject.sendEvent) === 'function') {
					movieObject.sendEvent('STOP');
				}
				if (document.all && !window.opera) {
					popDiv.className = 'hidden-object';
					faderDiv.className = 'hidden-object';
					if (flashLink) {
						flashLink.style.display = 'none';
					}
				} else {
					fadeOutTimer[1] = window.setInterval(fadeOut(popDiv, 0, 1), 50);
					fadeOutTimer[0] = window.setInterval(fadeOut(faderDiv, 0, 0), 50);
				}
				document.onkeydown = null;
			}
		};
	};
	
	// Mouse over event handler
	eventOver = function () {
		return function (e) {
			var inPopUp;
			if (this.parentNode.id === 'pop-icon-container') {
				newImg = this;
				inPopUp = true;
			} else {
				newImg = this.getElementsByTagName('img')[0];
				inPopUp = false;
			}
			setNewImage(newImg, inPopUp, false);
		};
	};
	
	// Mouse out event handler
	eventOut = function () {
		return function (e) {
			//preLoader.onload = null;
			if (this.parentNode.id === 'pop-icon-container') {
				popImg.src = currentImg;
				popImg.className = '';
				popAlt.innerHTML = currentAlt;
			} else {
				mainImg.src = origMainImg;
				mainImg.alt = origMainAlt;
				mainImg.className = '';
			}
		};
	};
	
	// Switches back and forth from movies to pictures in the pop up
	toggleSwitch = function (showVid) {
		return function () {
			if (showVid) {
				if (mainLink) {
					vidButton.className = 'selected';
					vidButton.onclick = null;
					picButton.className = '';
					picButton.onclick = toggleSwitch(false);
				}
				moviePlayer.style.visibility = '';
				popAlt.innerHTML = playlist[movieNum].title;
				if (flashLink) {
					flashLink.style.display = 'block';
				}
				if (nextDiv !== null && prevDiv !== null) {
					nextDiv.className = 'disable-me';
					nextDiv.style.display = 'none';
					nextDiv.onclick = null;
					prevDiv.className = 'disable-me';
					prevDiv.style.display = 'none';
					prevDiv.onclick = null;
				}
				if (playlist.length > 1) {
					window.setTimeout(addPlaylist(), 100);
				} else if (movieObject && typeof(movieObject.sendEvent) === 'function') {
					movieObject.sendEvent('ITEM', '0');
				}
			} else {
				if (movieObject && typeof(movieObject.sendEvent) === 'function') {
					movieObject.sendEvent('STOP');
				}
				vidButton.className = '';
				vidButton.onclick = toggleSwitch(true);
				picButton.className = 'selected';
				picButton.onclick = null;
				if (flashLink) {
					flashLink.style.display = 'none';
				}
				moviePlayer.style.visibility = 'hidden';
				popAlt.innerHTML = currentAlt;
				if (nextDiv !== null && prevDiv !== null) {
					nextDiv.style.display = 'block';
					prevDiv.style.display = 'block';
					setSelected();
				}
			}
		};
	};
	
	// Mouse click event handler
	eventClick = function (movNum) {
		return function (e) {
			if (movNum < 0) {
				var inPopUp;
				if (this.parentNode.id === 'pop-icon-container') {
					newImg = this;
					inPopUp = true;
				} else if (this.id === 'enlarge-text') {
					newImg = mainImg;
					inPopUp = false;
				} else {
					newImg = this.getElementsByTagName('img')[0];
					inPopUp = false;
				}
				setNewImage(newImg, inPopUp, true);
				setSelected();
			}
			if (this.parentNode.id !== 'pop-icon-container') {
				myInterval = window.setInterval(centerPopDiv(), 250); // Starts up centering function so pop up stays centered on window resize
				if (fadeInTimer[1] === null && fadeInTimer[0] === null && fadeOutTimer[0] === null && fadeOutTimer[1] === null) {
					for (i = 0; i < objects.length; i++) {
						if (objects[i].id !== 'flvMoviePlayer') {
							objects[i].style.visibility = 'hidden';
						}
					}
					if (document.all && !window.opera) {
						faderDiv.className = '';
						popDiv.className = '';
					} else {
						fadeInTimer[0] = window.setInterval(fadeIn(faderDiv, 4, 0), 50);
						fadeInTimer[1] = window.setInterval(fadeIn(popDiv, 5, 1), 50);
					}
					document.onkeydown = keyDownEvent();
					scrollFix = getScroll();
					popDiv.style.top = topPos + scrollFix + 'px';
				}
				if (playlist.length > 0) {
					movieNum = (movNum > -1) ? movNum : 0;
					window.setTimeout(toggleSwitch(movNum > -1), 1);
				}
			}
			return false;
		};
	};
	
	// Event handler for next and prev buttons in pop up
	nextPrev = function (direction) {
		return function (e) {
			for (i = 0; i < popIcons.length; i++) {
				if (popIcons[i].className === 'selected-image') {
					if (direction === 'back' && i > 0) {
						newImg = popIcons[i - 1];
						break;
					} else if (direction === 'forward' && i < (popIcons.length - 1)) {
						newImg = popIcons[i + 1];
						break;
					}
				}
			}
			setNewImage(newImg, true, true);
			setSelected();
			return false;
		};
	};
	
	keyDownEvent = function () {
		return function (e) {
			var keynum = (window.event) ? window.event.keyCode : e.which;
			switch (keynum) {
			case 37: // left arrow key press
				if (prevDiv !== null && prevDiv.className !== 'disable-me') {
					window.setTimeout(nextPrev('back'), 1);
				}
				break;
			case 39: // right arrow key press
				if (nextDiv !== null && nextDiv.className !== 'disable-me') {
					window.setTimeout(nextPrev('forward'), 1);
				}
				break;
			case 27: // escape key press
				if (popDiv.className !== 'hidden-object') {
					window.setTimeout(hideImage(), 1);
				}
				break;
			}
		};
	};
	
	findMovie = function () {
		return function () {
			if (!movieObject) {
				movieObject = document.getElementById('flvMoviePlayer');
				winH = 0;
			} else {
				window.setTimeout(findMovie(), 50);
			}
		};
	};
	
	embedFlash = function () {
		return function () {
			if (typeof(swfobject) === 'object') {
				swfobject.embedSWF('http://layout.opticsplanet.com/player-licensed.swf', 'flv-movie', '1020', '680', '9', false, flashVars, flashParams, flashAttributes);
				findMovie()();
			} else {
				window.setTimeout(embedFlash(), 50);
			}
		};
	};
	
	// init
	if (picBlock && mainLink || videoList || specialPicBlock) {
		if (mainLink) {
			newText = createEl('p', {'id': 'enlarge-text'}, picBlock); // This block adds the Click to enlarge text and icon
			newText.onclick = eventClick(-1);
			newText.innerHTML = 'Click any image to enlarge';
			
			mainImg = mainLink.getElementsByTagName('img')[0]; // This block sets orig and current vars for the main image on the page and in the pop up
			origMainImg = mainImg.src;
			origMainAlt = mainImg.alt;
			currentImg = mainImg.src.replace('180-180-ffffff', '1020-680-ffffff').replace('.png', '.jpg');
			currentAlt = mainImg.alt;
			
			loadingImg = createEl('img', {'id': 'loading-image', 'src': 'http://layout.opticsplanet.com/images/loading.gif'});
			picBlock.insertBefore(loadingImg, mainLink);
		} else if (specialPicBlock) {
			mainImg = specialPicBlock.getElementsByTagName('img')[0];
			currentImg = mainImg.src.replace('-m.jpg', '.jpg');
			currentAlt = mainImg.alt;
		} else {
			currentAlt = '';
		}
		
		popDiv = createEl('div', {'id': 'pop-up-window', 'class': 'hidden-object'}); // Creates and sets attributes for elements for pop up area
		closeImg = createEl('div', {'id': 'pop-close-button'}, popDiv);
		closeImg.onclick = hideImage();
		popAlt = createEl('p', {'id': 'pop-img-alt', 'innerHTML': currentAlt}, popDiv);
		if (mainLink || specialPicBlock) {
			popLoadingImg = createEl('img', {'id': 'pop-loading-img', 'src': 'http://layout.opticsplanet.com/images/loading.gif'}, popDiv);
			popImg = createEl('img', {'src': currentImg, 'id': 'pop-main-img'}, popDiv);
			popImg.onclick = hideImage();
			iconContainer = createEl('div', {'id': 'pop-icon-container'}, popDiv);
			links = (mainLink) ? picBlock.getElementsByTagName('a') : specialPicBlock.getElementsByTagName('a');
			for (i = 0; i < links.length; i++) { // Loops through the small images and creates new ones from it for the pop up and adds events
				if (links[i].id !== 'main-picture') {
					linksImg = links[i].getElementsByTagName('img')[0];
					if (linksImg.src.match(/\?video\=/)) {
						video = linksImg.src.split(/\?video\=/)[1];
						playlist.push({description: "", file: "http://images1.opticsplanet.com/flv/" + video + ".flv", title: linksImg.alt, type: "video"});
						links[i].onclick = eventClick(playlist.length - 1);
					} else {
						if (mainLink) {
							links[i].onmouseover = eventOver();
							links[i].onmouseout = eventOut();
						}
						newImg = createEl('img', {'src': linksImg.src.replace('88-40-ffffff', '66-66-ffffff'), 'alt': linksImg.alt}, iconContainer);
						newImg.onmouseover = eventOver();
						newImg.onmouseout = eventOut();
						newImg.onclick = eventClick(-1);
						popIcons.push(newImg);
						links[i].onclick = eventClick(-1);
					}
				} else {
					links[i].onclick = eventClick(-1);
				}
				links[i].href = '#';
			}
			if (popIcons.length > 1) {
				nextDiv = createEl('div', {'id': 'next-img-div'}, popDiv);
				nextDiv.onclick = nextPrev('forward');
				prevDiv = createEl('div', {'id': 'prev-img-div'}, popDiv);
				prevDiv.onclick = nextPrev('back');
			}
		} else {
			for (i = 0; (links = videoList.getElementsByTagName('a')[i]); i++) {
				video = links.href.split(/video\=/)[1];
				playlist.push({description: "", file: "http://images1.opticsplanet.com/flv/" + video + ".flv", title: links.innerHTML, type: "video"});
				links.onclick = eventClick(playlist.length - 1);
			}
		}
		if (playlist.length > 0) {
			addScriptToHead('http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', '', 'js');
			if (mainLink) {
				switchBox = createEl('div', {'id': 'pic-video-switch-box'}, popDiv);
				picButton = createEl('div', {}, switchBox);
				picButton.innerHTML = 'pictures';
				vidButton = createEl('div', {}, switchBox);
				vidButton.innerHTML = 'video';
			}
			moviePlayer = createEl('div', {'id': 'flv-movie-div', 'style': 'visibility:hidden;'}, popDiv);
			flashLink = createEl('a', {'id': 'flv-movie', 'class': 'player', 'href': 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash'}, moviePlayer);
			flashLink.innerHTML = 'Get the Flash Plugin to see this video.';
			flashLink.style.display = 'none';
			movieFile = (playlist.length > 1) ? 'playlist.xml' : playlist[0].file;
			playlistSpot = (playlist.length > 1) ? 'right' : 'none';
			flashVars = {'file': movieFile, 'playlist': playlistSpot, 'id': 'flvMoviePlayer', 'stretching': 'uniform', 'backcolor': 'f9f9f9', 'frontcolor': '000000', 'lightcolor': '2665ad', 'screencolor': 'ffffff', 'plugins': 'gapro-1', 'gapro.accountid': 'UA-138028-1', 'gapro.trackstarts': 'true', 'gapro.trackpercentage': 'true', 'gapro.tracktime': 'true'};
			flashParams = {'allowscriptaccess': 'always', 'allowfullscreen': 'true'};
			flashAttributes = {'id': 'flvMoviePlayer', 'name': 'flvMoviePlayer'};
			window.setTimeout(embedFlash(), 50);
		}
		faderDiv = createEl('div', {'id': 'big-faded-box', 'class': 'hidden-object'}); // Creates div used to fade out rest of page
		if (document.getElementById('footer')) {
			document.getElementById('footer').appendChild(popDiv);
			document.getElementById('footer').appendChild(faderDiv);
		} else {
			document.getElementById('object-list').appendChild(popDiv);
			document.getElementById('object-list').appendChild(faderDiv);
		}
		window.setTimeout(centerPopDiv(true), 200);
	}
}

function processNewSuggestions(searchTerm, searchResults) {
	jsonVoorhees[searchTerm] = [];
	jsonVoorhees[searchTerm] = searchResults;
	searchBoxHelp.processNew(searchTerm);
}

function SearchBox(theContainer, theButton, theText, help, addPageName) {
	var word, sliceOne, sliceTwo, listItem, length, i, container, button, text, theList, focused, mouseOver, prevValue, currentLI, eventFocusBlur, eventOverOut, eventKeyUp, setEvents, update, eventClick, matchKeywords, path, pathPieces, pageName;
	container = document.getElementById(theContainer);
	button = document.getElementById(theButton);
	text = document.getElementById(theText);
	theList = document.createElement('ul');
	focused = false;
	mouseOver = false;
	prevValue = null;
	currentLI = -1;
	
	this.processNew = function (term) {
		matchKeywords(term);
	};
	
	// Focus-blur event for textbox
	eventFocusBlur = function () {
		return function (e) {
			focused = !focused;
			container.className = (focused || mouseOver) ? 'hover' : '';
			if (focused) {
				if (trim(this.value) === 'Search') {
					this.value = '';
				} else if (help) {
					matchKeywords(trim(this.value.toLowerCase().replace(/[^a-z0-9\s\-]+/g, ' ')));
				}
				this.className = '';
			} else {
				this.value = trim(this.value);
				if (this.value === '' || this.value === 'Search') {
					this.className = 'empty';
					this.value = 'Search';
				} else if (help) {
					if (!mouseOver) {
						theList.className = 'top-nav-hidden';
						if (prevValue !== null) {
							this.value = prevValue;
						}
					}
				}
			}
		};
	};
	
	// Mouse over event for container, button and helper list
	eventOverOut = function (source) {
		return function (e) {
			var listItems;
			if (source.match('container')) {
				mouseOver = (source.match('over')) ? true : false;
				container.className = (focused || mouseOver) ? 'hover' : '';
			} else if (source === 'button') {
				mouseOver = (source.match('over')) ? true : false;
				button.className = (button.className === 'hover') ? '' : 'hover';
			} else if (source === 'over') {
				if (currentLI !== -1) {
					listItems = theList.getElementsByTagName('li');
					listItems[currentLI].className = '';
					currentLI = -1;
					if (prevValue !== null) {
						text.value = prevValue;
					}
				}
				this.className = 'search-helper-hover';
			} else if (help) {
				this.className = '';
			}
		};
	};
	
	// This runs when they press a key in the searchbox
	eventKeyUp = function () {
		return function (e) {
			var queryWord, listItems, keyPressed;
			keyPressed = (document.all) ? event.keyCode : e.which;
			listItems = theList.getElementsByTagName('li');
			if (keyPressed === 38 && listItems.length > 0) {
				if (currentLI === -1) {
					theList.className = 'top-nav-hidden';
				} else if (currentLI === 0) {
					text.value = prevValue;
					listItems[currentLI].className = '';
					currentLI -= 1;
				} else if (currentLI < listItems.length) {
					listItems[currentLI].className = '';
					currentLI -= 1;
					text.value = stripTags(listItems[currentLI].innerHTML);
					listItems[currentLI].className = 'search-helper-hover';
				}
			} else if (keyPressed === 40 && listItems.length > 0) {
				if (currentLI === -1) {
					theList.className = '';
					currentLI += 1;
					text.value = stripTags(listItems[currentLI].innerHTML);
					listItems[currentLI].className = 'search-helper-hover';
				} else if (currentLI !== listItems.length - 1) {
					listItems[currentLI].className = '';
					currentLI += 1;
					text.value = stripTags(listItems[currentLI].innerHTML);
					listItems[currentLI].className = 'search-helper-hover';
				}
			} else if (this.value !== prevValue && trim(this.value) !== '') {
				prevValue = this.value;
				currentLI = -1;
				queryWord = prevValue.toLowerCase().replace(/[^a-z0-9\s\-]+/g, ' ').replace(/\s+/g, '+');
				update(queryWord);
			} else if (listItems.length > 0 || trim(this.value) === '') {
				theList.innerHTML = '';
				theList.className = 'top-nav-hidden';
				prevValue = '';
			}
		};
	};
	
	// Sets all searchbox mouseover and focus events
	setEvents = function () {
		container.onmouseover = eventOverOut('container-over');
		container.onmouseout = eventOverOut('container');
		
		button.onmouseover = eventOverOut('button-over');
		button.onmouseout = eventOverOut('button');
		
		text.onfocus = eventFocusBlur();
		text.onblur = eventFocusBlur();
		
		if (text.value === '') {
			text.className = 'empty';
			text.value = 'Search';
		}
		
		if (help) {
			text.onkeyup = eventKeyUp();
		}
	};
	
	// If they haven't already searched this term then load the new hit list for this search term
	update = function (searchWord) {
		if (!jsonVoorhees[searchWord]) {
			var opGetter = 'http://tracker.opticsplanet.com/suggestion/' + searchWord + '.js';
			addScriptToHead(opGetter, '', 'js');
		} else {
			matchKeywords(searchWord);
		}
	};
	
	// submits search form when a list item is clicked
	eventClick = function () {
		return function (e) {
			text.value = stripTags(this.innerHTML);
			theList.className = 'top-nav-hidden';
			button.click();
		};
	};
	
	// play matchmaker
	matchKeywords = function (searchWord) {
		if (jsonVoorhees[searchWord] && jsonVoorhees[searchWord] !== '' && jsonVoorhees[searchWord].length > 0) {
			theList.innerHTML = '';
			length = (jsonVoorhees[searchWord].length > 10) ? 10 : jsonVoorhees[searchWord].length;
			for (i = 0; i < length; i++) {
				word = jsonVoorhees[searchWord][i].text;
				sliceOne = word.slice(0, searchWord.length);
				sliceTwo = word.slice(searchWord.length);
				word = sliceOne.bold() + sliceTwo;
				
				listItem = document.createElement('li');
				listItem.innerHTML = word;
				listItem.onmouseover = eventOverOut('over');
				listItem.onmouseout = eventOverOut('out');
				listItem.onmousedown = eventClick();
				
				if (document.all) {
					listItem.style.width = container.offsetWidth - 20 + 'px';
				}
				
				theList.appendChild(listItem);
			}
			theList.className = '';
		} else {
			theList.innerHTML = '';
			theList.className = 'top-nav-hidden';
		}
	};
	
	// init
	if (container && button && text) {
		text.setAttribute('autocomplete', 'off');
		if (addPageName) {
			path = document.location.pathname;
			pathPieces = path.split('/');
			if (pathPieces.length > 1) {
				pageName = pathPieces[pathPieces.length - 1].split('.')[0];
				if (pageName === '') {
					pageName = pathPieces[pathPieces.length - 2];
				}
			} else {
				pageName = path.split('.')[0];
			}
			pageName = pageName.replace(/[^a-z,0-9]/gi, ' ');
			text.value = pageName;
		}
		setEvents();
		if (help) {
			theList.id = 'my-fake-id';
			theList.className = 'top-nav-hidden';
			theList.style.minWidth = container.offsetWidth - 3 + 'px';
			if (document.all) { // CHANGE THIS SO ITS HANDLED BY CSS
				theList.style.overflow = 'hidden';
			}
			container.appendChild(theList);
		}
	}
}

function BannerScroll(bigSize, banners) {
	var scrollDiv, scrollMain, scrollCp, i, j, theLink = [], theLink2 = [], scrollInt = null, scrollMe, scrollLeft = 0, pauseButton, runStop, paused = false, skip = false, whereToInsertCode, whereToInsert, nextBan, nextButton, prevButton, prevBan, set, smallScrollBox, rand, imageLink, thumbOver, bannerPos = [], banTotal, lastWidth = 0, centerPos, banAmount, start, end, fastScroll = false, resizeInt, jumpTo, jumpToSpot, windowResize, scrollContain, lastCenter = 0, smallImg = [], thumbRight, scrollPosBox, scrollPosBox2, smallScrollLeft, scrollPosWidth, smallScrollLeft2, elapsed = 0, lastTime = 0, bannerHeight, smallBanHeight, smallScroller, setSizes, disableEvents, enableEvents;
	
	smallScroller = function () {
		smallScrollLeft = (scrollLeft / 20);
		if (-smallScrollLeft > smallScrollBox.offsetWidth) {
			smallScrollLeft = (scrollLeft + (banTotal / 2)) / 20;
		}
		scrollPosBox.style.left = -smallScrollLeft + 'px';
		smallScrollLeft2 = -smallScrollLeft + scrollPosWidth;
		if (smallScrollLeft2 > smallScrollBox.offsetWidth) {
			smallScrollLeft2 = (smallScrollLeft2 - smallScrollBox.offsetWidth) - scrollPosWidth;
			scrollPosBox2.style.left = smallScrollLeft2 - 2 + 'px';
		} else {
			scrollPosBox2.style.left = -scrollPosWidth + 'px';
		}
	};
	
	setSizes = function () {
		lastWidth = document.body.offsetWidth;
		centerPos = (scrollMain.offsetWidth < 412) ? 0 : (scrollMain.offsetWidth - 414) / 2;
		scrollContain.style.width = scrollMain.offsetWidth - 14 + 'px';
		start = bannerPos[2] + centerPos;
		end = bannerPos[banners.length + 2] + centerPos;
		scrollPosWidth = (scrollContain.offsetWidth / 20);
		scrollPosBox.style.width = scrollPosWidth + 'px';
		scrollPosBox2.style.width = scrollPosWidth + 'px';
	};
	
	windowResize = function () {
		return function () {
			if (lastWidth !== document.body.offsetWidth) {
				setSizes();
				scrollLeft += centerPos - lastCenter;
				scrollDiv.style.left = scrollLeft + 'px';
				lastCenter = centerPos;
				smallScroller();
			}
		};
	};
	
	rand = function () {
		return Math.random() - 0.5;
	};
	
	disableEvents = function () {
		nextButton.onclick = null;
		prevButton.onclick = null;
		pauseButton.onclick = null;
		scrollDiv.onmouseover = null;
		scrollDiv.onmouseout = null;
	};
	
	enableEvents = function () {
		nextButton.onclick = nextBan();
		prevButton.onclick = prevBan();
		pauseButton.onclick = runStop();
		scrollDiv.onmouseover = runStop();
		scrollDiv.onmouseout = runStop();
	};
	
	// Speed should be positive to scroll left and negative to go right
	scrollMe = function (speed) {
		return function () {
			if (fastScroll) {
				disableEvents();
				if (speed > 0) {
					scrollLeft = (scrollLeft > (end + 40)) ? scrollLeft - speed : start;
				} else {
					scrollLeft = (scrollLeft < (start - 40)) ? scrollLeft - speed : end;
				}
				if (scrollLeft === start || scrollLeft === end) {
					skip = false;
				}
				if (!skip) {
					if ((speed > 0 && scrollLeft < (jumpToSpot + 40)) || (speed < 0 && scrollLeft > (jumpToSpot - 40))) {
						window.clearInterval(scrollInt);
						scrollInt = null;
						scrollLeft = jumpToSpot;
						fastScroll = false;
						enableEvents();
					}
				}
			} else {
				var now = new Date().getTime();
				elapsed = now - lastTime;
				lastTime = now;
				scrollLeft = (scrollLeft > end) ? scrollLeft - speed * elapsed / 1000 * 70 : start;
			}
			scrollDiv.style.left = scrollLeft + 'px';
			smallScroller();
		};
	};
	
	jumpTo = function (pos) {
		return function () {
			this.blur();
			var leftDist, rightDist, direction;
			if (scrollInt !== null) {
				window.clearInterval(scrollInt);
				scrollInt = null;
				paused = true;
				pauseButton.className = 'show-play';
			}
			jumpToSpot = bannerPos[pos] + centerPos;
			if (jumpToSpot > scrollLeft) {
				leftDist = scrollLeft - jumpToSpot;
				rightDist = (end - scrollLeft) + (jumpToSpot - start);
			} else {
				leftDist = (end - jumpToSpot) + (scrollLeft - start);
				rightDist = jumpToSpot - scrollLeft;
			}
			direction = (leftDist > rightDist) ? -40 : 40;
			if (direction > 0) {
				skip = (jumpToSpot > scrollLeft) ? true : false;
			} else {
				skip = (jumpToSpot < scrollLeft) ? true : false;
			}
			fastScroll = true;
			scrollInt = window.setInterval(scrollMe(direction), 20);
			return false;
		};
	};
	
	nextBan = function () {
		return function () {
			this.blur();
			if (scrollInt !== null) {
				window.clearInterval(scrollInt);
				scrollInt = null;
				paused = true;
				pauseButton.className = 'show-play';
			}
			for (i = 2; i < banners.length + 2; i++) {
				if (scrollLeft > bannerPos[i] + centerPos) {
					jumpToSpot = bannerPos[i] + centerPos;
					break;
				} else if (i === banners.length + 1) {
					jumpToSpot = start;
				}
			}
			skip = (jumpToSpot > scrollLeft) ? true : false;
			fastScroll = true;
			scrollInt = window.setInterval(scrollMe(40), 20);
		};
	};
	
	prevBan = function () {
		return function () {
			this.blur();
			if (scrollInt !== null) {
				window.clearInterval(scrollInt);
				scrollInt = null;
				paused = true;
				pauseButton.className = 'show-play';
			}
			for (i = banners.length + 2; i > 1; i--) {
				if (scrollLeft < bannerPos[i] + centerPos) {
					jumpToSpot = bannerPos[i] + centerPos;
					break;
				} else if (i === 2) {
					jumpToSpot = bannerPos[banners.length + 1] + centerPos;
				}
			}
			skip = (jumpToSpot < scrollLeft) ? true : false;
			fastScroll = true;
			scrollInt = window.setInterval(scrollMe(-40), 20);
		};
	};
	
	runStop = function () {
		return function () {
			if (!paused) {
				if (scrollInt !== null) {
					window.clearInterval(scrollInt);
					scrollInt = null;
					if (this.id === 'scroller-run-stop') {
						this.blur();
						pauseButton.className = 'show-play';
						paused = true;
					}
				} else {
					lastTime = new Date().getTime();
					scrollInt = window.setInterval(scrollMe(1), 10);
					if (this.id === 'scroller-run-stop') {
						this.blur();
						pauseButton.className = 'show-pause';
						paused = false;
					}
				}
			} else {
				if (this.id === 'scroller-run-stop') {
					this.blur();
					lastTime = new Date().getTime();
					scrollInt = window.setInterval(scrollMe(1), 10);
					pauseButton.className = 'show-pause';
					paused = false;
				}
			}
		};
	};
	
	thumbOver = function (num) {
		return function () {
			smallImg[num].className = (smallImg[num].className === 'scroller-thumb') ? 'top-nav-hidden' : 'scroller-thumb';
		};
	};
	
	// init
	if (banners) {
		banners.sort(rand);
		banAmount = banners.length * 2;
		bannerHeight = (bigSize) ? 200 : 150;
		smallBanHeight = (bigSize) ? 40 : 30;
		imageLink = (bigSize) ? 'http://layout.opticsplanet.com/images/scroller/' : 'http://layout.opticsplanet.com/images/scroller/mini-slides/';
		
		for (i = 0; i < (banAmount); i++) {
			if (i === 0) {
				bannerPos[i] = 0;
				banTotal = 0;
			} else {
				banTotal += 406;
				bannerPos[i] = banTotal * -1;
			}
			if (i === (banAmount - 1)) {
				banTotal += 406;
			}
		}
		
		scrollMain = createEl('div', {'id' : 'scroller-main-container'});
		scrollMain.style.height = bannerHeight + 36 + 'px';
		scrollCp = createEl('div', {'id' : 'scroller-control-panel'}, scrollMain);
		
		pauseButton = createEl('div', {'id' : 'scroller-run-stop'}, scrollCp);
		pauseButton.className = 'show-pause';
		pauseButton.onclick = runStop();
		
		nextButton = createEl('div', {'id' : 'scroller-next-button'}, scrollCp);
		nextButton.onclick = nextBan();
		
		prevButton = createEl('div', {'id' : 'scroller-prev-button'}, scrollCp);
		prevButton.onclick = prevBan();
		
		smallScrollBox = createEl('div', {'id' : 'scroller-small-box'}, scrollCp);
		scrollPosBox = createEl('div', {'class' : 'scroller-position-box'}, smallScrollBox);
		scrollPosBox2 = createEl('div', {'class' : 'scroller-position-box'}, smallScrollBox);
		
		scrollContain = createEl('div', {'id' : 'scroller-banners-container'}, scrollMain);
		scrollContain.style.height = bannerHeight + 'px';
		
		scrollDiv = createEl('div', {'id' : 'scroller-banners'}, scrollContain);
		scrollDiv.style.width = banTotal + 'px';
		scrollDiv.onmouseover = runStop();
		scrollDiv.onmouseout = runStop();
		
		j = 0;
		thumbRight = (banners.length * 20) - 15;
		for (set in banners) {
			if (banners[set]) {
				theLink[j] = createEl('a', {'href' : banners[set].url}, scrollDiv);
				theLink[j].innerHTML = '<img src="' + imageLink + banners[set].imageId + '.jpg" alt="' + banners[set].alt + '" width="400" height="' + bannerHeight + '">';
				theLink2[j] = createEl('a', {'href' : '#'}, smallScrollBox);
				theLink2[j].innerHTML = j + 1;
				theLink2[j].onmouseover = thumbOver(j);
				theLink2[j].onmouseout = thumbOver(j);
				theLink2[j].onclick = (j < 2) ? jumpTo(j + banners.length) : jumpTo(j);
				smallImg[j] = createEl('img', {'src' : imageLink + 'small/' + banners[set].imageId + '.jpg', 'alt' : banners[set].alt, 'class' : 'top-nav-hidden', 'width' : 80, 'height' : smallBanHeight}, scrollContain);
				smallImg[j].style.right = thumbRight + 'px';
				thumbRight -= 20;
				j++;
			}
		}
		
		for (i = 0; i < theLink.length; i++) {
			scrollDiv.appendChild(theLink[i].cloneNode(true));
		}
		
		if (document.getElementById('breadcrumbs_top')) {
			whereToInsertCode = document.getElementById('breadcrumbs_top').nextSibling;
			whereToInsert = whereToInsertCode.parentNode;
		} else {
			whereToInsert = document.getElementById('main-panel');
			whereToInsertCode = whereToInsert.firstChild;
		}
		
		if (whereToInsertCode) {
			whereToInsert.insertBefore(scrollMain, whereToInsertCode);
		} else if (whereToInsert) {
			whereToInsert.appendChild(scrollMain);
		}
		
		setSizes();
		scrollLeft = start;
		smallScroller();
		scrollDiv.style.left = scrollLeft + 'px';
		scrollPosBox.style.left = -smallScrollLeft + 'px';
		scrollPosBox2.style.left = -scrollPosWidth + 'px';
		
		scrollInt = window.setInterval(scrollMe(1), 10);
		resizeInt = window.setInterval(windowResize(), 100);
	}
}

function AlphaList(id, hideable) {
	var linksContainer, alphaLinks, i, showList, allLists, alphaLists = [], liWidths = [], lastCols = [], liLinks, j, windowResize, lastWindowWidth = 0, colsHeight = [], createCols, colsTotalWidth = [], colsList = [], slideMe, slideInt = null, slideCount = 1, slideAmt, heightDiff =  0, maxCols = [], maxWidth, numCols = [], lastShown = null, titleList = [], title = [], k,  noTitleList = false, seeAll, showAll, clearDiv,
	container = document.getElementById(id),
	ieVersion = getIEVersion();
	
	slideMe = function (closeMe, list, cols) {
		return function () {
			if (closeMe) {
				if (slideCount < 9) {
					colsList[list][cols].style.height = colsList[list][cols].offsetHeight - slideAmt + 'px';
					slideCount++;
				} else {
					colsList[list][cols].style.height = '0px';
					alphaLists[list].className = 'shop-by-lists';
					window.clearInterval(slideInt);
					slideInt = null;
				}
			} else {
				if (slideCount > 2) {
					colsList[list][cols].style.height = colsList[list][cols].offsetHeight + slideAmt + 'px';
					slideCount--;
				} else {
					colsList[list][cols].style.height = colsHeight[list][cols] + 'px';
					colsList[list][cols].className = '';
					window.clearInterval(slideInt);
					slideInt = null;
				}
			}
		};
	};
	
	windowResize = function () {
		return function () {
			if (lastWindowWidth !== document.body.offsetWidth) {
				lastWindowWidth = document.body.offsetWidth;
				if (lastShown !== null) {
					for (i = maxCols[lastShown] - 1; i > -1; i--) {
						if (colsTotalWidth[lastShown][i] < container.offsetWidth) {
							numCols[lastShown] = i;
							break;
						}
					}
					if (numCols[lastShown] !== lastCols[lastShown]) {
						colsList[lastShown][lastCols[lastShown]].className = 'hide-lists';
						colsList[lastShown][numCols[lastShown]].style.height = colsHeight[lastShown][numCols[lastShown]] + 'px';
						colsList[lastShown][numCols[lastShown]].className = '';
						alphaLists[lastShown].removeChild(colsList[lastShown][lastCols[lastShown]]);
						alphaLists[lastShown].appendChild(colsList[lastShown][numCols[lastShown]]);
						lastCols[lastShown] = numCols[lastShown];
					}
				} else if (!hideable || seeAll.innerHTML.match('hide all')) {
					for (i = 0; i < alphaLists.length; i++) {
						for (j = maxCols[i]; j > -1; j--) {
							if (colsTotalWidth[i][j] < container.offsetWidth) {
								numCols[i] = j;
								break;
							}
						}
						if (numCols[i] !== lastCols[i]) {
							alphaLists[i].removeChild(colsList[i][lastCols[i]]);
							alphaLists[i].appendChild(colsList[i][numCols[i]]);
							lastCols[i] = numCols[i];
						}
						if (hideable) {
							colsList[i][numCols[i]].style.height = '';
							colsList[i][numCols[i]].style.paddingTop = '20px';
							if (i > 0) {
								colsList[i][numCols[i]].style.borderTop = '1px solid #ccc';
							}
						}
					}
				}
			}
		};
	};
	
	createCols = function (num) {
		var listItems, rows, start, end, list, k, rowsHeight;
		colsTotalWidth[num] = [];
		colsList[num] = [];
		colsHeight[num] = [];
		listItems = alphaLists[num].getElementsByTagName('a');
		maxCols[num] = 11;
		for (i = 1; i < maxCols[num]; i++) {
			rows = Math.ceil(listItems.length / i);
			if (i > 1 && rows < 3) {
				maxCols[num] = i - 1;
				break;
			}
			if (!noTitleList) {
				colsTotalWidth[num][i] = (hideable) ? 80 : 130;
			} else {
				colsTotalWidth[num][i] = 0;
			}
			start = 0;
			end = rows;
			colsList[num][i] = document.createElement('li');
			rowsHeight = rows * 18;
			colsHeight[num][i] = (rowsHeight > 63) ? rowsHeight : 63;
			if (hideable) {
				colsList[num][i].style.height = '0px';
			}
			if (!noTitleList) {
				colsList[num][i].appendChild(title[num].cloneNode(true));
			}
			for (j = 0; j < i; j++) {
				if (listItems[start]) {
					list = document.createElement('ul');
					maxWidth = 0;
					for (k = start; k < end; k++) {
						if (listItems[k]) {
							list.appendChild(listItems[k].parentNode.cloneNode(true));
							if (liWidths[num][k] > maxWidth) {
								maxWidth = liWidths[num][k];
							}
						}
					}
					if (hideable) {
						maxWidth += 20;
					} else {
						maxWidth += 50;
					}
					colsTotalWidth[num][i] += maxWidth;
					if (ieVersion === 6) {
						list.style.width = maxWidth - 30 + 'px';
					}
					start += rows;
					end += rows;
					colsList[num][i].appendChild(list);
				}
			}
		}
	};
	
	showList = function (num) {
		return function () {
			this.blur();
			if (slideInt !== null) {
				return false;
			}
			if (!colsList[num]) {
				createCols(num);
			}
			for (i = maxCols[num]; i > -1; i--) {
				if (colsTotalWidth[num][i] < container.offsetWidth) {
					numCols[num] = i;
					break;
				}
			}
			if (lastShown !== null) {
				alphaLinks[lastShown].className = '';
				if (lastShown === num) {
					colsList[lastShown][lastCols[lastShown]].className = 'hide-lists';
					slideCount = 1;
					slideAmt = colsHeight[lastShown][numCols[lastShown]] / 10;
					slideAmt = (ieVersion > 0) ? Math.floor(slideAmt) : slideAmt;
					slideInt = window.setInterval(slideMe(true, lastShown, numCols[lastShown]), 25);
					lastShown = null;
					return false;
				}
				heightDiff = colsHeight[num][numCols[num]] - colsHeight[lastShown][lastCols[lastShown]];
				colsList[num][numCols[num]].style.height = colsList[lastShown][lastCols[lastShown]].offsetHeight + 'px';
				colsList[lastShown][lastCols[lastShown]].className = 'hide-lists';
				colsList[lastShown][lastCols[lastShown]].style.height = '0px';
				alphaLists[lastShown].className = 'shop-by-lists';
				if (heightDiff === 0) {
					alphaLinks[num].className = 'shop-by-alpha-letter-selected';
					alphaLists[num].className += ' show-list';
					colsList[num][numCols[num]].className = '';
					if (numCols[num] !== lastCols[num]) {
						alphaLists[num].innerHTML = '';
						alphaLists[num].appendChild(colsList[num][numCols[num]]);
						lastCols[num] = numCols[num];
					}
					lastShown = num;
					return false;
				}
			}
			if (numCols[num] !== lastCols[num]) {
				alphaLists[num].innerHTML = '';
				alphaLists[num].appendChild(colsList[num][numCols[num]]);
				lastCols[num] = numCols[num];
			}
			alphaLinks[num].className = 'shop-by-alpha-letter-selected';
			alphaLists[num].className += ' show-list';
			slideCount = 10;
			slideAmt = (heightDiff !== 0) ? heightDiff / 10 : colsHeight[num][numCols[num]] / 10;
			slideAmt = (ieVersion > 0) ? Math.floor(slideAmt) : slideAmt;
			colsList[num][numCols[num]].className = 'hide-lists';
			slideInt = window.setInterval(slideMe(false, num, numCols[num]), 25);
			lastShown = num;
			heightDiff = 0;
			return false;
		};
	};
	
	showAll = function () {
		return function () {
			if (seeAll.innerHTML === '+ show all') {
				for (k = 0; k < alphaLinks.length; k++) {
					alphaLists[k].className = alphaLists[k].className.replace(new RegExp(' show-list\\b'), '');
					alphaLinks[k].onclick = null;
					alphaLists[k].className += ' show-list';
					alphaLinks[k].className = '';
					
					if (!colsList[k]) {
						createCols(k);
					}
					for (i = maxCols[k]; i > -1; i--) {
						if (colsTotalWidth[k][i] < container.offsetWidth) {
							numCols[k] = i;
							break;
						}
					}
					if (numCols[k] !== lastCols[k]) {
						alphaLists[k].innerHTML = '';
						alphaLists[k].appendChild(colsList[k][numCols[k]]);
						lastCols[k] = numCols[k];
					}
					colsList[k][numCols[k]].style.height = '';
					colsList[k][numCols[k]].style.padding = '10px 0';
					if (k > 0) {
						colsList[k][numCols[k]].style.borderTop = '1px solid #ccc';
					}
				}
				lastShown = null;
				seeAll.innerHTML = '&mdash; hide all';
			} else {
				for (k = 0; k < alphaLinks.length; k++) {
					alphaLinks[k].onclick = showList(k);
					alphaLists[k].className = alphaLists[k].className.replace(new RegExp(' show-list\\b'), '');
					colsList[k][numCols[k]].style.height = '0px';
					colsList[k][numCols[k]].style.padding = '';
					if (k > 0) {
						colsList[k][numCols[k]].style.borderTop = '';
					}
				}
				seeAll.innerHTML = '+ show all';
			}
			return false;
		};
	};
	
	// init
	if (container) {
		if (hideable) {
			linksContainer = getElementsByClassName(container, 'shop-by-alpha-links', 'span')[0];
			alphaLinks = linksContainer.getElementsByTagName('a');
			for (i = 0; i < alphaLinks.length; i++) {
				alphaLinks[i].onclick = showList(i);
			}
			seeAll = document.createElement('a');
			seeAll.innerHTML = '+ show all';
			seeAll.href = '#';
			seeAll.onclick = showAll();
			seeAll.id = 'shop-by-show-all';
			linksContainer.parentNode.insertBefore(seeAll, linksContainer);
			clearDiv = document.createElement('div');
			clearDiv.style.clear = 'both';
			container.appendChild(clearDiv);
		}
		allLists = getElementsByClassName(container, 'shop-by-lists', 'ul');
		for (k = 0; k < allLists.length; k++) {
			alphaLists[k] = allLists[k];
			liWidths[k] = [];
			lastCols[k] = -1;
			liLinks = alphaLists[k].getElementsByTagName('a');
			for (j = 0; j < liLinks.length; j++) {
				liWidths[k][j] = liLinks[j].offsetWidth;
			}
			titleList[k] = allLists[k].getElementsByTagName('ul')[0];
			if (titleList[k].getElementsByTagName('li')[0].className === 'shop-by-pic-link' || titleList[k].getElementsByTagName('li')[0].className === 'shop-by-big-letter') {
				title[k] = titleList[k].cloneNode(true);
				alphaLists[k].getElementsByTagName('li')[0].removeChild(titleList[k]);
			} else {
				noTitleList = true;
			}
			if (!hideable) {
				alphaLists[k].className += ' show-list';
				createCols(k);
				alphaLists[k].innerHTML = '';
				alphaLists[k].appendChild(colsList[k][1]);
				lastCols[k] = 1;
			}
		}
		window.setInterval(windowResize(), 200);
		container.className += ' shop-by-script';
	}
}

function ShopByScroller(id) {
	var container, boxes, i, totalWidth, scrollInt, scrollBoxes, currentPos = 0, resetSpot, mouseOver, prevBut, nextBut, fastScroll, fastCount, frame, 
	outerDiv = document.getElementById(id);
	
	fastScroll = function (direction) {
		return function () {
			nextBut.onclick = null;
			prevBut.onclick = null;
			container.onmouseover = null;
			if (scrollInt !== null) {
				window.clearInterval(scrollInt);
			}
			fastCount = 0;
			resetSpot += direction;
			scrollInt = window.setInterval(scrollBoxes(direction), 50);
		};
	};
	
	mouseOver = function (over) {
		return function () {
			if (over) {
				if (scrollInt !== null) {
					window.clearInterval(scrollInt);
					scrollInt = null;
				}
			} else {
				if (scrollInt === null) {
					scrollInt = window.setInterval(scrollBoxes(1), 25);
				}
			}
		};
	};
	
	scrollBoxes = function (speed) {
		return function () {
			currentPos -= speed;
			if (speed !== 1) {
				fastCount++;
				if (fastCount === 10) {
					window.clearInterval(scrollInt);
					resetSpot = -totalWidth + 2;
					prevBut.onclick = fastScroll(-20);
					nextBut.onclick = fastScroll(20);
					container.onmouseover = mouseOver(true);
					scrollInt = window.setInterval(scrollBoxes(1), 25);
				}
			}
			if (speed > 0) {
				currentPos = (currentPos < resetSpot) ? 0 : currentPos;
			} else {
				currentPos = (currentPos > -20) ? resetSpot : currentPos;
			}
			container.style.left = currentPos + 'px';
		};
	};
	
	// init
	if (outerDiv) {
		frame = getElementsByClassName(outerDiv, 'shop-by-scroll-frame', 'div')[0];
		frame.className += ' with-script';
		container = getElementsByClassName(frame, 'shop-by-scroll-container', 'div')[0];
		if (container) {
			boxes = getElementsByClassName(container, 'shop-by-scroll-box', 'div');
			totalWidth = boxes.length * 192;
			resetSpot = -totalWidth + 2;
			container.style.width = (totalWidth * 2) + 'px';
			for (i = 0; i < boxes.length; i++) {
				container.appendChild(boxes[i].cloneNode(true));
			}
			container.onmouseover = mouseOver(true);
			container.onmouseout = mouseOver(false);
			prevBut = getElementsByClassName(outerDiv, 'shop-by-scroll-prev', 'div')[0];
			prevBut.className = 'shop-by-scroll-prev-on';
			prevBut.onclick = fastScroll(-20);
			nextBut = getElementsByClassName(outerDiv, 'shop-by-scroll-next', 'div')[0];
			nextBut.className = 'shop-by-scroll-next-on';
			nextBut.onclick = fastScroll(20);
			scrollInt = window.setInterval(scrollBoxes(1), 25);
		}
	}
}

function spansToLinks() {
	var allSpanTags, i, tagsLength, spanTag, unSpanTag;
	allSpanTags = document.getElementsByTagName('span');
	tagsLength = allSpanTags.length;
	for (i = 0; i < tagsLength; i++) {
		spanTag = allSpanTags[i];
		if (spanTag.title.indexOf('||') !== -1) {
			if (spanTag.getElementsByTagName('span').length === 0 && spanTag.innerHTML.length < 500) {
				unSpanTag = document.createElement(String.fromCharCode(65));
				unSpanTag.href = String.fromCharCode(72) + 'tt' + String.fromCharCode(80) + ':' + spanTag.title.replace(/\//g, String.fromCharCode(46)).replace(/\|/g, String.fromCharCode(47));
				unSpanTag.className = spanTag.className;
				unSpanTag.id = spanTag.id;
				unSpanTag.innerHTML = spanTag.innerHTML;
				spanTag.innerHTML = '';
				spanTag.appendChild(unSpanTag);
			}
			spanTag.title = '';
			spanTag.style.paddingLeft = '0';
		}
	}
}

function cookieCheckIn(len) {
	if (cookiesForBridge.length === len) {
		addScriptToHead('http://tracker.opticsplanet.com/bridge.php?_rand=' + Math.random() + '&_realm=opticsplanet&' + cookiesForBridge.join('&'), '', 'js');
	} else {
		window.setTimeout('cookieCheckIn(' + len + ');', 100);
	}
}

function filterRelatedItems() {
	var timesRun = 0, yStoreCode = null, filter;
	
	filter = function () {
		return function () {
			var relatedDiv, relatedRows, relatedLink, relatedUrl, i, length;
			if (timesRun < 100) {
				timesRun++;
				if (typeof(YStore) !== 'undefined') {
					if (typeof(YStore.csellData) !== 'undefined' && typeof(YStore.csellData.r) !== 'undefined') {
						if (YStore.csellData.r.length > 0) {
							relatedDiv = document.getElementById('ys_relatedItems');
							if (relatedDiv) {
								relatedRows = relatedDiv.getElementsByTagName('tr');
								length = relatedRows.length;
								for (i = 0; i < length; i++) {
									relatedLink = relatedRows[i].getElementsByTagName('a')[0];
									if (relatedLink) {
										relatedUrl = relatedLink.href;
										if (relatedUrl.match(/bundle-[0-9]{6}-[a-z0-9]+/)) {
											relatedRows[i].style.display = 'none';
										}
									}
								}
								return true;
							}
						}
					} else if (typeof(YStore.crossSellUrl) !== 'undefined' && yStoreCode === null) {
						yStoreCode = YStore.crossSellUrl + '&callback=YStore.csellData=&noCacheIE=' + Math.random();
						addScriptToHead(yStoreCode, '', 'js');
					}
				}
				window.setTimeout(filter(), 100);
			}
		};
	};
	
	// init
	if (document.getElementById('priceblock')) {
		window.setTimeout(filter(), 100);
	}
}

function Banners(name, placement, insertBeforeId, imgWidth, imgHeight) {
	var insertBeforeObject;
	
	// adds banners into html
	this.show = function (data) {
		var container, banner, subElement, i, url, sidbInput,
		bannerData = data.banners;
		
		if (bannerData && bannerData.length > 0) {
			container = document.createElement('div');
			container.id = placement + '-banners-container';
			
			for (i = 0; i < bannerData.length; i++) {
				if (bannerData[i].html) {
					container.innerHTML += bannerData[i].html;
				} else if (bannerData[i].id && (bannerData[i].title || bannerData[i].text)) {
					banner = document.createElement('a');
					banner.className = placement + '-banner';
					url = 'http://tracker.opticsplanet.com/banner/resolve.php?page=' + encodeURIComponent(window.location) + '&banner_id=' + bannerData[i].id;
					banner.setAttribute('href', url);
					
					if (bannerData[i].image_id) {
						subElement = document.createElement('img');	
						subElement.setAttribute('src', 'http://images' + (i % 2 + 1) + '.opticsplanet.com/' + imgWidth + '-' + imgHeight + '-ffffff/' + bannerData[i].image_id + '.gif');
						subElement.setAttribute('width', imgWidth);
						subElement.setAttribute('height', imgHeight);
						subElement.setAttribute('alt', bannerData[i].title ? bannerData[i].title : bannerData[i].text);
						banner.appendChild(subElement);
					}
					
					if (bannerData[i].title) {
						subElement = document.createElement('span');
						subElement.className = placement + '-banner-title';
						subElement.innerHTML = bannerData[i].title;
						banner.appendChild(subElement);
					}
					
					if (bannerData[i].text) {
						subElement = document.createElement('span');
						subElement.className = placement + '-banner-body';
						subElement.innerHTML = bannerData[i].text;
						banner.appendChild(subElement);
					}
					container.appendChild(banner);
				}
			}
			insertBeforeObject.parentNode.insertBefore(container, insertBeforeObject);
		}
		
		if ((data.was_clicked === true || data.was_clicked === 'true') && document.getElementById('addToCartForm')) {
			sidbInput = document.createElement('input');
			sidbInput.type = 'hidden';
			sidbInput.name = 'OPSIDB';
			sidbInput.value = data.bsid;
			sidbInput.id = 'op-sidb';
			document.getElementById('addToCartForm').appendChild(sidbInput);
		}
	};
	
	// init
	insertBeforeObject = document.getElementById('page-container');
	if (insertBeforeObject) {
		addScriptToHead('http://tracker.opticsplanet.com/banner/serve.php?page=' + encodeURIComponent(window.location) + '&jsoncallback=' + name + '.show&placement=' + placement + '&rand' + Math.round(Math.random() * 1000000), '', 'js');
	}
}

// feedback forms popup stuff (D. Naumov) (Optimized by M. Fayman)
function classFeedbackForm() {
	var msgInt,
	divLargeWrapper = createEl('div', {'id': 'help-large-wrapper'}),
	divSmallWrapper = createEl('div', {'id': 'help-small-wrapper'}, divLargeWrapper),
	helpWindow = createEl('div', {'id': 'help-window'}, divSmallWrapper),
	helpHeader = createEl('div', {'id': 'help-header'}, helpWindow),
	helpCloseButton = createEl('div', {'id': 'help-close-button'}, helpHeader),
	spanTitle = createEl('span', {'id': 'span-title'}, helpHeader),
	formFrame = createEl('iframe', {'id': 'form-frame', 'width': '650', 'height': '1500', 'allowtransparency': 'true', 'frameborder': 'no', 'scrolling': 'no', 'src': '#', 'onload': 'this.style.visibility = "visible";'}, helpWindow),
	linkRFQ = document.getElementById('icon-link-price_quote'),
	linkPriceMatch = document.getElementById('icon-link-best_price'),
	linkExpertAdvice = document.getElementById('icon-link-ask_an_expert'),
	linkDealNotification = document.getElementById('icon-link-deal_request'),
	linkCallToOrder = document.getElementById('call-to-order-button'),
	link2CallToOrder = document.getElementById('call-to-order-link'),
	feedbackData = {
		'rfq' : {'title' : 'RFQ', 'height' : '1030px', 'ie6height' : '1060px'},
		'es' : {'title' : 'Email Support', 'height' : '550px', 'ie6height' : '580px'},
		'pm' : {'title' : 'Price Match', 'height' : '780px', 'ie6height' : '810px'},
		'ea' : {'title' : 'Expert Advice', 'height' : '520px', 'ie6height' : '550px'},
		'dn' : {'title' : 'Deal Notification', 'height' : '820px', 'ie6height' : '850px'},
		'etp' : {'title' : 'Email This Page', 'height' : '650px', 'ie6height' : '680px'},
		'cto' : {'title' : 'Call To Order', 'height' : '1030px', 'ie6height' : '1060px'}
	},
	
	showMessageFromIFrame = function () {
		return function () {
			var msg = window.location.hash.substring(1);
			if (msg === 'resize') {
				helperResizeForCloseScreen();
				window.location.hash = '';
			} else if (msg === 'close') {
				classFeedbackForm.closeFormWindow();
				window.location.hash = '';
				window.clearInterval(msgInt);
			}
		};
	},
	
	openFormWindow = function (type) {
		return function () {
			var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
			if (isIE6) {
				window.scrollTo(0, 0);
			}
			spanTitle.innerHTML = feedbackData[type].title;
			//helpWindow.style.height = isIE6 ? feedbackData[type].ie6height : feedbackData[type].height;
			formFrame.src = this.href.replace(/fullsize|window/, 'iframe');
			formFrame.style.visibility = 'hidden';
			helpWindow.style.display = 'block';
			msgInt = window.setInterval(showMessageFromIFrame(), 100);
			return false;
		};
	},
	
	closeButton = function () {
		return function () {
			helpWindow.style.display = 'none';
			return false;
		};
	};
	
	this.closeFormWindow = function () {
		closeButton()();
		return false;
	};
	
	// constructor
	helpCloseButton.onclick = closeButton();
	document.body.appendChild(divLargeWrapper);
	if (linkRFQ) {
		linkRFQ.onclick = openFormWindow('rfq');
	}
	if (linkPriceMatch) {
		linkPriceMatch.onclick = openFormWindow('pm');
	}
	if (linkExpertAdvice) {
		linkExpertAdvice.onclick = openFormWindow('ea');
	}
	if (linkDealNotification) {
		linkDealNotification.onclick = openFormWindow('dn');
	}
	if (linkCallToOrder) {
		linkCallToOrder.onclick = openFormWindow('cto');
	}
	if (link2CallToOrder) {
		link2CallToOrder.onclick = openFormWindow('cto');
	}
}; // end of classFeedbackForm

// function for resizing confirmation popup (D. Naumov)
function helperResizeForCloseScreen() {
	window.scrollTo(0,0);
}

function newsletterData() {
	var nlCookie = new Cookie('_opnld'), nldInput,
	data = window.location.search.match(/nldata=[a-z,0-9,\/]+/i);
	if (data) {
		data += '';
		data = data.split('=')[1];
		nlCookie.setValue(data, 168);
	}
	data = nlCookie.getValue();
	if (data && document.getElementById('addToCartForm')) {
		nldInput = document.createElement('input');
		nldInput.type = 'hidden';
		nldInput.name = 'OPNLD';
		nldInput.value = data;
		nldInput.id = 'op-nld';
		document.getElementById('addToCartForm').appendChild(nldInput);
	}
}

function VelaroChat() {
	var chatButton = document.getElementById('velaro-chat-button');
	this.setDisplay = function (display) {
		chatButton.style.display = display;
	};
	// init
	if (chatButton) {
		chatButton.style.display = 'none';
		addScriptToHead('http://tracker.opticsplanet.com/velaro.js?_rand=' + Math.round(Math.random() * 1000000), '', 'js');
	}
}

function setupTipBoxes() {
	var i, l, special, id, element,
	ctoTips = getElementsByClassName(document, 'cto-tip-me', 'span'),
	rxTips = {
		'rx-sphere' : 'Optical power of a lens in diopters <strong>+ or - sign must be specified</strong> <br>If NO VALUE is present, please leave empty. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#power">More details...</a>',
		'rx-cylinder' : 'Measure of astigmatism in diopters <strong>+ or - sign must be specified</strong> <br>If NO VALUE is present, please leave empty. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#cylinder">More details...</a>',
		'rx-axis' : 'Orientation of the axis of a cylindrical lens <br>If NO VALUE is present, please leave empty. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#axis">More details...</a>',
		'rx-prism' : 'Prescribed when a diagnosis of a muscle or focusing disorder is present <br>If NO VALUE is present, please leave empty. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#prism">More details...</a>',
		'rx-base' : 'Rotation of a prism <br>If NO VALUE is present, please leave empty. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#base">More details...</a>',
		'bino-pd' : 'Distance between the <strong>centers</strong> of two pupils (<strong>mm</strong>)<br>Either binocular <strong>OR</strong> monocular PD <strong>must be specified</strong>',
		'mono-pd' : 'Distance between the <strong>center</strong> of each pupil and edge of the nose (<strong>mm</strong>)<br>Either binocular <strong>OR</strong> monocular PD <strong>must be specified</strong>',
		'rx-add' : 'Additional magnification in the lower portion of a multifocal lens <br>(AKA no line progressive, lined bifocal, or trifocal). <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#add_power">More details...</a>',
		'rx-seght' : 'Defines a height of the bifocal/progressive segment of a lens<br><strong>Must be included for bifocal & progressive lenses</strong>. <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#segment_height">More details...</a>',
		'rx-distpd' : 'Distance between the <strong>center</strong> of each pupil and edge of the nose (<strong>mm</strong>)<br>(For <strong>distance vision</strong>). <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#pupil_distance">More details...</a>',
		'rx-nearpd' : 'Distance between the <strong>center</strong> of each pupil and edge of the nose (<strong>mm</strong>)<br>(For <strong>near vision/reading</strong>). <a href="http://www.tactical-store.com/prescription-sunglasses-info.html#pupil_distance">More details...</a>'
	};
	
	for (i = 0, l = ctoTips.length; i < l; i++) {
		special = (ctoTips[i].parentNode.parentNode.className !== 'left-panel-specials-item') ? true : false;
		TipBox(ctoTips[i], 'Please call our phone sales department toll free at 800-504-5994 or go to the product page and click the Call To Order button to fill out the form for more information on this item.', special);
	}
	for (id in rxTips) {
		if (rxTips[id]) {
			element = document.getElementById(id);
			if (element) {
				TipBox(element, rxTips[id], false);
			}
		}
	}
}

function copyPagination() {
	var i, l,
	fromNode = document.getElementById('pagination-top'),
	toNode = document.getElementById('pagination-bottom');

	if (fromNode && toNode) {
		toNode.innerHTML = '';
		for (i = 0, l = fromNode.childNodes.length; i < l; i++) {
			toNode.appendChild(fromNode.childNodes[i].cloneNode(true));
		}
	}
}

function initOpticsPlanetPage() {
	var i, objList, selectors;
	if (arguments.callee.done) { // check if we've been here before
		return;  // don't need to run this twice
	}
	arguments.callee.done = true; // flag this function so we don't do the same thing twice
	
	
	// If user came from another domain, cross the cookie bridge
	if (!document.referrer.match(document.domain)) {
		addScriptToHead('http://tracker.opticsplanet.com/bridge.php?_rand=' + Math.random() + '&_realm=opticsplanet', '', 'js');
	} else {
		// Check/Set cookie and Display Recently Viewed History
		window.setTimeout('History();', 1);
	
		// load up google analytics
		addScriptToHead((('https:' === document.location.protocol) ? 'https://ssl.' : 'http://www.') + 'google-analytics.com/ga.js', '', 'js');
		window.setTimeout('googleAnalytics();', 1);
	}
	
	oldIE = (window.external && typeof window.XMLHttpRequest === 'undefined');
	if (oldIE) {
		window.setTimeout('IE6MinWidthFix();', 0); // css expressions are uncool but we need min-width in IE6
	}
	
	// turn those special spans into links
	window.setTimeout('spansToLinks();', 0);
	
	// fix fuckups
	//initPriceAdjust();
	//initDisableAddToCart();

	// setup selectors
	objList = document.getElementById('object-list');
	if (objList) {
		selectors = getElementsByClassName(objList, 'sub-page-selector', 'ul');
		for (i = 0; i < selectors.length; i++) {
			window.setTimeout("var selectorsInit" + i + " = new Selectors(" + i + ");", 0);
		}
	}
	
	// setup bundles expand and collapse
	window.setTimeout('Bundles();', 0);
	
	// Top nav drop down
	window.setTimeout('DropTop();', 0);
	
	// make sure people/bots don't submit your@email.com to mailing list
	window.setTimeout('validateMailingListForm();', 0);

	// setup collapsible question and answer
	window.setTimeout('QNA();', 0);
		
	// Makes Sort By go away in tabs
	window.setTimeout("var topSortBy = new SortByBeGone('sort-by-navigation-top');", 0);
	window.setTimeout("var bottomSortBy = new SortByBeGone('sort-by-navigation-bottom');", 0);
	
	//Search Form Bar
	if (document.getElementById('smarty-search-page') && document.getElementById('left-menu-search')) {
		window.setTimeout("searchBoxHelp = new SearchBox('smarty-search-page', 'smarty-search-page-submit', 'smarty-search-page-text', true, true);", 0);
		window.setTimeout("var leftSearchBox = new SearchBox('left-menu-search', 'left-menu-search-submit', 'left-menu-search-text', false, false);", 0);
	} else if (document.getElementById('smarty-search-page')) {
		window.setTimeout("searchBoxHelp = new SearchBox('smarty-search-page', 'smarty-search-page-submit', 'smarty-search-page-text', true, false);", 0);
	} else if (document.getElementById('shop-by-search-page')) {
		window.setTimeout("searchBoxHelp = new SearchBox('shop-by-search-page', 'shop-by-search-page-submit', 'shop-by-search-page-text', true, false);", 0);
	} else {
		window.setTimeout("searchBoxHelp = new SearchBox('left-menu-search', 'left-menu-search-submit', 'left-menu-search-text', true, false);", 0);
	}
	
	// Setup the tip boxes
	window.setTimeout('TipYourServer();', 0);
	
	// setup tip boxes
	window.setTimeout('setupTipBoxes();', 0);
		
	// load up yahoo analytics - this should be called on the .com pages
	if (document.URL.match('opticsplanet.com')) {
		addScriptToHead('http://d.yimg.com/mi/ywa.js', '', 'js');
		window.setTimeout('yahooAnalytics();', 100);
	}
	
	// load Velaro
	window.setTimeout('Velaro();', 0);
	
	// load up MSN PPC
	window.setTimeout('msnPpc();', 0);
	
	// load up image gallery script for product pages
	window.setTimeout('ImageSwapper();', 0);
	
	// start check in to use the bridge as soon as the needed cookies are available
	if (document.getElementById('right-panel')) {
		window.setTimeout('cookieCheckIn(3)', 100);
	} else {
		window.setTimeout('cookieCheckIn(1)', 100);
	}
	
	// start header banner loader
	window.setTimeout("headerBanners = new Banners('headerBanners', 'header', 'page-container', 60, 60)", 0);
	
	// filter out bundle items from yahoo related items
	window.setTimeout('filterRelatedItems()', 0);
	
	if (document.domain.match('opticsplanet.com') && !document.domain.match('feedback')) {
		// required for classFeedbackForm JS security permissions (D. Naumov)
		document.domain = 'opticsplanet.com';
	}
	
	// init feedback forms (D. Naumov)
	//classFeedbackForm = new classFeedbackForm();
	
	// checks if newsletter data is in url and adds cookie
	window.setTimeout('newsletterData();', 0);
	
	// if pagination is there, copy it to the bottom
	window.setTimeout('copyPagination();', 0);
}
