// identify mobile browsers
(function(a){$.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|i(phone|pad|pod)|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

var oldIE = false, jsonVoorhees = [], searchBoxHelp, headerBanners, facebookCommentsCount = {}, _gaq = _gaq || [], godMode = false, 
	tabPriority = 0, tabPriorityCookie = new Cookie("__op_tab");

// load js that has never caches in user's browser
$.getScript('http://layout.opticsplanet.com/data/instant.r44.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 createEl(elType, elExtras, elParent) {
	var attribute,
	el = document.createElement(elType);
	for (attribute in elExtras) {
		if (elExtras[attribute] !== '') {
			if (attribute === 'class') {
				el.setAttribute('className', elExtras[attribute]);
			}
			el.setAttribute(attribute, elExtras[attribute]);
		}
	}
	if (elParent) {
		elParent.appendChild(el);
	}
	return el;
}

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

// at this point we need to know if we are using the "god mode"
godMode = godsLoveCookies();

// Let GA run first so we get better tracking
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 currentRootDomain = document.location.host.match(/opticsplanet\.(?:com|net)/),
		searchString = document.location.href.match(/opticsplanet.com\/s\/([^\/]+)/),
		oldCookieTail = "",
		oldCookies = "",
		goodCookiePat = /^_(_utm[^_]+|opnld|_op_tab)$/;
		
	currentRootDomain = currentRootDomain ? '.' + currentRootDomain[0] : 'none';

	// give this tab an ID so when cookies are updated in this tab we can make sure it does not interfere with other tabs
	if(currentRootDomain != 'none'){
		tabPriority = (parseInt(tabPriorityCookie.getValue()) || tabPriority) + 1;
		document.cookie = '__op_tab=' + tabPriority + "; path=/; domain=" + currentRootDomain;
	}
	
//	_gaq.push(['gwo._setAccount', 'UA-138028-20']);
//	_gaq.push(['gwo._setDomainName', currentRootDomain]);
//	_gaq.push(['gwo._setAllowLinker', true]);
//	_gaq.push(['gwo._setAllowAnchor', true]);
//	_gaq.push(['gwo._trackPageview', '/0500763016/test']);	
	
	_gaq.push(['_setAccount', 'UA-138028-1']);
	_gaq.push(['_setDomainName', currentRootDomain]);
	_gaq.push(['_setAllowLinker', true]);
	_gaq.push(['_setAllowAnchor', true]);
	
	// we will no longer track searches in the message board in favor of increased GA performance
	if(searchString) { // 3 unescapes are no fuckup
		_gaq.push(['_trackPageview', '/s/?query=' + encodeURIComponent(unescape(unescape(unescape(searchString[1]))).replace(/\+/g," ").replace(/(^\s|\s$)/g,'')).replace(/%20/g,'+')]);
	} else {
		_gaq.push(['_trackPageview']);
	}	
	
	// 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 (){
			
		if (oldCookies != document.cookie) {
			
			oldCookies = document.cookie;
			
			if(tabPriority < tabPriorityCookie.getValue()){
				window.clearInterval(cookieBrdigeInterval);
				return;
			}
				
			var mixedCookies = document.cookie.split(";");
			var tastyCookies = [];
			
			for ( i = 0; i < mixedCookies.length ; i++ ){
				mixedCookies[i] = trim(mixedCookies[i]);				
				if(goodCookiePat.test(mixedCookies[i].split('=')[0])){
					tastyCookies.push(mixedCookies[i]);
				}
			}
			
			var cookieTail = "#" + encodeURIComponent(tastyCookies.join(";"));
			
			if (oldCookieTail !== cookieTail){
				oldCookieTail = cookieTail;
				
				try {
					if(!document.location.host.match(/opticsplanet\.com/)){
						createEl('iframe',{'class' : 'js-communication-iframe', 'src': 'http://cookiebridge.opticsplanet.com/' + cookieTail},document.body);
					}
					
					if(!document.location.host.match(/opticsplanet\.net/)){
						createEl('iframe',{'class' : 'js-communication-iframe', 'src': 'http://cookiebridge.opticsplanet.net/' + cookieTail},document.body);
					}
					
					if(!document.location.host.match(/\.store\.yahoo\.net/)){
						createEl('iframe',{'class' : 'js-communication-iframe', 'src': 'http://search.store.yahoo.net/opticsplanet/cgi-bin/nsearch?catalog=opticsplanet' + cookieTail},document.body);
					}
					
				} catch (e) {
					// oldCookieTail = ""; // potentially dangerous as we could end up in an endless loop
				}
			}
		}
	};
	
	var cookieBrdigeInterval = window.setInterval(cookieBridge,250);
	
	$(function () { // start cookie bridge as soon as the document loads
		if ($(".js-communication-iframe").length < 2){
			oldCookieTail = ""; // this will trigger the cookie bridge to try to copy cookies again
		}
	});
}

