var currLevel = 0;
var arrowDirection = 0;
var container;
var loadedPages = {};
var loadedPagesCount = 0;
var loadedImages = [];
$(function() {
	
	container = $('#container');
	$(window).resize(windowResize);
	windowResize();

	$('#navigation > ul > li').mouseenter(function() {
		if ($('#navigation').hasClass('hidden')) return;
		var $this = $(this);
		clearTimeout($this.attr('_timer'));
		$this.attr('_count', parseInt($this.attr('_count')) + 1);
		if (! $this.hasClass('showing')) {
			hideSubNav($this.siblings('li.showing'));
			$this.addClass('showing');
			$this.find('ul').css('display', 'block').animate({opacity: 1}, 500)
			.find('li').animate({marginLeft: 0}, 500);
		}
	}).mouseleave(function() {
		var $this = $(this);
		var count = parseInt($this.attr('_count')) - 1;
		$this.attr('_count', count);
		if (count <= 0) {
			$this.attr('_timer', setTimeout(function() {
				count = parseInt($this.attr('_count'));
				if (count <= 0 && $this.hasClass('showing')) {
					$this.attr('_count', 0);
					hideSubNav($this);
				}
			}, 1000));
		}
		
	}).attr('_count', 0);

	if ($('body').hasClass('home')) setupHomeRots();

	$('#newsMail').focus(function() {
		var $this = $(this);
		if ($this.val() == 'Submit email address') $this.val('');
	}).blur(function() {
		var $this = $(this);
		if ($.trim($this.val()) == '') $this.val('Submit email address');
	});
	$('#menu').click(function() {
		var nav = $('#navigation');
		if (nav.hasClass('hidden')) {
			showNav();
		} else {
			hideNav();
		}
	});
	$('#navigation, #boilerplate').find('a').click(function() {
		if ($(this).attr('href') != '#') {
			if ($(this).hasClass('external')) {
				return true;
			}
			location.hash = $(this).attr('href');
			$('#navigation li.showing').each(function() {hideSubNav($(this));}).attr('_count', 0)
				.find('ul').css('display', 'none');
		} else if (this.id == 'logo') {
			location.hash = 'home';
		}
		return false;
	});
	var currHash = '';
	(function checkHash() {
		try {
			var newHash = location.hash.replace('#', '');
			if (currHash != newHash) {
				if (newHash == '' || newHash == 'home') {
					newHash = '';
					returnHome();
				} else {
					leaveHome();
					try {
    					_gaq.push(['_trackPageview', newHash]);
					} catch(e) {}
					if (loadedPages[newHash]) {
						loadPage(loadedPages[newHash]);
					} else {
						$.ajax({url: newHash, data: {js: true}, dataType: 'html'}).success(function(html) {
							loadedPages[newHash] = html;
							loadedPagesCount++;
							if (loadedPagesCount > 20) {
								for (key in loadedPages) {
									delete loadedPages[key];
									loadedPagesCount--;
									break;
								}
							}
							loadPage(html);
						});
					}
				}
				currHash = newHash;
			}
		} catch (e) {}
		setTimeout(checkHash, 100);
	})();
	wireLinks();
});

var imgWidth = 960;
var imgHeight = 612;
var imgRatio = imgWidth / imgHeight;
function windowResize() {
	var winWidth = $(window).width();
	if (winWidth < imgWidth) winWidth = imgWidth;
	var winHeight = $(window).height();
	if (winHeight < imgHeight) winHeight = imgHeight;
	var winRatio = winWidth / winHeight;
	var currImg = $('#background img, img.bgImage');
	var newHeight = 0;
	var newWidth = 0;
	if (winRatio <= imgRatio) {
		newHeight = winHeight;
		newWidth = imgWidth * (newHeight / imgHeight);
		currImg.css({width: newWidth, height: newHeight, top: 0, left: (winWidth - newWidth) / 2});
	} else {
		newWidth = winWidth;
		newHeight = imgHeight * (newWidth / imgWidth);
		currImg.css({width: newWidth, height: newHeight, left: 0, top: (winHeight - newHeight) / 2});
	}
	$('#navigation ul ul').css('width', winWidth - 232);
	$('div.body, div.page').css({width: container.width(), height: container.height()});
	updateStretchy();
} 

