// NYCe Wheels Global Javascript

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

// Sets the opacity level for an element
function setOpacity(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
}

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

// 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;
	};
	
	this.getValue = function () {
		var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
		return results ? unescape(results[2]) : null;
	};
	
	this.remove = function () {
		this.setValue("", -1);
	};
}

// IE6 fix for header menu and non anchor tag hover issues
function initHeaderMenu() {
	var i, timer = null, eventOver, eventOut, hideShow, showMe = false, last = -1,
	els = document.getElementById('header-menu').childNodes;
	
	hideShow = function (which) {
		return function () {
			if (showMe) {
				if (!els[which].className.match('header-menu-hover')) {
					els[which].className += ' header-menu-hover';
				}
				if (oldIE && els[which].getElementsByTagName('ul')[0]) {
					els[which].getElementsByTagName('ul')[0].style.width = els[which].offsetWidth - 1 + 'px';
				}
				last = which;
			} else {
				els[which].className = els[which].className.replace(new RegExp(' header-menu-hover\\b'), '');
				last = -1;
			}
			timer = null;
		};
	};
	
	eventOver = function (num) {
		return function (e) {
			if (timer !== null) {
				window.clearTimeout(timer);
				timer = null;
			}
			if (last > -1 && last !== num) {
				els[last].className = els[last].className.replace(new RegExp(' header-menu-hover\\b'), '');
				last = -1;
			}
			showMe = true;
			timer = window.setTimeout(hideShow(num), 300);
		};
	};
	
	eventOut = function (num) {
		return function (e) {
			if (timer !== null) {
				window.clearTimeout(timer);
				timer = null;
			}
			showMe = false;
			timer = window.setTimeout(hideShow(num), 300);
		};
	};
	
	for (i = 0; i < els.length; i++) {
		els[i].onmouseover = eventOver(i);
		els[i].onmouseout = eventOut(i);
	}
}

/// Question and Answer
function qna() {
	var lastHash = null, containers = [], cookie, checkHash, eventOverOut, eventClick, qNaCurrent, theQuestion, i, objectList, cookieVal,
	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') {
					newValue += i + '|';
				}
			}
			cookie.setValue(newValue);
		};
	};
	
	// init this thing
	objectList = document.getElementById('page-content');
	if (objectList) {
		containers = getElementsByClassName(objectList, 'collapsible-content-question', 'div');
		if (containers.length > 0) {
			for (i = 0; i < containers.length; i++) {
				qNaCurrent = containers[i];
				
				// checks cookie to see which qna's were left open last time they were on this page
				cookieVal = cookie.getValue();
				if (cookieVal) {
					qNaCurrent.className += (cookieVal.match(i)) ? '' : ' hide-answer';
				} else {
					qNaCurrent.className += ' hide-answer';
				}
				
				theQuestion = getElementsByClassName(qNaCurrent, 'qna-question', 'div');
				if (theQuestion.length > 0) {
					theQuestion = theQuestion[0];
					theQuestion.onmouseover = eventOverOut();
					theQuestion.onmouseout = eventOverOut();
					theQuestion.onclick = eventClick();
				}
			}
			window.setInterval(checkHash(), 200);
		}
	}
}

// makes tabs work
function Tabs(tabsContainerId, tabContainerClass, tabNameClass, resizeTabs){
	var i, tabsContainer = document.getElementById(tabsContainerId), tabs, tabWidth, currentTab,
	tabClickHandler = function (self) {
		return function () {
			currentTab.parentNode.className = 'tab-enabled';
			self.parentNode.className = 'tab-active';
			currentTab = self;
			if (oldIE) {
				
			}
		};
	},
	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){
		tabs = getElementsByClassName(tabsContainer,tabNameClass, 'div');
		if(tabs.length > 0){
			if(resizeTabs){
				tabWidth = Math.floor(tabsContainer.offsetWidth / tabs.length);
				for(i = 0; i < tabs.length; i++){
					tabs[i].style.left	= (tabWidth * i) + 'px';
					tabs[i].style.width	= (tabWidth - 1) + 'px';
				}
				tabs[tabs.length-1].style.width = (tabsContainer.offsetWidth - (tabs.length - 1) * tabWidth - 2) + 'px';
			} 
			else {
				tabs[tabs.length-1].style.marginRight = '0';
			}
			for(i = 0; i < tabs.length; i++){
				if (tabs[i].parentNode.className !== 'tab-disabled') {
					tabs[i].onclick = tabClickHandler(tabs[i]);
					tabs[i].onmouseover = tabHoverHandler(true);
					tabs[i].onmouseout = tabHoverHandler(false);
					if(!currentTab){
						currentTab = tabs[i];
					}
				}
			}
			currentTab.parentNode.className = 'tab-active';
		}
		tabsContainer.className = tabContainerClass;
	}
}

