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

// mobile browser detect from detectmobilebrowser.com modified to return true/false instead of redirecting, call - mobile(navigator.userAgent||navigator.vendor||window.opera)
function mobile(a){if(/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile|o2|opera mini|palm( os)?|plucker|pocket|pre\/|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|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)))return true;else return false}

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

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

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

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

	// 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
	if (mainPanel) {
		containers = getElementsByClassName(mainPanel, 'collapsible-content-question', 'div');
		containers = containers.concat(getElementsByClassName(mainPanel, '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);
		}
	}
}

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

// 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 = 260;
		nodes = gridContainer.childNodes;
		numNodes = nodes.length;
		pageContainer = document.getElementById('page-container');
		if (pageContainer.className.match(/no-left-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);
}

function selectors() {
	var lists, i, j, l, li, button,
	container = document.getElementById('selectors-container'),
	
	openCloseSelector = function () {
		return function () {
			if (this.parentNode.className === 'selectors-collapsed') {
				this.innerHTML = '<span>Less</span>';
				this.parentNode.className = '';
			} else {
				this.innerHTML = '<span>' + (this.parentNode.getElementsByTagName('li').length - 6) + ' More</span>';
				this.parentNode.className = 'selectors-collapsed';
			}
		};
	};
	
	// init
	if (container) {
		lists = getElementsByClassName(container, 'selectors-collapsed', 'ul');
		for (i = 0, l = lists.length; i < l; i++) {
			li = lists[i].getElementsByTagName('li');
			if (li.length > 6) {
				button = li[li.length - 1];
				button.innerHTML = '<span>' + (li.length - 6) + ' More</span>';
				button.onclick = openCloseSelector();
			}
		}
	}
}

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,
	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';
							colsList[i][numCols[i]].style.borderBottom = '1px solid #fff';
						}
					}
				}
			}
		};
	};
	
	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';
					colsList[k][numCols[k]].style.borderBottom = '1px solid #fff';
				}
				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 = '';
					colsList[k][numCols[k]].style.borderBottom = '';
				}
				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.nextSibling);
		}
		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 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, createEl, newImg, setOpacity, fadeIn, fadeInTimer = [], fadeInOpac = [], fadeOut, fadeOutTimer = [], fadeOutOpac = [], nextDiv = null, prevDiv = null, nextPrev, popAlt, magGlass, 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.tacticalstore.com/180-180-ffffff/',
	objects = document.getElementsByTagName('object'),
	videoList = document.getElementById('caption-documents-flv'),
	isMobile = mobile(navigator.userAgent||navigator.vendor||window.opera);
	fadeInOpac[1] = 0;
	fadeInOpac[0] = 0;
	fadeInTimer[1] = null;
	fadeInTimer [0] = null;
	fadeOutTimer[1] = null;
	fadeOutTimer [0] = 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;
		popDiv.style.height = popH + 'px';
		if (mainLink) {
			bigUrl = 'http://images1.tacticalstore.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];
			}
			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 = '';
					}
				}
			}
		};
	};
	
	// Creates elements with attributes and appends it if parent provided
	createEl = function (elType, elExtras, elParent) {
		var el, 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;
	};
	
	// Handles all image changes for mouseovers and clicks, includes preload
	setNewImage = function (img, popArea, changeCurrent) {
		var imgSrc, skip = false, url, setImg, setAlt, tempImg;
		imgSrc = img.src.split('/');
		imgSrc = imgSrc[imgSrc.length - 1].split('.', 1);
		setImg = bigUrl + imgSrc + '.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);
			};
			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 () {
		for (i = 0; i < popIcons.length; i++) {
			if (popIcons[i].src.split('-ffffff')[1] === currentImg.split('-ffffff')[1].replace('.jpg', '.gif')) {
				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 || isMobile) {
					popDiv.className = 'hidden-object';
					faderDiv.className = 'hidden-object';
					if (flashLink) {
						flashLink.style.display = 'none';
					}
				} else {
					fadeOutTimer[1] = window.setInterval(fadeOut(popDiv, 0, 1), 50);
					fadeOutTimer[0] = window.setInterval(fadeOut(faderDiv, 0, 0), 50);
				}
				document.onkeydown = null;
			}
		};
	};
	
	// Mouse over event handler
	eventOver = function () {
		return function (e) {
			var inPopUp;
			if (this.parentNode.id === 'pop-icon-container') {
				newImg = this;
				inPopUp = true;
			} else {
				newImg = this.getElementsByTagName('img')[0];
				inPopUp = false;
			}
			setNewImage(newImg, inPopUp, false);
		};
	};
	
	// Mouse out event handler
	eventOut = function () {
		return function (e) {
			//preLoader.onload = null;
			if (this.parentNode.id === 'pop-icon-container') {
				popImg.src = currentImg;
				popImg.className = '';
				popAlt.innerHTML = currentAlt;
			} else {
				mainImg.src = origMainImg;
				mainImg.alt = origMainAlt;
				mainImg.className = '';
			}
		};
	};
	
	// Switches back and forth from movies to pictures in the pop up
	toggleSwitch = function (showVid) {
		return function () {
			if (showVid) {
				if (mainLink) {
					vidButton.className = 'selected';
					vidButton.onclick = null;
					picButton.className = '';
					picButton.onclick = toggleSwitch(false);
				}
				moviePlayer.style.visibility = '';
				popAlt.innerHTML = playlist[movieNum].title;
				if (flashLink) {
					flashLink.style.display = 'block';
				}
				if (nextDiv !== null && prevDiv !== null) {
					nextDiv.className = 'disable-me';
					nextDiv.style.display = 'none';
					nextDiv.onclick = null;
					prevDiv.className = 'disable-me';
					prevDiv.style.display = 'none';
					prevDiv.onclick = null;
				}
				if (playlist.length > 1) {
					window.setTimeout(addPlaylist(), 100);
				} else if (movieObject && typeof(movieObject.sendEvent) === 'function') {
					movieObject.sendEvent('ITEM', '0');
				}
			} else {
				if (movieObject && typeof(movieObject.sendEvent) === 'function') {
					movieObject.sendEvent('STOP');
				}
				vidButton.className = '';
				vidButton.onclick = toggleSwitch(true);
				picButton.className = 'selected';
				picButton.onclick = null;
				if (flashLink) {
					flashLink.style.display = 'none';
				}
				moviePlayer.style.visibility = 'hidden';
				popAlt.innerHTML = currentAlt;
				if (nextDiv !== null && prevDiv !== null) {
					nextDiv.style.display = 'block';
					prevDiv.style.display = 'block';
					setSelected();
				}
			}
		};
	};
	
	// Mouse click event handler
	eventClick = function (movNum) {
		return function (e) {
			if (movNum < 0) {
				var inPopUp;
				if (this.parentNode.id === 'pop-icon-container') {
					newImg = this;
					inPopUp = true;
				} else if (this.id === 'enlarge-text') {
					newImg = mainImg;
					inPopUp = false;
				} else {
					newImg = this.getElementsByTagName('img')[0];
					inPopUp = false;
				}
				setNewImage(newImg, inPopUp, true);
				setSelected();
			}
			if (this.parentNode.id !== 'pop-icon-container') {
				myInterval = window.setInterval(centerPopDiv(), 250); // Starts up centering function so pop up stays centered on window resize
				if (fadeInTimer[1] === null && fadeInTimer[0] === null && fadeOutTimer[0] === null && fadeOutTimer[1] === null) {
					for (i = 0; i < objects.length; i++) {
						if (objects[i].id !== 'flvMoviePlayer') {
							objects[i].style.visibility = 'hidden';
						}
					}
					if (document.all && !window.opera || isMobile) {
						faderDiv.className = '';
						popDiv.className = '';
					} else {
						fadeInTimer[0] = window.setInterval(fadeIn(faderDiv, 4, 0), 50);
						fadeInTimer[1] = window.setInterval(fadeIn(popDiv, 5, 1), 50);
					}
					document.onkeydown = keyDownEvent();
					scrollFix = getScroll();
					popDiv.style.top = topPos + scrollFix + 'px';
				}
				if (playlist.length > 0) {
					movieNum = (movNum > -1) ? movNum : 0;
					window.setTimeout(toggleSwitch(movNum > -1), 1);
				}
			}
			return false;
		};
	};
	
	// Event handler for next and prev buttons in pop up
	nextPrev = function (direction) {
		return function (e) {
			for (i = 0; i < popIcons.length; i++) {
				if (popIcons[i].className === 'selected-image') {
					if (direction === 'back' && i > 0) {
						newImg = popIcons[i - 1];
						break;
					} else if (direction === 'forward' && i < (popIcons.length - 1)) {
						newImg = popIcons[i + 1];
						break;
					}
				}
			}
			setNewImage(newImg, true, true);
			setSelected();
			return false;
		};
	};
	
	keyDownEvent = function () {
		return function (e) {
			var keynum = (window.event) ? window.event.keyCode : e.which;
			switch (keynum) {
			case 37: // left arrow key press
				if (prevDiv !== null && prevDiv.className !== 'disable-me') {
					window.setTimeout(nextPrev('back'), 1);
				}
				break;
			case 39: // right arrow key press
				if (nextDiv !== null && nextDiv.className !== 'disable-me') {
					window.setTimeout(nextPrev('forward'), 1);
				}
				break;
			case 27: // escape key press
				if (popDiv.className !== 'hidden-object') {
					window.setTimeout(hideImage(), 1);
				}
				break;
			}
		};
	};
	
	findMovie = function () {
		return function () {
			if (!movieObject) {
				movieObject = document.getElementById('flvMoviePlayer');
				winH = 0;
			} else {
				window.setTimeout(findMovie(), 50);
			}
		};
	};
	
	embedFlash = function () {
		return function () {
			if (typeof(swfobject) === 'object') {
				swfobject.embedSWF('http://layout.tacticalstore.com/player-licensed.swf', 'flv-movie', '1020', '680', '9', false, flashVars, flashParams, flashAttributes);
				findMovie()();
			} else {
				window.setTimeout(embedFlash(), 50);
			}
		};
	};
	
	// init
	if (picBlock && mainLink || videoList) {
		if (mainLink) {
			magGlass = createEl('img', {'id': 'mag-glass-img', 'src': 'http://layout.tacticalstore.com/tactical-store/images/tiny-mag-glass.png', 'width': '12', 'height': '10'}, mainLink); // This adds the magnifying glass image over the main image
			
			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.tacticalstore.com/images/loading.gif'});
			picBlock.insertBefore(loadingImg, mainLink);
		} 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) {
			popLoadingImg = createEl('img', {'id': 'pop-loading-img', 'src': 'http://layout.tacticalstore.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);
		
			for (i = 0; (links = picBlock.getElementsByTagName('a')[i]); i++) { // Loops through the small images and creates new ones from it for the pop up and adds events
				if (links.id !== 'main-picture') {
					linksImg = links.getElementsByTagName('img')[0];
					if (linksImg.src.match(/\?video\=/)) {
						video = linksImg.src.split(/\?video\=/)[1];
						playlist.push({description: "", file: "http://images1.tacticalstore.com/flv/" + video + ".flv", title: linksImg.alt, type: "video"});
						links.onclick = eventClick(playlist.length - 1);
					} else {
						links.onmouseover = eventOver();
						links.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.onclick = eventClick(-1);
					}
				} else {
					links.onclick = eventClick(-1);
				}
				links.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.tacticalstore.com/flv/" + video + ".flv", title: links.innerHTML, type: "video"});
				links.onclick = eventClick(playlist.length - 1);
			}
		}
		if (playlist.length > 0) {
			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'};
			addScriptToHead('http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js', '', 'js');
			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('page-container').appendChild(popDiv);
			document.getElementById('page-container').appendChild(faderDiv);
		}
		window.setTimeout(centerPopDiv(), 200);
	}
}