function hideSubNav(nav) {
	nav.removeClass('showing');
	nav.find('ul').stop().animate({opacity: 0}, 500, function() {$(this).css('display', 'none');});
	nav.find('li').stop().animate({marginLeft: -1000}, 500);
}
function showNav() {
	var nav = $('#navigation');
	if (nav.hasClass('hidden')) {
		nav.animate({left: 0}, 350, function() {
			nav.animate({left: -6}, 100);
		});
		nav.removeClass('hidden');
	}
}
function hideNav() {
	var nav = $('#navigation');
	if ( ! nav.hasClass('hidden')) {
		nav.animate({left: -172}, 350, function() {
			nav.animate({left: -166}, 100);
		});
		nav.addClass('hidden');
	}
}
var runHomeRots = false;
function setupHomeRots() {
	runHomeRots = true;
	var firstRot = true;
	(function homeRotate() {
		if (! runHomeRots) return;
		if (!firstRot) {
			rotateBgImage();
		} else {
			firstRot = false;
		}
		setTimeout(homeRotate, 20000);
	})();
}
function rotateBgImage() {
	var currImg = $('#background').find('img.current');
	var nextImg = currImg.next('img:first');
	if (nextImg.length == 0) nextImg = $('#background').find('img:first');
	nextImg.css({left: currImg.css('left'), top: currImg.css('top'), width: currImg.css('width'),
		height: currImg.css('height') 
	});
	if ($.support.transition) {
		currImg.removeClass('current');
		nextImg.addClass('current');
	} else {
		currImg.animate({opacity: 0}, 1000);
		nextImg.animate({opacity: 1}, 1000, function() {
			currImg.removeClass('current');
			nextImg.addClass('current');
		});
	}
}
function startLoading() {
	$('#screen, #loading').css('display', 'block');
}
function endLoading() {
	$('#screen, #loading').css('display', 'none');
}
function leaveHome() {
	if ($('body').hasClass('home')) {
		$('#newsSub, #homeCopy').animate({top: 600}, 500, function() { $('#footer').hide(); });
		$('#arrows, #productLinks').animate({right: 55}, 300, function() {$(this).animate({right: 45}, 100);});
		$('#breadcrumbs').animate({top: 34}, 300);
		$('body').removeClass('home');
		runHomeRots = false;
		hideNav();
	}
}
function returnHome() {
	if (! $('body').hasClass('home')) {
		try {
   			_gaq.push(['_trackPageview', '/']);
		} catch(e) {}
		$('#footer').show();
		$('#newsSub, #homeCopy').animate({top: 0}, 500);
		$('#arrows').animate({right: 55}, 100, function() {$(this).animate({right: -93}, 300);});
		$('#productLinks').animate({right: 55}, 100, function() {$(this).animate({right: -600}, 300);});
		$('#breadcrumbs').animate({top: -20}, 300);
		$('body').addClass('home');
		showNav();
		setupHomeRots();
		$('div.page.current, div.page.currReq').css({'left': 0, 'right': 'auto'}).animate({'left': container.width()}, 500, function() {
			$(this).remove();
		});
		$('#topNav, #footer').removeClass('blackAll');
		currLevel = 0;
	}
}

