var oldIE = false, jsonVoorhees = [], searchBoxHelp, headerBanners, facebookCommentsCount = {}, _gaq = _gaq || [], godMode = false; // enable for new feature testing by #godMode=on

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;
}

// this makes Mike's createEl function more convinient for building trees of elements
function createElementTree(elType, elExtras, elChildren){
	var attribute, child,
	el = document.createElement(elType);
	for (attribute in elExtras) {
		if (elExtras[attribute] !== '') {
			if (document.all) {
				if(attribute === 'class'){
					el.className = elExtras[attribute];
				} else {
					el[attribute] =  elExtras[attribute];
				}
			} else {
				el.setAttribute(attribute, elExtras[attribute]);
			}
		}
	}
	if (elChildren) {
		for (child in elChildren) {
			if(typeof elChildren[child] === 'string'){
				el.appendChild(document.createTextNode(elChildren[child]));
			} else {
				el.appendChild(elChildren[child]);
			}
		}
	}
	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) {
		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;
	};
	
	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) rightPanelBox = getElementsByClassName(rightPanel, 'menu-box menu-box-multiline', '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);
				
				createList();
				if (urls.length > collapseAfter) {
					createButton();
					collapseMe();
				}
				if (oldIE) {
					fixIE6();
				}
			}
		}
	}
}

// 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 (Edited by V.Nguyen)
function Bundles() {
	var table, i, tbody, rows, hideShow, bundlePrice, header, eventOverOut, createButton, bundleTitle, bundleTitleArrow, bundlePrice, hiddenBundlePrice, bundleRow,
	bundleArrow = document.createElement('span');
	tbody = null;
	rows = null;
	
	// Hides and shows the extra rows in bundles table
	hideShow = function () {
		return function () {
			var i;
			for (i = 1; i < rows.length; i++) {
				hiddenRow = rows[i];
				hiddenRow.className = (hiddenRow.className === 'top-nav-hidden') ? '' : 'top-nav-hidden';
			}
			hiddenBundlePrice.innerHTML = (hiddenBundlePrice.innerHTML === '') ? 'Total' : '';
			bundleRow.id = (bundleRow.id === 'bundle-arrow-more') ? 'bundle-arrow-less' : 'bundle-arrow-more';
		};
	};
	
	// Mouse over event
	eventOverOut = function () {
		return function (e) {
			bundleRow.className = (bundleRow.className === 'bundle-arrow-hover') ? '' : 'bundle-arrow-hover';
		};
	};
	
	// Creates the row, and its contents, for the more-less button
	createButton = function () {
		bundleTitle = getElementsByClassName(tbody,'optionrxtitle','td');
		bundlePrice = getElementsByClassName(tbody,'optionrxtitlel','td');
		inputBox = table.getElementsByTagName('input');
		
		if (hiddenRow.className === 'top-nav-hidden'){
			for (i = 0; i < bundleTitle.length; i++) {
				bundleTitleArrow = bundleTitle[i];
			}
			for (i = 0; i < bundlePrice.length; i++) {
				hiddenBundlePrice = bundlePrice[i];
				hiddenBundlePrice.innerHTML = '';
			}
		}
		bundleRow = bundleTitleArrow.parentNode;
		bundleRow.id = 'bundle-arrow-more';
		for (i = 0; i < inputBox.length - 1; i++) {
			inputRadio = inputBox[i];
			inputRadio.className = 'hi';
			bundleRow.onclick = hideShow();
			bundleRow.onmouseover = eventOverOut();
			bundleRow.onmouseout = eventOverOut();
			/*if (!inputRadio.checked){
				bundleRow.onclick = hideShow();
				bundleRow.onmouseover = eventOverOut();
				bundleRow.onmouseout = eventOverOut();
			}
			if (inputRadio.checked){
				bundleRow.onclick = null;
				bundleRow.onmouseover = null;
				bundleRow.onmouseout = null;
			}*/
		}
	};
	// init
	table = document.getElementById('bundles-table');
	if (table) {
		tbody = table.getElementsByTagName('tbody')[0];
		if (tbody) {
			rows = tbody.getElementsByTagName('tr');
			if (rows.length > 2) {
				table.className = 'bundles-dropdown-container';
				for (i = 1; i < rows.length; i++) {
					hiddenRow = rows[i];
					hiddenRow.className = 'top-nav-hidden';
				}
				createButton();
			}
		}
	}
}

// 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');
		if(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. Please see our <a href="/map.html">MAP (Minimum Advertised Price) page</a> for explanation of pricing.';
	
	// 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 > 960 ? '' : '960px';
				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&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);
	}
}