function searchBox() {
	var input = document.getElementById('header-search-input'),
	focused = function (isFocus) {
		return function () {
			if (isFocus) {
				input.value = (trim(input.value) === 'search here') ? '' : input.value;
			} else {
				input.value = (trim(input.value) === '') ? 'search here' : input.value;
			}
		};
	};
	
	if (input) {
		input.onfocus = focused(true);
		input.onblur = focused(false);
	}
}

// Handles the rotation of the big promo images
function promoSwap() {
	var promos, i, timer, mouseOver, swapPromo, current = 0, last, fadeIn, fadeOpac = 1, fadeTimer = null,
	topPanel = document.getElementById('home-page-promos');
	
	// Starts and stops promo swapping when mouse is over current promo
	mouseOver = function (over) {
		return function () {
			if (over) {
				if (timer !== null) {
					window.clearTimeout(timer);
					timer = null;
				}
			} else {
				if (timer === null && fadeTimer === null) {
					timer = window.setTimeout(swapPromo(), 4000);
				}
			}
		};
	};
	
	// This handles the fading in for the next promo and resets variables so its ready for the next one
	fadeIn = function () {
		return function () {
			setOpacity(promos[current], fadeOpac);
			if (fadeOpac < 5) {
				fadeOpac++;
				fadeTimer = window.setTimeout(fadeIn(), 50);
			} else {
				setOpacity(promos[last], 0);
				promos[last].style.left = '-10000px';
				promos[last].style.zIndex = 5;
				promos[current].style.zIndex = 4;
				fadeOpac = 1;
				fadeTimer = null;
				timer = window.setTimeout(swapPromo(), 4000);
			}
		};
	};
	
	// This decides which promo should fade in next and calls the fader
	swapPromo = function (dir) {
		return function () {
			if (timer !== null) {
				last = current;
				if (dir) {
					this.blur();
					window.clearTimeout(timer);
					timer = null;
					if (dir > 0) {
						current = (current !== promos.length - 1) ? current + dir : 0;
					} else {
						current = (current !== 0) ? current + dir : promos.length - 1;
					}
				} else {
					current = (current !== promos.length - 1) ? current + 1 : 0;
				}
				promos[current].style.left = '0px';
				fadeTimer = window.setTimeout(fadeIn(), 50);
			}
		};
	};
	
	// init
	if (topPanel) {
		promos = topPanel.getElementsByTagName('img');
		if (promos.length > 1) {
			topPanel.className = 'show-buttons';
			for (i = 0; i < promos.length; i++) {
				promos[i].onmouseover = mouseOver(true);
				promos[i].onmouseout = mouseOver(false);
				if (i > 0) {
					setOpacity(promos[i], 0);
					promos[i].style.left = '-10000px';
					promos[i].style.zIndex = 5;
				} else {
					promos[i].style.left = '0px';
					promos[i].style.zIndex = 4;
				}
			}
			document.getElementById('home-page-promos-next').onclick = swapPromo(1);
			document.getElementById('home-page-promos-prev').onclick = swapPromo(-1);
			timer = window.setTimeout(swapPromo(), 4000);
		}
	}
}

function randomizeHeader(json) {
	var headImg, numToShow,
	imgUrl = 'http://lib.store.yahoo.net/lib/nycewheels/',
	randNum = Math.round(Math.random() * 100),
	headline = document.getElementById('header-headline'),
	percent = Math.floor(100 / json.length);
	
	if (headline && json.length > 0) {
		randNum = (randNum > 99) ? 99 : randNum;
		numToShow = Math.floor(randNum / percent);
		if (json[numToShow]) {
			headImg = headline.getElementsByTagName('img')[0];
			if (headImg) {
				headline.removeChild(headImg);
			}
			headImg = document.createElement('img');
			headImg.src = imgUrl + json[numToShow].image;
			headImg.alt = json[numToShow].alt;
			headline.appendChild(headImg);
		}
	}
}

function pageInit(){
	var mainProductImage = document.getElementById('product-main-image'),
	tabs = new Tabs('tabs','product-tabs','tab-name',true), 
	pictureGallery = new Tabs('picture-gallery','gallery','gallery-tab-name',false),
	videoGallery = new Tabs('video-gallery','gallery video-gallery','gallery-tab-name',false);
	
	if (mainProductImage) {
		mainProductImage.onclick = function () {
			tabs.showTab(2);
			pictureGallery.showTab(0);
		}
	}
	searchBox();
	promoSwap();
	qna();
	initHeaderMenu();
}