function loadPage(html) {
	endLoading();
	html = $(html);
	var newPage = html.filter('div.page');
	var currPage = $('div.page.current');
	if (newPage.attr('id') == currPage.attr('id')) return; // already current page

	$('#arrows').replaceWith(html.filter('#arrows'));
	$('#arrows').find('a').click(function() {
		var $this = $(this);
		if ($this.hasClass('left')) {
			arrowDirection = -1;
		} else {
			arrowDirection = 1;
		}
		if ($this.attr('href') != '#') {
			location.hash = $this.attr('href');
		}
		return false;
	});
	$('#productLinks').replaceWith(html.filter('#productLinks'));
	$('#arrows').before(newPage);
	newPage = $('#' + newPage.attr('id'));
	newPage.css({'width': container.width(), 'height': container.height()});
	if (currLevel > newPage.attr('level') || (currLevel == newPage.attr('level') && arrowDirection == -1)) {
		newPage.css({'right':  container.width(), 'left': 'auto'}).addClass('current unwired').animate({right: 0}, 500);
		currPage.removeClass('current').css({'right': 0, 'left': 'auto'}).animate({right: -container.width()}, 700, function() {$(this).remove();});
	} else {
		newPage.css({'left':  container.width()}).addClass('current unwired').animate({left: 0}, 500);
		currPage.removeClass('current').css({'right': 'auto', 'left': 0}).animate({left: -container.width()}, 700, function() {$(this).remove();});
	}
	$('#breadcrumbs').replaceWith(html.filter('#breadcrumbs'));
	if ($('#breadcrumbs').hasClass('right')) {
		$('#cartInfo').css('display', 'none');
	} else {
		$('#cartInfo').css('display', 'block');
	}
	if (newPage.hasClass('blackAll')) {
		$('#topNav, #footer, #cartInfo').addClass('blackAll');
	} else {
		$('#topNav, #footer, #cartInfo').removeClass('blackAll');
	}
	setTimeout(wireLinks, 1000);
	arrowDirection = 0;
	currLevel = newPage.attr('level');
	if (newPage.attr('bg')) showBackground(newPage);
	$('a.faqLink').click(function() {
		var $this = $(this);
		$this.parents('div.copyContainer').animate({top: -$('.' + $this.attr('linkTo')).position()['top']}, 300);
		return false;
	});
}

function showBackground(page) {
	var names = page.attr('bg').split(',');
	var showingCount = 0;
	for (var x=0; x < names.length; x++) {
		var imgName = 'http://static.zuaudio.com/images/products/background/' + names[x] + '.jpg';
		if ($.inArray(imgName, loadedImages) > -1) {
			showNow(imgName);
		} else {
			var img = $(new Image());
			img.load(function() {
				loadedImages.push($(this).attr('src'));
				showNow($(this).attr('src'));
			}).attr('src', imgName);
		}
	}
	function showNow(img) {
		if (page.hasClass('current')) {
			var hideClass = ' hidden';
			if (showingCount == 0) hideClass = ' current';
			page.prepend('<img src="' + img + '" class="bgImage' + hideClass + '" />');
			var bgImage = page.find('img.bgImage');
			bgImage.css({'left': container.width()});
			var winWidth = $(window).width();
			if (winWidth < imgWidth) winWidth = imgWidth;
			var winHeight = $(window).height();
			if (winHeight < imgHeight) winHeight = imgHeight;
			var winRatio = winWidth / winHeight;
			var newHeight = 0;
			var newWidth = 0;
			var left = 0;
			if (winRatio <= imgRatio) {
				newHeight = winHeight;
				newWidth = imgWidth * (newHeight / imgHeight);
				bgImage.css({width: newWidth, height: newHeight, top: 0});
				left = (winWidth - newWidth) / 2;
			} else {
				newWidth = winWidth;
				newHeight = imgHeight * (newWidth / imgWidth);
				bgImage.css({width: newWidth, height: newHeight, top: (winHeight - newHeight) / 2});
			}
			if (page.hasClass('unwired')) {
				bgImage.css({left: left});
			} else {
				bgImage.animate({left: left}, 500);
			}
			showingCount++;
			if (names.length > 1 && showingCount == names.length) {
				var first = true;
				(function rotImgs() {
					if (first) {
						first = false;
					} else {
						if (!page.hasClass('current')) return;
						var currImg = page.find('img.bgImage.current');
						var nextImg = currImg.next('img:first');
						if (nextImg.length == 0) {
							nextImg = page.find('img.bgImage:first');
							nextImg.css('opacity', 1).removeClass('hidden').addClass('current');
							currImg.removeClass('current').animate({opacity: 0}, 1000);
						} else {
							nextImg.css('opacity', 0).removeClass('hidden').addClass('current').animate({opacity: 1}, 1000, function() {
								currImg.removeClass('current').css('opacity', 0);
							});
						}
					}
					setTimeout(rotImgs, 5000);
				})();
			}
		}
	}
}