function scrollRelatedProds() {
	var items, end, scrollProd, scrollIt, keepAtTop, oldTop, getScrollTop, mouseOver, pageScroll, counter = 0, getY,
	footer = document.getElementById('footer'),
	leftPanelBox = document.getElementById('left-panel-specials'),
	nextStop = 0,
	scrollPos = 0,
	start = 0,
	scrollable = false,
	next = document.createElement('div'),
	prev = document.createElement('div'),
	container = document.getElementById('left-panel-specials-scrollbox'),
	isMobile = mobile(navigator.userAgent||navigator.vendor||window.opera);
	
	getY = function (obj) {
		var curtop = 0;
		if (obj.offsetParent) {
			while (1) {
				curtop += obj.offsetTop;
				if (!obj.offsetParent) {
					break;
				}
				obj = obj.offsetParent;
			}
		}
		return curtop;
	};
	
	getScrollTop = function () {
		var scrollTop = document.body.scrollTop;
		if (scrollTop === 0) {
			if (window.pageYOffset) {
				scrollTop = window.pageYOffset;
			} else {
				scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
		}
		return scrollTop;
	};

	keepAtTop = function () {
		return function () {
			var scrollY = getScrollTop(),
			footerY = getY(footer);
			if (scrollY !== pageScroll) {
				pageScroll = scrollY;
				if (leftPanelBox.className === '' && oldTop !== leftPanelBox.offsetTop) {
					oldTop = leftPanelBox.offsetTop;
				}
				if (pageScroll > oldTop) {
					if ((footerY - pageScroll) < 220) {
						leftPanelBox.className = 'left-panel-absolute';
					} else if (leftPanelBox.className !== 'left-panel-static') {
						leftPanelBox.className = 'left-panel-static';
					}
				} else if (pageScroll < oldTop && leftPanelBox.className === 'left-panel-static') {
					leftPanelBox.className = '';
				}
			}
			if (scrollable) {
				if (counter === 50) {
					window.setTimeout(scrollProd(-9), 0);
				} else {
					counter++;
				}
			}
		};
	};
	
	scrollIt = function (speed) {
		return function () {
			scrollPos += speed;
			container.style.left = scrollPos + 'px';
			if (scrollPos === nextStop) {
				next.onclick = scrollProd(-9);
				prev.onclick = scrollProd(9);
				return;
			}
			window.setTimeout(scrollIt(speed), 20);
		};
	};
	
	scrollProd = function (dir) {
		return function () {
			if (next.onclick !== null) {
				next.onclick = null;
				prev.onclick = null;
			}
			if (dir < 0) {
				if (nextStop === end) {
					nextStop = start;
					container.style.left = start + 'px';
					scrollPos = start;
				}
				nextStop += -189;
			} else {
				if (nextStop === start) {
					nextStop = end;
					container.style.left = end + 'px';
					scrollPos = end;
				}
				nextStop += 189;
			}
			counter = 0;
			window.setTimeout(scrollIt(dir), 20);
		};
	};
	
	mouseOver = function (isOver) {
		return function () {
			if (isOver) {
				scrollable = false;
				next.onclick = prev.onclick = null;
			} else {
				scrollable = true;
				counter = 0;
				next.onclick = scrollProd(-9);
				prev.onclick = scrollProd(9);
			}
		};
	};
	
	// init
	if (container && !isMobile) {
		items = getElementsByClassName(container, 'left-panel-specials-item', 'div');
		if (items.length > 1) {
			container.appendChild(items[0].cloneNode(true));
			end = items.length * -189;
			container.style.width = (items.length + 1) * 189 + 'px';
			container.style.left = start + 'px';
			next.id = 'next-button';
			next.onclick = scrollProd(-9);
			container.parentNode.appendChild(next);
			prev.id = 'prev-button';
			prev.onclick = scrollProd(9);
			container.parentNode.appendChild(prev);
			scrollable = true;
			container.onmouseover = mouseOver(true);
			container.onmouseout = mouseOver(false);
		}
		oldTop = leftPanelBox.offsetTop;
		pageScroll = getScrollTop();
		window.setInterval(keepAtTop(), 100);
	}
}

// makes tabs work
function Tabs(tabsContainerId, tabContainerClass, tabNameClass, resizeTabs, secondaryContainerId) {
	var i, tabs, tabsTwo, tabWidth, currentTab, active, thisWidth,
	tabsContainer = document.getElementById(tabsContainerId),
	tabsContainerTwo = document.getElementById(secondaryContainerId),
	ie = getIEVersion(),
	
	tabClickHandler = function (self) {
		return function () {
			currentTab.parentNode.className = 'tab-enabled';
			self.parentNode.className = 'tab-active';
			currentTab = self;
			return false;
		};
	},
	
	tabHoverHandler = function (hover) {
		return function () {
			this.className = tabNameClass + (hover ? ' tab-name-hover' : '');
		};
	};
	
	this.showTab = function (tabIndex) {
		if (tabs.length > tabIndex) {
			tabClickHandler(tabs[tabIndex])();
		}
	};
	
	if (tabsContainer) {
		tabsContainer.className = tabContainerClass;
		tabs = getElementsByClassName(tabsContainer, tabNameClass, 'div');
		if (tabs.length > 0) {
			if (resizeTabs) {
				tabWidth = 0;
				for (i = 0; i < tabs.length; i++) {
					if (tabs[i].parentNode.className === 'tab-active') {
						active = true;
						currentTab = tabs[i];
					} else {
						active = false;
						tabs[i].parentNode.className = 'tab-active';
					}
					if (ie < 8) {
						tabs[i].getElementsByTagName('div')[0].style.display = 'inline';
					}
					thisWidth = tabs[i].getElementsByTagName('div')[0].offsetWidth + 32;
					if (ie < 8) {
						tabs[i].getElementsByTagName('div')[0].style.display = 'block';
					}
					tabs[i].style.left = tabWidth + 'px';
					tabs[i].style.width = thisWidth + 'px';
					tabWidth += thisWidth;
					if (!active) {
						tabs[i].parentNode.className = 'tab-enabled';
					}
				}
			} else {
				tabs[tabs.length - 1].style.marginRight = '0';
			}
			for (i = 0; i < tabs.length; i++) {
				if (tabs[i].parentNode.className !== 'tab-disabled') {
					if (!tabs[i].getElementsByTagName('a')[0]) {
						tabs[i].onclick = tabClickHandler(tabs[i]);
					}
					tabs[i].onmouseover = tabHoverHandler(true);
					tabs[i].onmouseout = tabHoverHandler(false);
				}
			}
			if (tabsContainerTwo) {
				tabsTwo = tabsContainerTwo.getElementsByTagName('a');
				for (i = 0; i < tabsTwo.length; i++) {
					tabsTwo[i].onclick = tabClickHandler(tabs[i]);
				}
			}
		}
	}
}

function BannerScroll(bigSize, banners) {
	var scrollDiv, scrollMain, scrollCp, i, l, theLink = [], theLink2 = [], scrollLeft = 0, pauseButton, paused = false, whereToInsertCode, whereToInsert, nextButton, prevButton, smallScrollBox, imageLink, banTotal, lastWidth = 0, resizeInt, scrollContain, smallImg = [], thumbRight, scrollPosBox, scrollPosBox2, smallScrollLeft, scrollPosWidth, smallScrollLeft2, bannerHeight, smallBanHeight, counter = 39, currentBan = 0, scrollInt = null, dist = 0,
	isMobile = mobile(navigator.userAgent || navigator.vendor || window.opera),
	
	// Creates elements with attributes and appends it if parent provided
	createEl = function (elType, elExtras, elParent) {
		var el, attribute;
		el = document.createElement(elType);
		for (attribute in elExtras) {
			if (elExtras[attribute] !== '') {
				el.setAttribute(attribute, elExtras[attribute]);
			}
		}
		if (elParent) {
			elParent.appendChild(el);
		}
		return el;
	},
	
	rand = function () {
		return Math.random() - 0.5;
	},
	
	runStop = function () {
		return function () {
			if (this.id === 'scroller-run-stop') {
				if (pauseButton.className === 'show-pause') {
					this.blur();
					pauseButton.className = 'show-play';
					paused = true;
					counter = 0;
				} else {
					this.blur();
					pauseButton.className = 'show-pause';
					paused = false;
					counter = 39;
				}
			} else {
				if (pauseButton.className === 'show-pause') {
					paused = (!paused) ? true : false;
					counter = 0;
				}
			}
		};
	},
	
	smallScroller = function () {
		smallScrollLeft = (scrollLeft / 20);
		if (-smallScrollLeft > smallScrollBox.offsetWidth) {
			smallScrollLeft = 0;
		}
		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';
		}
	},
	
	disableEvents = function () {
		nextButton.onclick = prevButton.onclick = pauseButton.onclick = scrollDiv.onmouseover = scrollDiv.onmouseout = null;
		for (i = 0, l = theLink2.length; i < l; i++) {
			theLink2[i].onclick = null;
		}
	},
	
	enableEvents = function () {
		nextButton.onclick = goTo('next');
		prevButton.onclick = goTo('prev');
		pauseButton.onclick = scrollDiv.onmouseover = scrollDiv.onmouseout = runStop();
		for (i = 0, l = theLink2.length; i < l; i++) {
			theLink2[i].onclick = goTo(i);
		}
	},
	
	scrollMe = function () {
		return function () {
			var diff = dist / 8;
			diff = Math.ceil(Math.abs(diff)) * Math.round(diff / Math.abs(diff));
			dist -= diff;
			scrollLeft = scrollLeft - diff;
			if (dist > 0 && (scrollLeft < -banTotal || scrollLeft === -banTotal)) {
				scrollLeft += banTotal;
			} else if (scrollLeft > 0) {
				scrollLeft -= banTotal;
			}
			scrollDiv.style.left = scrollLeft + 'px';
			smallScroller();
			if (dist === 0) {
				enableEvents();
				window.clearInterval(scrollInt);
			}
		};
	},
	
	goTo = function (pos) {
		return function () {
			var left, right, direction;
			if (this.id && this.id.match('scroller')) {
				this.blur();
			}
			disableEvents();
			if (pos === 'next') {
				pos = currentBan + 1;
			} else if (pos === 'prev') {
				pos = currentBan - 1;
			}
			if (pos > currentBan) {
				right = pos - currentBan;
				left = currentBan + (banners.length - pos);
			} else {
				right = pos + (banners.length - currentBan);
				left = currentBan - pos;
			}
			direction = (left < right) ? -left : right;
			dist = direction * 401;
			currentBan = pos;
			scrollInt = window.setInterval(scrollMe(), 20);
			counter = 0;
			return false;
		};
	},
	
	windowResize = function () {
		return function () {
			if (!paused) {
				if (counter === 40) {
					window.setTimeout(goTo('next'), 0);
					counter = 0;
				} else {
					counter++;
				}
			}
			if (lastWidth !== document.body.offsetWidth) {
				lastWidth = document.body.offsetWidth;
				scrollContain.style.width = scrollMain.offsetWidth + 'px';
				scrollPosWidth = scrollContain.offsetWidth / 20;
				scrollPosBox.style.width = scrollPosBox2.style.width = scrollPosWidth + 'px';
				smallScroller();
			}
		};
	},
	
	thumbOver = function (num) {
		return function () {
			smallImg[num].className = (smallImg[num].className === 'scroller-thumb') ? 'top-nav-hidden' : 'scroller-thumb';
		};
	};
	
	// init
	if (banners && !isMobile) {
		banners.sort(rand);
		bannerHeight = (bigSize) ? 200 : 150;
		smallBanHeight = (bigSize) ? 40 : 30;
		imageLink = (bigSize) ? 'http://layout.tacticalstore.com/images/scroller/' : 'http://layout.tacticalstore.com/images/scroller/mini-slides/';
		banTotal = banners.length * 401;
		
		scrollMain = createEl('div', {'id' : 'scroller-main-container'});
		scrollMain.style.height = bannerHeight + 30 + 'px';
		scrollCp = createEl('div', {'id' : 'scroller-control-panel'}, scrollMain);
		
		pauseButton = createEl('div', {'id' : 'scroller-run-stop'}, scrollCp);
		pauseButton.className = 'show-pause';
		
		nextButton = createEl('div', {'id' : 'scroller-next-button'}, scrollCp);
		prevButton = createEl('div', {'id' : 'scroller-prev-button'}, scrollCp);
		
		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 + 2 + 'px';
		
		scrollDiv = createEl('div', {'id' : 'scroller-banners'}, scrollContain);
		scrollDiv.style.width = (banTotal * 2) + 'px';
		thumbRight = (banners.length * 20) - 15;
		for (i = 0, l = banners.length; i < l; i++) {
			theLink[i] = createEl('a', {'href' : banners[i].url}, scrollDiv);
			theLink[i].innerHTML = '<img src="' + imageLink + banners[i].imageId + '.jpg" alt="' + banners[i].alt + '" width="400" height="' + bannerHeight + '" style="display:inline;">';
			theLink2[i] = createEl('a', {'href' : '#', 'id' : ('scroller-thumb' + i)}, smallScrollBox);
			theLink2[i].innerHTML = i + 1;
			theLink2[i].onmouseover = theLink2[i].onmouseout = thumbOver(i);
			smallImg[i] = createEl('img', {'src' : imageLink + 'small/' + banners[i].imageId + '.jpg', 'alt' : banners[i].alt, 'class' : 'top-nav-hidden', 'width' : 80, 'height' : smallBanHeight}, scrollContain);
			smallImg[i].style.right = thumbRight + 'px';
			thumbRight -= 20;
		}
		for (i = 0, l = theLink.length; i < l; i++) {
			scrollDiv.appendChild(theLink[i].cloneNode(true));
		}
		if (document.getElementById('breadcrumbs')) {
			whereToInsertCode = document.getElementById('breadcrumbs').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);
		}
		enableEvents();
		windowResize()();
		smallScroller();
		resizeInt = window.setInterval(windowResize(), 100);
	}
}

