var 
// Adds script tag to head of the page
addScriptToHead = function(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);
}, 

imageSwapper = function(){
	// Swaps product images
	var imageThumbUrl, newImage, newImageSrc, newImageAlt,
	mainImage = $('#product-main-picture img'),
	imageThumbLink = $('#product-thumbnail-images-container a.product-thumbnail-images');
	
	// Handles all image changes for clicks
	imageThumbLink.each(function(){
		imageThumbLink.click(function(){
			// selects the thumbnail
			if(!$(this).hasClass('product-thumbnail-images-selected')){
				$('#product-thumbnail-images-container a.product-thumbnail-images').not(this).removeClass('product-thumbnail-images-selected');
				$(this).addClass('product-thumbnail-images-selected');
			}
			// changes image to selected thumbnail
			newImageSrc = $('#product-thumbnail-images-container .product-thumbnail-images-selected').attr('href');
			newImageAlt = $('#product-thumbnail-images-container .product-thumbnail-images-selected').find('img').attr('alt');
			
			if (mainImage.attr('src') != newImageSrc){
				mainImage.attr('src', newImageSrc).attr('alt', newImageAlt);
			}
			return false;
		})
	});
},

Cookie = function(name) {
	// Cookie handling
	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);
	};
},

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

QNA = function() {
	// Question and Answer
	var 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('container'),

	// 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);
		}
	}
},
// "subscribe to newsletter" (D. Naumov) (Optimized by M. Fayman)
ClassNewsletter = function() {
	var blinkInterval, blinkCount = 0, blinkWhite = false,
	emailForm = document.getElementById('reg'),
	errorMessage = document.getElementById('email-format-error'),
	successMessage = document.getElementById('subscribe-success'),
	emailInput = document.getElementById('signup'),
	
	// JSONP submit to phplist
	emailSubmit = function () {
		return function () {
			var query = 'http://enews.opticsplanet.com?p=subscribe&id=1&store=bushnellspeedster&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 {
				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 = 'none';
			successMessage.style.display = 'block';
		} else if (status === 'error') {
			alert("subscription error");
		}
		return false;
	};

	// constructor
	if (emailForm) {
		emailForm.onsubmit = emailSubmit();
	}
} // end of classNewsletter
, initGlobalJavascript = function(){
	imageSwapper();
	QNA();
	classNewsletter = new ClassNewsletter();
}