function wireLinks() {

	updateStretchy();

	$('div.prodDesc').mouseenter(function() {
		$(this).find('div.background').stop().animate({opacity: 0.5}, 300);
	}).mouseleave(function() {
		$(this).find('div.background').stop().animate({opacity: 0}, 300);
	})
	.each(wireCopyBlock);
	$('#breadcrumbs').find('a').click(function() {
		var $this = $(this);
		if ($this.attr('href') != '#') {
			location.hash = $this.attr('href');
		}
		return false;
	});
	$('#thumbnails').find('a').each(function() {
		var link = $(this);
		if (link.find('img').length > 1) {
			link.mouseenter(function() {
				if (link.attr('_over') != 'true' && link.attr('_running') == 'false') {
					link.attr({'_over': 'true', '_running': 'true'});
					(function rotThumbs() {
						var curr = link.find('img.current');
						var next = curr.next();
						if (link.attr('_over') == 'false') {
							link.attr('_running', 'false');
							next = link.find('img.primary');
							if (next.hasClass('current')) return;
						} else if (next.length == 0) next = link.find('img:first');
						if ($.support.opacity) {
							curr.stop().animate({opacity: 0}, 500).removeClass('current');
							next.stop().animate({opacity: 1}, 300).addClass('current');
						} else {
							curr.css('opacity', 0).removeClass('current');
							next.stop().css('opacity', 1).addClass('current');
						}
						setTimeout(rotThumbs, 750);
					})();
				}
			}).mouseleave(function() {
				$(this).attr('_over', 'false');
			}).attr({'_over': 'false', '_running': 'false'});
		}
	});
	$('a.popup').each(function() {
		var winHeight = $(window).height();
	    var height = 900 > winHeight ? winHeight : 900;
		var width = height == 900 ? 649 : 649 * ((height - 92) / (900 - 92)); // the funky 92 removes the bottom panel
		if ($(this).hasClass('grouped')) {
			$('a[rel=' + $(this).attr('rel') + ']').colorbox({width: width, height: height});
		} else {
			$(this).colorbox({width: width, height: height});
		}
	});

	$('#container a.prodInfo, #productLinks a').click(function() {
		if ($(this).attr('href') != '#') {
			location.hash = $(this).attr('href');
			$('#navigation li.showing').each(function() {hideSubNav($(this));}).attr('_count', 0)
				.find('ul').css('display', 'none');
		}
		return false;
	});
	$('a.buyNow, #cartInfo').click(function() {
		alert("Thank you for your interest.\n\nWe will be selling again online very soon!!\n\nIn the meantime please give us a call at 800-516-8925.");
		return false;
	});
	$('#aboutBlock').each(function() {
		var links = $(this).find('a');
		links.mouseenter(function() {
			var overlay = $(this).find('div.overlay');
			var name = $(this).find('span');
			overlay.stop().fadeTo(300, 0.80);
			name.stop().animate({left: 0}, 300);
		}).mouseleave(function() {
			var overlay = $(this).find('div.overlay');
			var name = $(this).find('span');
			overlay.stop().fadeOut(300);
			name.stop().animate({left: 167}, 300, function() {$(this).css('left', -167);});
		});
		var delay = 300;
		links.find('div.overlay').hide();
		links.find('span').each(function() {
			var $this = $(this);
			setTimeout(function() {
				$this.animate({left: 167}, 900, 'linear', function() {$this.css('left', -167)});
			}, delay);
			delay += 600;
		});
	});
	$('div.unwired').removeClass('unwired');
}