// init Async GA NOW!
window.setTimeout('googleAnalyticsAsync();', 0);


function headerDropDown(selector, noHover){
	$(selector).each(function () {
		var that = $(this),
			dropDownButton = that.find('span.header-fancy-dropdown-button'),
			dropDown = that.find('div.fancy-select-box-outer'),
			mouseIsIn = false,
			timer = null,
			activeDropDown = null,
			finishedSlideDown = false, // checks to see if slideDown animation is done before closing it
			
			openTheDropDown = function(force){
				timer = null;
				activeDropDown = dropDown;
				
				$('#header-container div.fancy-select-box-outer').not(activeDropDown).slideUp(120);
				
				if (!dropDown.is(':visible') && (mouseIsIn || force)){
					that.addClass('header-fancy-dropdown-hover-styles');
					dropDown.slideDown(120, function(){
						finishedSlideDown = true;
						return false;
					});
				}
			},
			
			closeTheDropDown = function(force){
				timer = null;
				if (dropDown.is(':visible') && (!mouseIsIn || force)){
					if(finishedSlideDown){
						dropDown.slideUp(120, function(){
							that.removeClass('header-fancy-dropdown-hover-styles');
							finishedSlideDown = false;
						});
					}
				}
			}, 
			resetTimer = function(callback) {
				if(timer){
					window.clearTimeout(timer);
				}
				timer = window.setTimeout(callback, 400);
			};

		dropDown.hide().removeClass('header-fancy-dropdown-css-hover'); // hide the dropdown so CSS hover effect wont be triggered
		
		if(!noHover){
			that.mouseenter(function(){
				mouseIsIn = true;
				resetTimer(openTheDropDown);
			}).mouseleave(function(){
				mouseIsIn = false;
				resetTimer(closeTheDropDown);
			});
		}

		$(document).not(that).click(function () { // Hides dropdowns when its not in focus
			dropDown.not(activeDropDown).slideUp(120);
			activeDropDown = null;
			//return false;
		});
		
		dropDownButton.click(function(){ 	// Trigger the mouseover/mouseout effects when clicked
			if (dropDown.is(':visible')){
				closeTheDropDown(true);
			} else {
				openTheDropDown(true);
			}
		});
	});
}

// start all header drop downs
$(function () {
	headerDropDown('div.header-fancy-dropdown-js-hover');
	headerDropDown('div.header-fancy-dropdown-js-click',true);
	fancySelect('div#header-search-type');
});


// instant banners
$(function () {
	// disable old instant banners
	if(typeof multitypeBanners == 'function') multitypeBanners = function () {};

	var headerBanner = function (banners) {
		var banner =  $('#header-promo-banner'),
			interval = null,
			current = 0,
			elements = {
				icon  : $('#header-promo-banner-type'),
				title : $('#header-promo-banner-text'),
				image : $('#header-promo-banner img'),
				text  : $('#header-promo-banner span.header-promo-banner-details'),
				link  : $('#header-promo-banner a'),
				nav	  : $('#header-promo-banner-nav-text'),
				left  : $('#header-promo-banner-nav-left'),
				right : $('#header-promo-banner-nav-right')
			},
			fade = elements.icon.add(elements.title).add(banner.find('div.fancy-select-box>div')),
		
		run = function () {
			if(interval !== null){
				pause ();
			}
			interval = window.setInterval(function () { advance(1); }, 8000);
		},
		pause = function () {
			if(interval !== null){
				window.clearInterval(interval);
				interval = null;
			}
		},
		advance = function (dir) {
			var crap = '' + interval + ' ' + dir + ' ' + current + ' ';
			current = ((current + dir) % banners.length + banners.length) % banners.length; 
					
			elements.nav.html((current + 1) + '/' + banners.length); 
					
			fade.stop().fadeTo(400, 0.01, function () {
			
				elements.icon.removeClass().addClass('header-promo-banner-' + banners[current].type);
				elements.title.html(banners[current].title);
				if(banners[current].image_id){
					elements.image.show();
					elements.image.attr('src', 'http://images1.opticsplanet.com/80-80-ffffff/' + banners[current].image_id + '.jpg');
				} else {
					elements.image.hide();
				}
				elements.text.html(banners[current].text.replace(/\<br\s*\>/gi,' ')).append(elements.link);
				elements.link.html('Visit').attr('href', 'http://tracker.opticsplanet.com/banner/resolve.php?page=' + encodeURIComponent(document.location.href) + '&banner_id=' + banners[current].id);
				
				fade.stop().fadeTo(400, 1);
			});
		};
			
		elements.left.click(function () { advance(-1); return false; });
		elements.right.click(function () { advance(1); return false; });
		
		banner.mouseenter(pause);
		banner.mouseleave(run);
		
		fade.fadeTo(1, 0.01);
		banner.show();
		advance(0);
		run();
	};

	// init 
	$.ajax({
		url:'http://tracker.opticsplanet.com/banner/serve.php',
		dataType: 'jsonp',
		data : {
			placement : 'header',
			page : document.location.href
		},
		success: function (data){
			if(data.banners && data.banners.length > 0){
				headerBanner(data.banners);
			}
				
			// add right panel banner if needed
			if(data['right-panel']){
				$('div.dvor-menu-box').first().removeClass('dvor-menu-box').addClass('dvor-right-panel-banner').html(data['right-panel'].html)
			}
			
			// banner tracking for old product options
			if (data['was_clicked']) {
				$('#addToCartForm').append('<input type="hidden" name="OPSIDB" id="op-sidb" value="' + data.bsid + '">');
			}
		}
	});
});