function googleAnalyticsAsync(){
	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
	
	var searchBox, searchPage = null, headerTag, headerText, searchQuery;
	
	_gaq.push(['_setAccount', 'UA-138028-1']);
	_gaq.push(['_setDomainName', 'none']);
	_gaq.push(['_setAllowLinker', true]);
	_gaq.push(['_setAllowAnchor', true]);
	
	// tracking search pages
	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) {
		_gaq.push(['_trackPageview', searchPage]);
	} else {
		_gaq.push(['_trackPageview']);
	}
	
	// init Facebook callbacks
	try {
		if (FB && FB.Event && FB.Event.subscribe) {
			
			FB.Event.subscribe('edge.create', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
			});
			
			FB.Event.subscribe('edge.remove', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
			});
			
			FB.Event.subscribe('message.send', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
			});
			
			FB.Event.subscribe('comment.create', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'comment', targetUrl]);
			});
				
			FB.Event.subscribe('comment.remove', function(targetUrl) {
				_gaq.push(['_trackSocial', 'facebook', 'uncomment', targetUrl]);
			});
			
		}
	} catch (e) {}
	
	// init links to the shopping cart. use `live` so it will be applied to any generated links
	$('a[href*="store.yahoo.net"]').live('click',function(){
		_gaq.push(['_link', $(this).attr('href'),true]);
		return false; 
	});
	
	// init old style add to cart
	if(document.getElementById("addToCartForm")){
		_gaq.push(['_linkByPost', document.getElementById("addToCartForm"), true]);
	}
	
	// TRACK!
	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  	})();
	
	// send GA cookies to our other domains
	var cookieBridge = function (){
		var gaCookies = document.cookie.match(/^(.*__utm[abcz].*){2}$/);

		if(gaCookies) { // found GA cookies!
			window.clearInterval(cookieBrdigeInterval);

			var cookieTail = "#" + encodeURIComponent(document.cookie) + '" style="position:absolute;left:-10000000px;top:-100000000px;height:1px;width:1px;"></iframe>';
			
			if(!document.location.host.match(/opticsplanet\.com/)){
				$(document.body).append('<iframe src="http://cookiebridge.opticsplanet.com/' + cookieTail);
			}
			
			if(!document.location.host.match(/opticsplanet\.net/)){
				$(document.body).append('<iframe src="http://cookiebridge.opticsplanet.net/' + cookieTail);
			}
			
			if(!document.location.host.match(/\.store\.yahoo\.net/)){
				$(document.body).append('<iframe src="http://search.store.yahoo.net/opticsplanet/cgi-bin/nsearch?catalog=opticsplanet' + cookieTail);
			}
		}
	};
	
	var cookieBrdigeInterval = window.setInterval(cookieBridge,100);
}

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'),
	socialBlockIframe = document.getElementById('main-panel').getElementsByTagName('iframe'),
	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';
				}
				for (i = 0; i < socialBlockIframe.length; i++){
					socialBlockIframe[i].style.visibility = 'visible';
				}
			}
		};
	};
	
	// 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;
			}
			if (document.all){
				for (i = 0; i < socialBlockIframe.length; i++){
						socialBlockIframe[i].style.visibility = 'visible';
				}
			}
		};
	};
	
	// 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 {
					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);
				}
				for (i = 0; i < socialBlockIframe.length; i++){
					socialBlockIframe[i].style.visibility = 'hidden';
				}
			}
			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) {
			
			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]) {
				if (banners[set].url && banners[set].imageId && banners[set].alt) {
					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(104) + 'tt' + String.fromCharCode(112) + ':' + 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 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 multitypeBanners(name, placement, imgWidth, imgHeight) {
	var insertBeforeObject, documClick = null, innerClick = false;
	
	// adds banners into html
	this.show = function (data) {
		var topContainer, bottomContainer, banner, subElement, i, url, sidbInput;
		bannerData = data.banners; // data for all top banners
		globalData = data.global;  // data for the red "what's the deal" banner
		
		if (data.was_clicked && 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);
		}
		
		var rightBannerData = data['right-panel']; // data for right-panel banner
		var rightPanelBannerBox = getElementsByClassName(document, 'dvor-menu-box', 'div');
		
		if (rightPanelBannerBox.length > 0 && rightBannerData) {
			rightPanelBannerBox = rightPanelBannerBox[0];
			rightPanelBannerBox.className = 'dvor-right-panel-banner';
			rightPanelBannerBox.innerHTML = rightBannerData.html;
		}
		
		if (bannerData && bannerData.length > 0) {
			
			topContainer = document.createElement('div');
			topContainer.id = 'top-banners';
			
			bottomContainer = document.createElement('div');
			bottomContainer.id = 'bottom-banners';
			
			bottomContainer.style.zIndex = "300000";
			
		/////// making Red banner ///////////////////////////
			
			if (globalData) {
		
			///// Create banner header part (where to click) //////
				
				var toggleButton = 	createElementTree('div',{'class':'top-banner-arrow'},'');
				
				var topBannerTitle = createElementTree('div',{'class':'top-banner-header'},
		  			[  
						createElementTree('div',{'class':'top-banner-header-inner'}, ''),
					  	toggleButton
					]
				);			
				
				var topBannerInnerContainer =  createElementTree('div',{'class':'top-banner-inner-container'},
		  			[
						topBannerTitle,
						createElementTree('div',{'class':'info-clear'},'')
					]
				);
					
				var nextTopBannerContainer = createElementTree('div',{'class':'top-deal-banner top-banner-container'},
		  			[ createElementTree('div',{'class':'top-banner-upper-left'},''),
				 	  createElementTree('div',{'class':'top-banner-upper-right'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-left'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-right'},''),
					  topBannerInnerContainer			 
		  			]
		  		);

				nextTopBannerContainer.onclick = eventBannerExpandClick('top-deal-banner-popup');	 
				
				topContainer.appendChild(nextTopBannerContainer); 	
					
		
			///// Create banner content part (that shows up on click) //////

					
				var bottomBannerTitle = createElementTree('div',{'class':'top-banner-header'},
		  			[  
						createElementTree('div',{'id':'top-banner-arrow-ie6','class':'top-banner-arrow'}, ''),
					]
				);			
				
				var bottomBannerContent = createElementTree('div', {'id':'top-deal-popup-contents','class':'top-banner-contents'},'');  


				red_url = 'http://tracker.opticsplanet.com/banner/resolve.php?page=' + encodeURIComponent(window.location) + '&banner_id=' + globalData.id;

				var bannerDollars = '', bannerCents = '', priceString;
					 
				if (globalData.text) {
					priceString = globalData.text.split(".");
						
					if (priceString) {
			
						if (priceString.length > 0) bannerDollars = priceString[0];	
						if (priceString.length > 1) bannerCents = priceString[1]; 
					} 
				}

				var htmlArray = '<div class="top-deals-tab-selected" id="top-deals-day">  <a class="top-deals-tabs" href="#"></a> <div class="top-deals-tab-content"> <div class="top-deals-tab-content-inner">  <a id="top-deals-day-link" href="';
					htmlArray += red_url;
				 	htmlArray += '"><span id="top-deals-day-name">';
					htmlArray += globalData.title;
					htmlArray += '</span>  <img height="267" width="367" id="top-deals-day-image" alt="';
					htmlArray += globalData.title;
					htmlArray += '" src="http://images1.opticsplanet.com/367-267-ffffff/';
					htmlArray += globalData.image_id;
					htmlArray += '.jpg">  <span id="top-deals-day-price">  <span>$';
					htmlArray += bannerDollars;
					htmlArray += '<span>';
					htmlArray += bannerCents;
					htmlArray += '</span></span></span> </a></div></div></div>';
				
					htmlArray += '<div id="top-deals-week" class=""><a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content"><div class="top-deals-tab-content-inner"><a href="http://www.opticsplanet.net/dealoftheweek.html"><img height="418" width="418" alt="Deals of the Week" src="http://layout.opticsplanet.com/images/top-banners-week.jpg"></a></div>  </div></div><div id="top-gift-certificates" class="">  <a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content">  <div class="top-deals-tab-content-inner">  <img height="418" width="418" alt="OpticsPlanet Gift Certificates" src="http://layout.opticsplanet.com/images/top-banners-certificates.jpg"><a id="top-gift-certificates-10" href="http://www.opticsplanet.net/opgifcer.html"></a><a id="top-gift-certificates-25" href="http://www.opticsplanet.net/opticsplanet-gift-card-25.html"></a><a id="top-gift-certificates-50" href="http://www.opticsplanet.net/opticsplanet-gift-card-50.html"></a><a id="top-gift-certificates-100" href="http://www.opticsplanet.net/opticsplanet-gift-card-100.html"></a><a id="top-gift-certificates-150" href="http://www.opticsplanet.net/opticsplanet-com-email-gift-certificate-150.html"></a></div>  </div></div><div id="top-gift-guide" class="">  <a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content">  <div class="top-deals-tab-content-inner">  <img height="418" width="418" alt="Gift Guides" src="http://layout.opticsplanet.com/images/top-banners-guide.jpg"><a id="top-gift-guide-xmas" href="http://www.opticsplanet.net/christmas-gifts.html"></a><a id="top-gift-guide-stocking" href="http://www.opticsplanet.net/stocking-stuffers.html"></a><a id="top-gift-guide-30" href="http://www.opticsplanet.net/gifts-below30.html"></a><a id="top-gift-guide-link" href="http://www.opticsplanet.net/best-gifts.html"></a></div>  </div></div><div id="top-out-24">  <a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content">  <div class="top-deals-tab-content-inner">  <a href="http://www.opticsplanet.net/fast-ship.html">  <img height="418" width="418" alt="Out the Door in 24" src="http://layout.opticsplanet.com/images/top-banners-out-the-door.jpg"></a></div>  </div></div><div id="top-extended-return">  <a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content">  <div class="top-deals-tab-content-inner">  <a href="http://www.opticsplanet.net/return-policy.html">            <img height="418" width="418" alt="Extended Return Policy" src="http://layout.opticsplanet.com/images/top-banners-extended.jpg"></a></div>  </div></div><div id="top-deal-clearance">  <a class="top-deals-tabs" href="#"></a>  <div class="top-deals-tab-content">  <div class="top-deals-tab-content-inner">  <a href="http://www.opticsplanet.net/clearance.html">  <img height="418" width="418" alt="Clearance" src="http://layout.opticsplanet.com/images/top-banners-clearance.jpg"></a></div></div></div>'; 
					
	              
			    bottomBannerContent.innerHTML = htmlArray;  // add stuff
			
				var bottomBannerInnerContainer =  createElementTree('div',{'class':'top-banner-inner-container'},
		  			[
						bottomBannerTitle,
						bottomBannerContent,
						createElementTree('div',{'class':'info-clear'},'')
					]
				);
			
			  bottomBannerTitle.onclick = eventBannerCollapseClick(); 
			  bottomBannerContent.onclick = eventBannerBodyClick();
						
				var nextBottomBannerContainer = createElementTree('div',{'id':'top-deal-banner-popup', 'class':'top-deal-banner top-banner-container top-banner-container-dropdown'},
		  			[ 
					  bottomBannerInnerContainer			 
		  			]
		  		);
				
				nextBottomBannerContainer.style.top = "10px";
				nextBottomBannerContainer.style.zIndex = "310000";
				
				if (getIEVersion() > 0 && getIEVersion() < 8) nextBottomBannerContainer.style.minWidth = "700px";

				
				bottomContainer.appendChild(nextBottomBannerContainer); 	
		
				// adding click handlers to red banner tabs
				
				var toggleButtons = getElementsByClassName(nextBottomBannerContainer, 'top-deals-tabs', 'a');
				
				if (toggleButtons.length > 0) {
					for (var i = 0; i < toggleButtons.length; i++) {
						toggleButtons[i].onclick = tabClickHandler();
					}
				} 

			  } 
			  
		/////// making All Other banners ///////////////////////////
			for (i = 0; i < bannerData.length; i++) {
				
				if (bannerData[i].id == 976) {  //794 for testing  
					bannerData[i].type = 'free';
				} 
				
			///// Create banner header part (where to click) //////
				
				var toggleButton = 	createElementTree('div',{'class':'top-banner-arrow'},'');
				
				var topBannerTitle = createElementTree('div',{'class':'top-banner-header'},
		  			[  
						createElementTree('div',{'class':'top-banner-header-inner'}, [bannerData[i].title]),
					  	toggleButton
					]
				);			
				
				var topBannerInnerContainer =  createElementTree('div',{'class':'top-banner-inner-container'},
		  			[
						topBannerTitle,
						createElementTree('div',{'class':'info-clear'},'')
					]
				);
					
				var nextTopBannerContainer = createElementTree('div',{'class':'top-'+ bannerData[i].type +'-banner top-banner-container'},
		  			[ createElementTree('div',{'class':'top-banner-upper-left'},''),
				 	  createElementTree('div',{'class':'top-banner-upper-right'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-left'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-right'},''),
					  topBannerInnerContainer			 
		  			]
		  		);

				
			if (bannerData[i].id == 976) {//794 for testing

				nextTopBannerContainer.onclick = eventFreeBannerClick();		
			
			}
			else	
				nextTopBannerContainer.onclick = eventBannerExpandClick(bannerData[i].id);				
				
				topContainer.appendChild(nextTopBannerContainer); 		
			
				
			///// Create banner content part (that shows up on click) //////
				
				url = 'http://tracker.opticsplanet.com/banner/resolve.php?page=' + encodeURIComponent(window.location) + '&banner_id=' + bannerData[i].id;
				imageUrl = 'http://images' + (i % 2 + 1) + '.opticsplanet.com/' + imgWidth + '-' + imgHeight + '-ffffff/' + bannerData[i].image_id + '.gif';				
				
				var textHTMLData = createElementTree('span',{'class':'top-banner-text'}, '');
					 textHTMLData.innerHTML = bannerData[i].text;
				
				if (bannerData[i].image_id) {
				
					var imageLink = createElementTree('a', {
							'href': url
						}, [ 
							createElementTree('img', {
									'src': imageUrl,
									'width': imgWidth,
									'height': imgHeight,
									'alt': bannerData[i].title
									}, ''), 
							
							textHTMLData]);
					
				} else {
					
					var imageLink = createElementTree('a', {
							'href': url
						}, [ textHTMLData ]);
				}
				
				var bottomBannerUL =  createElementTree('UL', {'class':''},[
					createElementTree('LI', {'class':''}, [imageLink])
				    ]);
				
					
				var bottomBannerContent = createElementTree('div', {'class':'top-banner-contents'},
					[		
				  		bottomBannerUL,
					    createElementTree('div',{'class':'top-banner-lower-left'},''),
						createElementTree('div',{'class':'top-banner-lower-right'},'')	
					]	 
				);  
					
				
				
				var bottomToggleButton = createElementTree('div',{'class':'top-banner-arrow'},'');
					
				
				var bottomBannerTitle = createElementTree('div',{'class':'top-banner-header'},
		  			[  
						createElementTree('div',{'class':'top-banner-header-inner'}, [bannerData[i].title]),
					  	bottomToggleButton
					]
					
				);
						
				
				var bottomBannerInnerContainer =  createElementTree('div',{'class':'top-banner-inner-container'},
		  			[
						bottomBannerTitle,
						bottomBannerContent,
						createElementTree('div',{'class':'info-clear'},'')
					]
				);
				
				bottomBannerTitle.onclick = eventBannerCollapseClick();
				bottomBannerContent.onclick = eventBannerBodyClick();
						
				var nextBottomBannerContainer = createElementTree('div',{'id':'banner-'+bannerData[i].id, 'class':'top-'+ bannerData[i].type +'-banner top-banner-container top-banner-container-dropdown'},
		  			[ createElementTree('div',{'class':'top-banner-upper-left'},''),
				 	  createElementTree('div',{'class':'top-banner-upper-right'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-left'},''),
				 	  createElementTree('div',{'class':'top-banner-lower-right'},''),
					  bottomBannerInnerContainer			 
		  			]
		  		);
				
				bottomContainer.appendChild(nextBottomBannerContainer); 		
			
			
			} // for
			
			
			topContainer.appendChild(createElementTree('div',{'class':'info-clear'},'')); 	
			bottomContainer.appendChild(createElementTree('div',{'class':'info-clear'},''));
			insertBeforeObject.parentNode.insertBefore(topContainer, insertBeforeObject);
			insertBeforeObject.parentNode.insertBefore(bottomContainer, insertBeforeObject);
		}
		
	};
	
	eventFreeBannerClick= function (){
			return function(){
				
			var BundlesTable = document.getElementById('bundles-table');	
				
			var BundlesDropdown = document.getElementById('bundle-arrow-more');	
				
			if (!BundlesDropdown)  BundlesDropdown = document.getElementById('bundle-arrow-less');
			
			if (BundlesTable) {	

				var hiddenRows = BundlesTable.getElementsByTagName('tr'); 

			for (i = 1; i < hiddenRows.length; i++) {
                hiddenRow = hiddenRows[i];
                if (hiddenRow.className == 'top-nav-hidden') hiddenRow.className = '';
				// else  hiddenRow.className = 'top-nav-hidden';
            }
            //hiddenBundlePrice.innerHTML = (hiddenBundlePrice.innerHTML === '') ? 'Total' : '';

            if (BundlesDropdown.id == 'bundle-arrow-more') BundlesDropdown.id = 'bundle-arrow-less';
			 //else BundlesDropdown.id ='bundle-arrow-more';
			
			scrollDistance = BundlesTable.offsetTop;
			
			window.scroll(0,scrollDistance - 20);
			
			}
				
		}	
	};
						
	
	 eventBannersBlur = function (){
			return function(){
				
				if (!innerClick) {
					if (document.all) {
						document.body.detachEvent('onclick', docClick)
					}
					else {
						document.body.removeEventListener('click', docClick, false);
					}
					
					var bottomBannerListContainer = document.getElementById('bottom-banners');
					
					var bottomBannersList = bottomBannerListContainer.getElementsByTagName('div');
					
					for (i = 0; i < bottomBannersList.length; i++) {
					
						bottomBannersList[i].className = bottomBannersList[i].className.replace(' showup', '');
						
					}
					
				}
				innerClick = false;
			}	
	};
			
	
	
	eventBannerExpandClick = function (id){
			return function(){
				
					// collapse first			
					innerClick = true;
				
				    if (document.all) {
						document.body.detachEvent('onclick', docClick)
					}
					else {
						document.body.removeEventListener('click', docClick, false);
					}
					
					var bottomBannerListContainer = document.getElementById('bottom-banners'),
					topBannerListContainer = document.getElementById('top-banners');
					
					bottomBannerListContainer.style.top = (topBannerListContainer.offsetTop - 5) + "px";
					
					var bottomBannersList = bottomBannerListContainer.getElementsByTagName('div');
					
					for (i = 0; i < bottomBannersList.length; i++) {
					
						bottomBannersList[i].className = bottomBannersList[i].className.replace(' showup', '');
						
					}

					// then expand	
					innerClick = true;
					
					if (id == 'top-deal-banner-popup') {
						bottomBanner = document.getElementById(id); // red banner
					}
					else 
						bottomBanner = document.getElementById('banner-' + id);
					
					topBanner = this;
							
					bottomBanner.style.left = (topBanner.offsetLeft - 0) + "px";

					bottomBanner.className += ' showup';	

					if (topBanner.offsetLeft + bottomBanner.offsetWidth > document.body.offsetWidth) {
						//fix oversize
						
						bottomBanner.style.left = (document.body.offsetWidth - bottomBanner.offsetWidth - 20)+ "px";
						
					}

					
					
					if (document.all) {
						document.body.attachEvent('onclick', docClick);
						window.attachEvent('onresize', docClick);
					}
					else {
						document.body.addEventListener('click', docClick, false);
						window.addEventListener('resize', docClick, false);
					}
			}	
		};
		
		
	var eventBannerBodyClick = function (){
		return function(){
	
				innerClick = true;
		}	
	};		


	var eventBannerCollapseClick = function (){
			return function(){
		
					innerClick = true;
				
					if (document.all) {
						document.body.detachEvent('onclick', docClick);
						window.detachEvent('onresize', docClick);
						
					}
					else {
						document.body.removeEventListener('click', docClick, false);
						window.removeEventListener('resize', docClick, false);
					}
					
					var bottomBannerListContainer = document.getElementById('bottom-banners');
					
					var bottomBannersList = bottomBannerListContainer.getElementsByTagName('div');
					
					for (i = 0; i < bottomBannersList.length; i++) {
					
						bottomBannersList[i].className = bottomBannersList[i].className.replace(' showup', '');
						
					}
			
			}	
		};	

        // red banner tabs click handler
		tabClickHandler = function () {
			return function(){
			
			var obj, currentTabs;
				// cleanup current tab 'top-deals-tab-selected'
				
				obj = this.parentNode.parentNode;
				
				currentTabs = getElementsByClassName(obj, 'top-deals-tab-selected', 'div');
				
				if (currentTabs.length > 0) {
					for (var j = 0; j <= currentTabs.length-1; j++) {
						currentTabs[j].className = '';
					}
				}	
					
				this.parentNode.className = 'top-deals-tab-selected';
			return false;	
			}
		};


		// we'll use this for capturing clicks outside of the banner
		docClick = eventBannersBlur();
	
	// 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');
	}
	
	
	
}

/// false tabs for Trade-in program (trade-in-for-a-cause-program.html) (D. Naumov)
function startTradeinProgramTabs() {

	var activeTabId,

	setFalseTabs = function ( ) {
	
		var falseTabs = getElementsByClassName(document, 'collapsible-item', 'div'), 
		falseTabBlock = document.getElementById('false-tabs'); 

		if (falseTabBlock) falseTabLinks = falseTabBlock.getElementsByTagName('a');
		
		function initTabs ( ) {
			
			for (i = 0; i < falseTabs.length; i += 1) {
			
				currentTab = falseTabs[i];
				
				if (currentTab.id != activeTabId) 
					currentTab.style.display = 'none';
				else 
					currentTab.style.display = 'block';
			}
		};
		
		// onClick event
		onFalseTabClick = function ( ) {   
			return function ( ) {
				
				for (i = 0; i < falseTabLinks.length; i += 1) {
				
					currentLink = falseTabLinks[i];
					currentLink.style.color = '#2665AD';
				}
				
				this.style.color = '#37A100';
				activeTabId = this.href.slice(this.href.search('#') + 1, this.href.length);
				
				initTabs();
				
				return false;
			}
		};
		
		
		// constructor
		activeTabId = 'intro';
		if (falseTabLinks && falseTabLinks[0]) falseTabLinks[0].style.color = '#37A100';
		initTabs();
		
		// set onClick event
		for (i = 0; i < falseTabLinks.length; i += 1) {
			if (falseTabLinks[i]) {
				falseTabLinks[i].onclick = onFalseTabClick();
			}
		}
		
	};
	
// main constructor	
falseTabs = new setFalseTabs ( );
	
};	


/// Shop & Save dropdown menu for the left panel (D. Naumov)
function startShopAndSaveMenu(){
	var shopSmarterMainContainer = document.getElementById('left-panel-shop-smarter'), 
		shopSmarterInnerContainer = document.getElementById('left-panel-shop-smarter-inner'),
		currentURL = document.URL,
		shopSmarterLinks,
		shopSmarterLinksUL,
		flagDocumentURrlMAtches,
		shopSmarterULObject;

	currentURL = currentURL.replace('http://', '').replace('https://', '').replace('www.opticsplanet.com/', '').replace('www.opticsplanet.net/', '').replace('staging/', '').replace(' ', '');
	
	var objRegExp = currentURL+'$';
	
	if (shopSmarterMainContainer) {
		shopSmarterLinks = shopSmarterMainContainer.getElementsByTagName('a');
		shopSmarterLinksUL = shopSmarterMainContainer.getElementsByTagName('ul');
	}
	
	if (shopSmarterLinksUL) {
	 	 if (shopSmarterLinksUL.length > 0) shopSmarterULObject = shopSmarterLinksUL[0];
	 }
		
	if (shopSmarterLinks && currentURL != '') {
		for (i = 0; i < shopSmarterLinks.length; i += 1) {
		
			currentLink = shopSmarterLinks[i];
	
			// check if one of links matches current URL (expand menu if this is true) 
			if (currentLink.href.match(objRegExp)) { 
			
				shopSmarterMainContainer.className = 'left-panel-shop-smarter-dropdown';

				currentLink.href = '';
				currentLink.className = 'left-panel-shop-smarter-selected';
				
				flagDocumentURrlMAtches = 1;
			}
		}
	}
	
	// onClick event
		onShopAndSaveClick = function ( ) {   
			return function ( ) {
			
			if (shopSmarterULObject.style.display != 'block') {
					shopSmarterULObject.style.display = 'block';
				return true;
			}
			
			if (shopSmarterULObject.style.display != 'none') {
					shopSmarterULObject.style.display = 'none';
				return true;		
			} 
				
				return true;
			}
		};
	
		// onMouseOver event
		onShopAndSaveMouseOver = function ( ) {   
			return function ( ) {

				if (shopSmarterULObject.style.display != 'block') {
					 shopSmarterULObject.style.display = 'block';
				} 
				return true;
			}
		};
		
	// onMouseOut event
		onShopAndSaveMouseOut = function ( ) {   
			return function ( ) {
				
				if (shopSmarterULObject.style.display != 'none') {
					shopSmarterULObject.style.display = 'none';
				}
				return true;
			}
		};		
			
	// set poiner events	
	if (!flagDocumentURrlMAtches) {
		
		if (shopSmarterInnerContainer) shopSmarterInnerContainer.onclick = onShopAndSaveClick();
		
		if (shopSmarterMainContainer) {
			shopSmarterMainContainer.onmouseover = onShopAndSaveMouseOver();
			shopSmarterMainContainer.onmouseout = onShopAndSaveMouseOut();
		}
	}
		
};
	

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));
		}
	}
}