function wireCopyBlock() {
	var $this = $(this);
	if ($this.find('div.copyContainer').height() <= $this.find('div.prodCopy').height()) {
		$this.find('div.prodArrows').hide();
	} else {
		$this.find('a.prodArrowUp').attr({'_scroller': 'stopped', '_accelerate': 'false'}).mouseover(function() {
			var btn = $(this);
			if (btn.attr('_scroller') == 'stopped') {
				btn.attr('_scroller', setInterval(function() {
					scrollUp(btn, $this.find('div.copyContainer'));
				}, 25));
			}
		}).mouseout(function() {
			var btn = $(this);
			if (btn.attr('_scroller') != 'stopped') {
				clearInterval(btn.attr('_scroller'));
				btn.attr('_scroller', 'stopped');
			}
		}).mousedown(function() {
			$(this).attr('_accelerate', 'true');
			return false;
		}).mouseup(function() {
			$(this).attr('_accelerate', 'false');
			return false;
		}).click(function() {
			return false;
		});
		$this.find('a.prodArrowDown').attr({'_scroller': 'stopped', '_accelerate': 'false'}).mouseover(function() {
			var btn = $(this);
			if (btn.attr('_scroller') == 'stopped') {
				btn.attr('_scroller', setInterval(function() {
					scrollDown(btn, $this.find('div.prodCopy'));
				}, 25));
			}
		}).mouseout(function() {
			var btn = $(this);
			if (btn.attr('_scroller') != 'stopped') {
				clearInterval(btn.attr('_scroller'));
				btn.attr('_scroller', 'stopped');
			}
		}).mousedown(function() {
			$(this).attr('_accelerate', 'true');
			return false;
		}).mouseup(function() {
			$(this).attr('_accelerate', 'false');
			return false;
		}).click(function() {
			return false;
		});
		$this.find('div.copyContainer').mousewheel(function(evt, delta) {
			delta = delta * 10;
			var list = $(this);
			var top = parseInt(list.css('top'));
			var height = list.parent().height() - list.height();
			if (delta < 0) {
				if (height < top) {
					if (delta + top < height) delta = height - top;
					list.css('top', top + delta);
				}
			} else {
				if (0 > top) {
					if (delta + top > 0) delta = -top;
					list.css('top', top + delta);
				}
			}
			return false;
		});
	}
}

function scrollUp(btn, cc) {
	var top = parseInt(cc.css('top'));
	if (btn.attr('_accelerate') == 'true') {
		top = top + 10;
	} else {
		top = top + 2;
	}
	if (top >= 0) {
		top = 0;
		clearInterval(btn.attr('_scroller'));
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
	}
	cc.css('top', top);
}
function scrollDown(btn, container) {
	var containerHeight = container.height();
	var cc = container.find('div.copyContainer');
	var top = parseInt(cc.css('top'));
	var ccHeight = cc.height();
	if (btn.attr('_accelerate') == 'true') {
		top = top - 10;
	} else {
		top = top - 2;
	}
	if (top <= (containerHeight - ccHeight)) {
		top = containerHeight - ccHeight;
		clearInterval(btn.attr('_scroller'));
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
	}
	cc.css('top', top);
}
// note that a stretchy div should only be at the end of content or you'll screw up your layout
function updateStretchy() {
	var stretchy = $('div.stretchy');
	if (stretchy.length > 0) {
		var maxHeight = container.height() - 40; // 20 for page padding + 35 for stretchy padding/margin
		var top = 92 + stretchy.position()['top'];
		var currHeight = stretchy.height();
		var addHeight = maxHeight - (top + currHeight);
		stretchy.css('height', currHeight + addHeight);
		var inner = stretchy.find('div.prodCopy')
		inner.css('height', inner.height() + addHeight);
	}
}

$.support.transition = (function(){ 
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support = thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.OTransition !== undefined || thisStyle.transition !== undefined;
    
    return support; 
})();