// header search
$(function (){
	var searchTypeSelect = $('#header-search-select'),
		form = searchTypeSelect.parents('form'),
		query = form.find('input[type="text"]'),
		types = {
			info : {
				url : 'http://www.opticsplanet.com/s/search.php',
				regex : /realm~info/,
				query : 'query',
				data : { realm : 'info' },
				run : function () {
					types.products.run();
				}
			},
			forum : {
				url : 'http://www.opticsplanet.com/msgboard/search.php',
				regex : /opticsplanet\.com\/msgboard/,
				query : 'keywords',
				data : {},
				run : function () {
					var oldSearchBox = $('#search_keywords');
					if(oldSearchBox.length > 0){
						query.val(oldSearchBox.val());
						oldSearchBox.parents('form').parents('div.search-box').hide();
					}					
				}
			},
			blog : {
				url : 'http://blog.opticsplanet.com/search',
				regex : /blog\.opticsplanet\.com/,
				query : 'q',
				data : {},
				run : function () {
					
				}
			},
			products : { // default case
				url : 'http://www.opticsplanet.com/s/search.php',
				regex : /.*/,
				query : 'query',
				data : {},
				run : function () {
					var oldSearchBox = $('#smarty-search-page-text');
					if(oldSearchBox.length > 0){
						query.val(oldSearchBox.val());
						oldSearchBox.parents('form').hide().prev().hide();
					}
				}
			}
		};
		
	// update search form to do the correct search if drop down selection changes
	searchTypeSelect.change(function () {
		var t = searchTypeSelect.val();
		
		form.find('input[type="hidden"]').remove();
		
		form.attr('action', types[t].url);
		query.attr('name', types[t].query);
		
		for(d in types[t].data){
			form.append('<input type="hidden" name="' + d + '" value="' + types[t].data[d] + '">');
		}
	});
	
	// remove garabage that is not needed in the search query before the form is submitted
	form.submit(function () {
		searchTypeSelect.remove();
		return true;
	});
	
	// set the drop down to current search type on page load	
	for (t in types) {
		if(window.location.href.match(types[t].regex)){
			searchTypeSelect.find('option:[value="' + t + '"]').attr('selected', 'selected').parent().change();
			types[t].run();
			break;
		}
	}

});


function googleAnalyticsAsyncExtras(){ // wait for the page to load before running this part
	// 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]);
	}
}


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

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