// collapsible multiple breadcrumbs (V. Nguyen)
function breadcrumbsHider(){	
	var i,
	container = document.getElementById('breadcrumbs-float'),
	toggleButton, div, clearFloat
	buttonClick = function (){
		return function () {
			if (!container.className.match(/show-breadcrumbs/)) {
				container.className += 'show-breadcrumbs';
			} else {
				container.className = container.className.replace('show-breadcrumbs', '');
			}
			this.onselectstart = function (){
				return false;
			};
			return false;
		};
	};
	if (container){
			div = container.getElementsByTagName('div');
			if (div.length > 1){
				for ( i = 1 ; i < div.length ; i++ ){
					div[i].className += ' hidable-breadcrumb';
				}
				container.className += 'breadcrumbs-with-js show-breadcrumbs';
				if(oldIE){
					toggleButton = createEl('a', {'id': 'breadcrumbs-arrow'}, container);
				} else {
					toggleButton = createEl('span', {'id': 'breadcrumbs-arrow'}, container);
				}
				toggleButton.onclick = buttonClick();
			}
	}
}

function printLinkForProducts () {
	var printLink = document.getElementById('headblock-print-icon');
	if(printLink){
		printLink.onclick = function (){
			window.print();
			return false;
		};
	}
}

function enableLikeButtons() {

	var fblikeContainer = document.getElementById('headblock-fblike'), 
		leftFacebookBlockContainer = document.getElementById('left-panel-facebook-button'), 
		fbRoot = document.getElementById('fb-root');
	
	if (fblikeContainer) {
		fblikeContainer.style.display = 'none';
	}
	
	if (leftFacebookBlockContainer) {
		leftFacebookBlockContainer.style.display = 'none';
	}
	
	if(fbRoot && ( fblikeContainer || leftFacebookBlockContainer)) {
		addScriptToHead('http://graph.facebook.com/test?callback=enableFacebookButtons', '', 'js');
	}
	
}