// Creates the tip boxes and handles the hiding and showing
function TipBox(tipParent, tipText, specialCase) {
	var tipBody, tipPointer, container, parent, text, createTip, eventOverOut, timer = null, showTip = false, hideShow, x, y, wrapParent;
	parent = tipParent;
	text = tipText;
	
	// 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;
				}
			}
		};
	};
	
	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;
		};
	};
	
	// Wrap a parent in a span for styling
	wrapParent = function () {
		var guts, tipSpan;
		guts = parent.innerHTML;
		tipSpan = document.createElement('span');
		tipSpan.className = 'tip';
		tipSpan.innerHTML = guts;
		parent.innerHTML = '';
		parent.appendChild(tipSpan);
	};
	
	// Creates tip
	createTip = function () {
		var footer = document.getElementById('footer');
		
		tipBody = document.createElement('div');
		tipBody.className = 'tip-body';
		tipBody.innerHTML = text;
	
		tipPointer = document.createElement('div');
		tipPointer.className = 'tip-pointer';
		if (specialCase) {
			tipPointer.style.left = '250px';
		}
		
		container = document.createElement('div');
		container.className = 'tip-container-hidden';
		container.appendChild(tipBody);
		container.appendChild(tipPointer);
		container.onmouseover = eventOverOut();
		container.onmouseout = eventOverOut();
		
		footer.appendChild(container);
		
		parent.onmouseover = eventOverOut();
		parent.onmouseout = eventOverOut();
	};
	
	// init
	if (parent && text) {
		wrapParent();
		createTip();
	}
}