// 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 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 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');
		
		if (!$(text).parent().is($('#header-search-input-container'))){
			text.onfocus = eventFocusBlur();
			text.onblur = eventFocusBlur();
			
			if (text.value === '') {
				text.className = 'empty';
				text.value = 'Search';
			}
		}
		if (help) {
			text.onkeyup = eventKeyUp();
//			text.onchange = 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 = 'search-suggestion-box';
			theList.className = 'top-nav-hidden';
			theList.style.minWidth = container.offsetWidth - 3 + 'px';
			container.appendChild(theList);		
			$(window).resize(function() {
				theList.style.minWidth = container.offsetWidth - 3 + 'px';
			});
		}
	}
}

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 = 0; //scrollMain.offsetWidth < 412) ? 0 : (scrollMain.offsetWidth - 414 - 190) / 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);
	}
}

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

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'), 
		rightPanelFbContainer = document.getElementById('right-panel-fb'),
		bAContainer = document.getElementById('brilliance-awards-2011-container'),
		brillianceAwardsFbContainer = $('div#brilliance-awards-2011-container div.brilliance-awards-2011-grid-fb'),
		fbRoot = document.getElementById('fb-root');
	
	if (fblikeContainer) {
		fblikeContainer.style.display = 'none';
	}
	
	if (leftFacebookBlockContainer) {
		leftFacebookBlockContainer.style.display = 'none';
	}
	
	if(rightPanelFbContainer){
		rightPanelFbContainer.style.display = 'none';
		rightPanelFbContainer.parentNode.className = 'social-media-menu-box-nofb';
	}
	
	// Facebook like buttons on Brilliance Award 2011 page
	if(bAContainer){
		$('#brilliance-awards-2011-fb').css('display','none');
		brillianceAwardsFbContainer.css('display','none');
		$('#brilliance-awards-no-fb-access').css('display','block');
	}
	
	if(fbRoot && ( fblikeContainer || leftFacebookBlockContainer || rightPanelFbContainer || bAContainer)) {
		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'),
		rightPanelFbContainer = document.getElementById('right-panel-fb'),
		bAContainer = document.getElementById('brilliance-awards-2011-container'),
		brillianceAwardsFbContainer = $('div#brilliance-awards-2011-container div.brilliance-awards-2011-grid-fb');
	
	if (fblikeContainer) {
		fblikeContainer.style.display = 'block';
	}
	
	if (leftFacebookBlockContainer) {
		leftFacebookBlockContainer.style.display = 'block';	
	}
	
	if(rightPanelFbContainer){
		rightPanelFbContainer.style.display = 'block';
		rightPanelFbContainer.parentNode.className = '';
	}
	
	// Facebook like buttons on Brilliance Award 2011 page
	if(bAContainer){
		$('#brilliance-awards-2011-fb').css('display','block');
		brillianceAwardsFbContainer.css('display','block');
		$('#brilliance-awards-no-fb-access').css('display','none');
	}
}

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

// back to top button
function scrollableTopLink(){
	var scrollToTop = function(){
			if ($(window).scrollTop() == 0){
				$('#back-to-top-button:visible').fadeOut();
			} else {
				$('#back-to-top-button:hidden').fadeIn().unbind('click').bind('click',function(){
					$('html,body').animate({scrollTop: 0}, 400, 'swing');
				});
			}
		}
	$('#feedback-popup-window').after($('<span id="back-to-top-button"></span>'));
	scrollToTop();
	$(window).scroll(scrollToTop);
};


// fancy select that works well on mobile and desktop browsers
function fancySelect (selector) {
	var activeBox = null;
	$(selector).each(function () {
		var container = $(this),
			maxLen = 0,
			valueBox = $('<div class="fancy-select-select"><div class="fancy-select-fade"></div></div>'),
			oldSelect = container.find('select'),
			box = null;
			
		container.find('option').each(function () {
			maxLen = Math.max(maxLen, $(this).text().length);
		});
		
		valueBox.prepend($('<span class="fancy-select-value"></span>')
			.html(oldSelect.find('option:eq(0)').text())); // set default text
		
		valueBox.css('width', Math.max(80, Math.min(160, maxLen * 6 + 27)) + 'px');
		
		container.append(valueBox);
		
		// value changed - update visual stuff
		oldSelect.change(function () {
			var that = $(this);
			container.find('span').text(that.find('option:selected').text());
			if(box){
				box.find('div.selected').removeClass('selected');
				box.find('div.fancy-select-box div').eq(that.find('option').index(that.find('option:selected'))).addClass('selected');
			}
			return false;
		});
		
		if($.browser.mobile){
			
			// use native select on mobile devices
			oldSelect.css({
				'position'	: 'absolute',
				'margin'	: '0',
				'top'		: '20px',
				'left'		: '5px',
				'height'	: valueBox.outerHeight() + 'px',
				'width'		: valueBox.outerWidth() + 'px',
				'min-width'	: valueBox.outerWidth() + 'px',
				'max-width'	: valueBox.outerWidth() + 'px',
				'z-index'	: '100000',
				'opacity'	: '0'
			});
			
		} else {
			
			// use fancy JS select with regular brwsers
			oldSelect.hide();
			 
			valueBox.click(function (e) {
				var that = $(this), val;
						
				// first click, gotta generate the popup box
				if(!box){
					box = $('<div class="fancy-select-box"></div>');
					val = that.parent().find('select').val();
					
					// generate options
					that.parent().find('option').each(function (i, e) {
						var option = $('<div><span></span>' + $(this).text() + '</div>');
						if($(this).val() == 0){
							option.addClass('default');
						}
						if($(this).val() == val){
							option.addClass('selected');
						}
						
						// option clicked
						option.click(function () {
							that.parent().find('option').removeAttr('selected').filter('option').eq(i).attr('selected','selected').parent().change();
						});
						
						box.append(option);	
					});
					
					box = $('<div class="fancy-select-box-outer"><div class="fancy-select-box-arrow"></div></div>').append(box);
					$(document.body).append(box);
					
				}
				
				// if there are any other open boxes in this set, hide them
				if(activeBox){
					activeBox.click();
				}
				
				if(!box.is(':visible')){
					e.stopPropagation();
					activeBox = box;
					box.css({
						left : that.offset().left + 'px',
						top  : that.offset().top + that.outerHeight(false) + 'px'
					});
					box.slideDown(120);
					$(document).one('click', function () {
						box.slideUp(120);
						activeBox = null;
						return false;
					});
				}
				return false;
			});
		}
	});
}