function enableFacebookButtons (val) {

	var fblikeContainer = document.getElementById('headblock-fblike'),
	 	leftFacebookBlockContainer = document.getElementById('left-panel-facebook-button');
	
	if (fblikeContainer) {
		fblikeContainer.style.display = 'block';
	}
	
	if (leftFacebookBlockContainer) {
		leftFacebookBlockContainer.style.display = 'block';	
	}
}

// displays facebook comment counter
facebookCommentsCount.display = function(data){
	var headblockCommentBox = $('<div id="headblock-social-comments" class="headblock-social-block-items"></div>');
	if ($('div#main-panel').is('.hproduct')){
		$('div#ys_relatedItems').after('<a name="fb-comments-box"></a>');
		$('div#headblock-fblike').after(headblockCommentBox)
		
		if (data[0].fql_result_set[0].commentsbox_count == 1){
			$(headblockCommentBox).append(Math.floor(data[0].fql_result_set[0].commentsbox_count) + ' social comment <span class="fb-comments-box">add a comment</span>');
		} else if (data[0].fql_result_set[0].commentsbox_count > 1){
			$(headblockCommentBox).append(Math.floor(data[0].fql_result_set[0].commentsbox_count) + ' social comment <span class="fb-comments-box">add a comment</span>');
		} else {
			$(headblockCommentBox).append('no social comments yet. <span class="fb-comments-box">add a comment</span>');
		}
		$('#headblock-social-comments span.fb-comments-box').click(function() {
			var target = $('a[name=fb-comments-box]').offset().top;
			$('html,body').animate({scrollTop: target}, 500, 'swing');
			
			return false;
		});
	}
}