// "subscribe to newsletter" (D. Naumov) (Optimized by M. Fayman)
function classNewsletter() {
	var blinkInterval, blinkCount = 0, blinkWhite = false,
	emailForm = document.getElementById('newsletterFrm'),
	emailSubmitButton = document.getElementById('email-submit-button'),
	errorMessage = document.getElementById('email-format-error'),
	successMessage = document.getElementById('subscribe-success'),
	emailInput = document.getElementById('newsletter-input'),
	enterMessage = document.getElementById('enter-email'),
	
	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=tacticalstore&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 {
				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) {
		if (status === 'added') {
			errorMessage.style.display = emailForm.style.display = enterMessage.style.display = 'none';
			successMessage.style.display = 'block';
		} else if (status === 'error') {
			alert("subscription error");
		}
		return false;
	};

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

// feedback forms popup stuff (D. Naumov) (Optimized by M. Fayman)
function classFeedbackForm() {
	var helpWindow = document.getElementById('help-window'),
	helpCloseButton = document.getElementById('help-close-button'),
	linkRFQ = document.getElementById('icon-link-price_quote'),
	linkRFQheader = document.getElementById('header-link-rfq'),
	linkContactheader = document.getElementById('header-link-contact'),
	linkPriceMatch = document.getElementById('icon-link-best_price'),
	linkExpertAdvice = document.getElementById('icon-link-ask_an_expert'),
	linkDealNotification = document.getElementById('icon-link-deal_request'),
	linkEmailThisPage = document.getElementById('email-icon'),
	linkCallToOrder = document.getElementById('call-to-order-button'),
	link2CallToOrder = document.getElementById('call-to-order-link'),
	feedbackData = {
		'rfq' : {'title' : 'RFQ', 'height' : '1030px', 'ie6height' : '1060px'},
		'es' : {'title' : 'Email Support', 'height' : '550px', 'ie6height' : '580px'},
		'pm' : {'title' : 'Price Match', 'height' : '780px', 'ie6height' : '810px'},
		'ea' : {'title' : 'Expert Advice', 'height' : '520px', 'ie6height' : '550px'},
		'dn' : {'title' : 'Deal Notification', 'height' : '820px', 'ie6height' : '850px'},
		'etp' : {'title' : 'Email This Page', 'height' : '650px', 'ie6height' : '680px'},
		'cto' : {'title' : 'Call To Order', 'height' : '1030px', 'ie6height' : '1060px'}
	},
	
	openFormWindow = function (type) {
		return function () {
			var spanTitle = document.getElementById('span-title'),
			formFrame = document.getElementById('form-frame'),
			isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
			if (isIE6) {
				window.scrollTo(0, 0);
			}
			if (spanTitle && formFrame) {
				spanTitle.innerHTML = feedbackData[type].title;
				helpWindow.style.height = isIE6 ? feedbackData[type].ie6height : feedbackData[type].height;
				formFrame.src = this.href.replace(/fullsize|window/, 'iframe');
				formFrame.style.visibility = 'hidden';
				helpWindow.style.display = 'block';
			}
			return false;
		};
	},
	
	closeButton = function () {
		return function () {
			helpWindow.style.display = 'none';
			return false;
		};
	};
	
	this.closeFormWindow = function () {
		closeButton()();
		return false;
	};
	
	// constructor
	if (helpWindow) {
		if (linkRFQ) {
			linkRFQ.onclick = openFormWindow('rfq');
		}
		if (linkRFQheader) {
			linkRFQheader.onclick = openFormWindow('rfq');
		}
		if (linkContactheader) {
			linkContactheader.onclick = openFormWindow('es');
		}
		if (linkPriceMatch) {
			linkPriceMatch.onclick = openFormWindow('pm');
		}
		if (linkExpertAdvice) {
			linkExpertAdvice.onclick = openFormWindow('ea');
		}
		if (linkDealNotification) {
			linkDealNotification.onclick = openFormWindow('dn');
		}
		if (linkEmailThisPage) {
			linkEmailThisPage.onclick = openFormWindow('etp');
		}
		if (helpCloseButton) {
			helpCloseButton.onclick = closeButton();
		}
		if (linkCallToOrder) {
			linkCallToOrder.onclick = openFormWindow('cto');
		}
		if (link2CallToOrder) {
			link2CallToOrder.onclick = openFormWindow('cto');
		}
	}
}; // end of classFeedbackForm

// function for resizing confirmation popup
function helperResizeForCloseScreen() {
	var helpWindow = document.getElementById('help-window');
	if (helpWindow) {
		helpWindow.style.height = "420px";
	}
	window.scrollTo(0,0);
}

function setupTipBoxes() {
	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 !== 'left-panel-specials-item') ? true : false;
		tips[i] = new 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);
	}
}

function initPage() {
	if (document.domain.match('tactical-store.com') && !document.domain.match('feedback')) {
		// required for classFeedbackForm JS security permissions (D. Naumov)
		document.domain = 'tactical-store.com';
		
		// init feedback forms (D. Naumov)
		classFeedbackForm = new classFeedbackForm();
	}

	// init "subscribe to newsletter" stuff (D. Naumov)
	classNewsletter = new classNewsletter();
	
	// setup bundles expand and collapse
	window.setTimeout('bundles();', 0);
	
	// fire up selectors event handling if any exist
	window.setTimeout('selectors();', 0);
	
	// load up image gallery script for product pages
	window.setTimeout('ImageSwapper();', 0);
	
	// load up scroller for left panel related products
	window.setTimeout('scrollRelatedProds();', 0);
	
	// load Collapsible QnA script
	window.setTimeout('QNA();', 0);
	
	// setup tip boxes
	window.setTimeout('setupTipBoxes();', 0);
}