// Temporary replacement of classNewsletter
function subscribeNewsletter() {
	var blinkInterval, blinkCount = 0, blinkWhite = false,
	emailForm = document.getElementById('footer-newsletter-form'),
	errorMessage = document.getElementById('footer-newsletter-error'),
	successMessage = document.getElementById('footer-newsletter-success'),
	emailInput = document.getElementById('footer-newsletter-input'),
	enterMessage = document.getElementById('enter-email'),
	emailSubmitButton = document.getElementById('footer-newsletter-button'),	

	
	emailEmptyVal = function(){
		$(emailInput).focus(function(){
			if(this.value=='your@email.com'){
				$(this).removeClass('email-opacity');
				this.value = '';
			}
		}).blur(function(){
			if(this.value==''){
				this.value = 'your@email.com';
			}
			if(this.value=='your@email.com'){
				$(this).addClass('email-opacity');
			}
		});
	},
	
	blinkError = function () {
		return function () {
			if (blinkCount < 4) {
				errorMessage.style.color = (blinkWhite) ? '#cc0000' : '#ffffff';
				blinkWhite = !blinkWhite;
				blinkCount++;
			} else {
				window.clearInterval(blinkInterval);
				blinkCount = 0;
			}
		};
	},
	
	// JSONP submit to phplist
	emailSubmit = function () {
		return function () {
			var query = 'http://enews.opticsplanet.com?p=subscribe&id=1&store=opticsplanet2&jsonp=',
			filter = /^([a-zA-Z0-9_.\-])+@(([a-zA-Z0-9\-])+.)+([a-zA-Z0-9]{2,4})+$/;

			if (emailInput.value !== '' && emailInput.value !== 'your@email.com' && filter.test(emailInput.value)) {
				query += emailInput.value;
				addScriptToHead(query, '', 'js');
			} else {
				if(enterMessage){
					enterMessage.style.display = 'none';
				}
				errorMessage.style.display = 'block';
				blinkInterval = window.setInterval(blinkError(), 100);
			}
			return false;
		};
	};
	
	// Subscription confirmation, JSONP response from phplist 
	this.emailResponse = function (status) {
		console.log('answer received');
		if (status === 'added') {
			if (errorMessage) errorMessage.style.display = 'none';
			if (emailInput) emailInput.style.display = 'none';
			if (emailSubmitButton) emailSubmitButton.style.display = 'none';
			if (enterMessage) enterMessage.style.display = 'none';
			if (successMessage) successMessage.style.display = 'block';
		} else if (status === 'error') {
			alert("subscription error");
		}
		return false;
	};

	// constructor
	if (emailForm) {
		emailForm.onsubmit = emailSubmit();
	}
	
	emailEmptyVal();
	
} // end of classNewsletter


// dynamically grab the number of FB likes for footer
$(function (){
	$.getJSON('https://graph.facebook.com/opticsplanet', function(data) {
		$('em#footer-facebook-likes').append(Math.floor(data.likes/1000) + 'K+');
	});
});

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
	
	// 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
	}
	
	// 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);
	
	// GA Extras
	window.setTimeout('googleAnalyticsAsyncExtras();', 0);
	
	// fix fuckups
	//initPriceAdjust();
	//initDisableAddToCart();
	
	// checks if newsletter data is in url and adds cookie
	window.setTimeout('newsletterData();', 0);

	// init collapsible multiple breadcrumbs (V. Nguyen)
	window.setTimeout('breadcrumbsHider();', 0);

	// init back to top
	window.setTimeout('scrollableTopLink();', 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);
	
	// 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);
	
	// 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);
	})();
}