facebookCommentsCount.loader = function(){
	addScriptToHead('http://api-read.facebook.com/restserver.php?api_key=169881939742690&callback=facebookCommentsCount.display&format=json-strings&method=fql.multiquery&pretty=1&queries={%22index_link_stat_url%22%3A%22select%20commentsbox_count%20from%20link_stat%20where%20url%3D%5C%22' + encodeURIComponent(location.href) + '%5C%22%22}', '' , 'js');

}

function godsLoveCookies(){
	var godsCookie = new Cookie("OpticsPlanetGodsLoveCookies");
	
	if(document.location.hash == "#godMode=on"){
		godsCookie.setValue("crumbles", 7 * 24); 
	} else if(document.location.hash == "#godMode=off"){
		godsCookie.remove();
	}
	
	godsCookie = (godsCookie.getValue() == "crumbles");
	
	if(godsCookie){
		console.log("The God Mode is ON!!!");
	}
	
	return godsCookie;
}

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
	
	// new features are released for gods first
	godMode = godsLoveCookies();
	
	// facebook love
	var fbLove = document.location.href.replace(/[?&]?fb_xd_fragment=?[^&]*/,'');
	if (document.location.href != fbLove){
		document.location.href = fbLove;
	}
	
	oldIE = (window.external && typeof window.XMLHttpRequest === 'undefined');
	if (oldIE) {
		window.setTimeout('IE6MinWidthFix();', 0); // css expressions are uncool but we need min-width in IE6
	}
	
	// init Async GA
	window.setTimeout('googleAnalyticsAsync();', 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);
	}
	
	// turn those special spans into links
	window.setTimeout('spansToLinks();', 0);
	
	// clean hash from GA
	//window.setTimeout('googleAnalyticsCleanHash();', 0);
	
	// fix fuckups
	//initPriceAdjust();
	//initDisableAddToCart();
	
	// checks if newsletter data is in url and adds cookie
	window.setTimeout('newsletterData();', 0);
	
	// Top nav drop down
	window.setTimeout('DropTop();', 0);

	// init collapsible multiple breadcrumbs (V. Nguyen)
	window.setTimeout('breadcrumbsHider();', 0);
	
	// start header banner loader
	window.setTimeout("headerBanners = new multitypeBanners('headerBanners', 'header', 80, 80)", 0);

	// 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);
		}
	}
	
	// init facebook comment counter
	window.setTimeout('facebookCommentsCount.loader();', 0);
	
	// setup bundles expand and collapse
	window.setTimeout('Bundles();', 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 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);
	
	// filter out bundle items from yahoo related items
	window.setTimeout('filterRelatedItems()', 0);
	
	// if pagination is there, copy it to the bottom
	window.setTimeout('copyPagination();', 0);	
	
	// print link
	window.setTimeout('printLinkForProducts();', 0);
	
	/// Shop & Save dropdown menu for the left panel (D. Naumov)
	window.setTimeout('startShopAndSaveMenu();', 0);
	
	// show Facebook and Twitter "like"-buttons if these sites are not blocked (D. Naumov)
	window.setTimeout('enableLikeButtons();', 0);

	// init recently viewed
	window.setTimeout('History();', 0);

	// google plus code
	(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();
}
