var leftNav;
var History;
var currLoadingUrl = '';
(function(window, undefined) {
	History = window.History;

	try{
	History.Adapter.bind(window, 'statechange', function() {
		var state = History.getState();
		if (typeof state.data.section === 'undefined') state.data.section = 'home';

		setTitle(state.title);
		if (state.data.section != currSection) {
			$('body').addClass('loading');
			changeSections(state.data.section);

			$('#content').find('div.page').animate({left: -$(window).width()}, 500, function() { $(this).remove(); });
			currLoadingUrl = state.url;
			$.ajax({
				url: state.url, 
				cache: (state.data.section != 'home' && !$.browser.msie), 
				context: this,
				dataType: 'html', 
				success: function(html) {
					// safety check to see if we're still in the right state to display
					if (currLoadingUrl != state.url) return;
					$('#content').append(html);
					$('#content').find('div.page:last').css('left', $(window).width()).animate({left: 0}, 500, function() {
						$('body').removeClass('loading');
						$.publish('section_change_complete', [state.data.section]);
					});
				},
				error: function() { location.reload(true); }

			});
		} else {
			$.publish('sub_section_change', [state]);
		}
		try {
   			_gaq.push(['_trackPageview', state.url]);
		} catch(e) {}
	});
	} catch(e) {}
})(window);
$(function() {

	$(window).resize(checkWinSize);
	checkWinSize();

	setupLeftNav();
	$.subscribe('section_change', function(sections) {
		if (navHideable()) {
			hideLeftNav();
		} else {
			showLeftNav();
		}
		$('body').removeClass(sections['old']).addClass(sections['new']);
	});

	$('#collectionInfo').mouseenter(showLookInfo).mouseleave(hideLookInfo).click(toggleLookInfo);

	if (typeof firstSetup === 'function') {
		firstSetup();
	} else if (typeof firstSetup === 'object') {
		for (var x in firstSetup) {
			firstSetup[x]();
		}
	}
	if (navHideable()) setTimeout(hideLeftNav, 1000);
	if (currSection != 'home') $.publish('section_change_complete', [currSection]);

	$('#leftArrow').click(function() {
		var prev = $('#collectionBody').find('div.current').prev('div.look');
		if (prev.length == 0) prev = $('#collectionBody').find('div.look:last');
		History.pushState({section:'collection'}, prev.attr('title'), prev.attr('data-url'));
		return false;
	});
	$('#rightArrow').click(function() {
		var next = $('#collectionBody').find('div.current').next('div.look');
		if (next.length == 0) next = $('#collectionBody').find('div.look:first');
		History.pushState({section:'collection'}, next.attr('title'), next.attr('data-url'));
		return false;
	});
	$('#zoom').click(function() {
		$('body').append('<div id="zoomBox"/>');
		var src = $('#collectionBody').find('div.current').attr('data-zoom');
		if (!src) src = $('#collectionBody').find('div.current').find('img').attr('src');
		var scroller = false;

		$('body').addClass('loading');
		var img = $(new Image());
		img.load(function() {
			// scale up the image explicitly for IE
			if ($.browser.msie && $.browser.msie <= 8) {
				var width = $('#zoomBox').width();
				var height = this.height * (width / this.width);
				img.css({opacity: 0, height: height});
			} else {
				img.css({opacity: 0});
			}
			$('#zoomBox').append(img);
			img.animate({opacity: 1}, 300, function() {
				if (isiPad || isMobile()) {
					scroller = new iScroll('zoomBox');
				}
				$('#zoomBox').append('<a href="#" id="zoomClose"></a>');
				$('#zoomClose').click(function() {
					if (scroller) {
						scroller.destroy();
						scroller = false;
					}
					$('#zoomBox').remove();
					return false;
				});
				$('body').removeClass('loading');
			});
		}).attr('src', src);
		return false;
	});
});
function setTitle(newTitle) {
	if (typeof newTitle !== 'undefined' && newTitle != '') {
		document.title = newTitle + ' : ' + siteTitle;
	} else {
		document.title = siteTitle;
	}
}
function setupLeftNav() {
	leftNav = $('#leftNav');
	leftNav.mouseenter(showLeftNav).mouseleave(function() {
		if (navHideable()) hideLeftNav();
	});
	if (leftNav.height() > 0) leftNav.addClass('expanded');
	leftNav.find('a').click(function() {
		$this = $(this);
		if (!$this.hasClass('current')) {
			History.pushState({section:this.id}, $this.text(), $this.attr('href'));
		}
		return false;
	});
	$('#expandLeftNav').mouseenter(showLeftNav).click(function() {showLeftNav();return false;});
	var leftLinks = $('#leftLinks');
	leftNav.height(leftNav.height()).data({
		fullHeight: leftNav.height(),
		shortHeight: leftLinks.find('a:first').height() + parseInt(leftLinks.css('margin-bottom'))
	});
	var linksHeight = leftNav.height() - parseInt(leftLinks.css('margin-bottom'));
	leftLinks.css({position: 'absolute', top: leftNav.css('padding-top'), 
		left: leftNav.css('padding-left'), right: leftNav.css('padding-right'), bottom: 0,
		height: linksHeight
	}).data({fullHeight: linksHeight, shortHeight: leftLinks.find('a:first').height()});
	var allLinks = leftLinks.find('a');
	var currCount = 0;
	var pctEach = 100 / allLinks.length;
	allLinks.each(function() {
		$(this).css({position: 'absolute', top: (currCount * pctEach) + '%'})
			.data('pct', currCount * pctEach);
		currCount++;
	});
}

function showLeftNav() {
	if (!leftNav.hasClass('expanded')) {
		leftNav.stop().addClass('expanded').animate({height: leftNav.data('fullHeight') + 15}, 250, function() {
			leftNav.animate({height: leftNav.data('fullHeight')}, 75);
		});
		$('#leftLinks').stop().animate({height: $('#leftLinks').data('fullHeight') + 15}, 250, function() {
			$(this).animate({height: $(this).data('fullHeight')}, 75);
		});
		leftNav.find('a.left:not(.current)').stop().each(function() {
			$(this).css('top', $(this).data('pct') + '%');
		}).animate({left: 10}, 250, function() {
			$(this).animate({left: 0}, 75);
		});
		leftNav.find('a.right:not(.current)').stop().each(function() {
			$(this).css('top', $(this).data('pct') + '%');
		}).animate({left: -10}, 250, function() {
			$(this).animate({left: 0}, 75);
		});
		var curr = leftNav.find('a.current');
		curr.css('top', curr.data('pct') + '%');
	}
}
function hideLeftNav() {
	if (leftNav.hasClass('expanded')) {
		leftNav.stop().removeClass('expanded').animate({height: leftNav.data('fullHeight') + 15}, 75, function() {
			leftNav.animate({height: leftNav.data('shortHeight')}, 250);
		});
		$('#leftLinks').stop().animate({height: $('#leftLinks').data('fullHeight') + 15}, 75, function() {
			$(this).animate({height: $(this).data('shortHeight')}, 250);
		});
		leftNav.find('a.left:not(.current)').stop().each(function() {
			$(this).css('top', $(this).data('pct') + '%');
		}).animate({left: 10}, 75, function() {
			$(this).animate({left: -163}, 250);
		});
		leftNav.find('a.right:not(.current)').stop().each(function() {
			$(this).css('top', $(this).data('pct') + '%');
		}).animate({left: -10}, 75, function() {
			$(this).animate({left: 163}, 250);
		});
		leftNav.find('a.current').stop().animate({top: 0}, 325);
	}

}
function hideLeftNavItem(item, section) {
	if (item.attr('id') == 'home' || isiPad || isMobile()) return;
	var postAnim = function() {
		item.css('top', item.attr('data-pct') + '%');
	}
	if (section != 'home') {
		if (item.hasClass('left')) {
			item.stop().animate({left: -163}, 250, postAnim);
		} else {
			item.stop().animate({left: 163}, 250, postAnim);
		}
	} else {
		postAnim();
	}
}
function showLeftNavItem(item) {
	if (item.attr('id') == 'home' || isiPad || isMobile()) return;
	item.stop().animate({top: 0, left: 10}, 250);
}
function showLookInfo() {
	var info = $('#collectionInfo');
	if (!info.hasClass('expanded')) {
		info.addClass('expanded').stop().animate({height: info.height() + $('#lookDetails').find('div').height() + 10}, 300, function() {
			info.animate({height: info.height() - 10}, 75);
		});
	}
}
function hideLookInfo() {
	var info = $('#collectionInfo');
	if (info.hasClass('expanded')) {
		info.removeClass('expanded').addClass('animating').stop().animate({height: info.height() - $('#lookDetails').find('div').height() - 9}, 300, function() {
			info.animate({height: info.height() + 5}, 75, function() {$(this).removeAttr('style');});
		});
	}
}
function toggleLookInfo() {
	var info = $('#collectionInfo');
	if (info.is(':animated')) return;
	if (info.hasClass('expanded')) {
		hideLookInfo();
	} else {
		showLookInfo();
	}
}

function navHideable(section) {
	if (isiPad || isMobile()) return false;
	if (!section) section = currSection;
	return section != 'home';
}
// should call this when changing sections so events get fired properly
function changeSections(newSection) {
	if (newSection != '' && newSection != currSection) {
		var oldItem = $('#' + currSection).removeClass('current');
		hideLeftNavItem(oldItem, newSection);
		var newItem = $('#' + newSection).addClass('current');
		showLeftNavItem(newItem);
		var args = {'old': currSection, 'new': newSection};
		currSection = newSection;

		if (navHideable()) {
			hideLeftNav();
		} else {
			showLeftNav();
		}

		$.publish('section_change', [args]);
	}
}
function isMobile(){
	var ua = navigator.userAgent.toLowerCase();
    return (
        //Detect iPhone
        (navigator.platform.indexOf('iPhone') != -1) ||
        //Detect iPod
        (navigator.platform.indexOf('iPod') != -1) ||
        //Detect Android
        (ua.indexOf('android') > -1)
    );
}
function checkWinSize() {
	if (isiPad) {
		$('body').addClass('ipad').removeClass('small');
		 setTimeout(function() {
            window.scrollTo(0, 1);
        }, 100);
		return;
	} else if (isMobile()) {
		$('body').addClass('iphone');
		 setTimeout(function() {
            window.scrollTo(0, 1);
        }, 100);
		return;
	}
	if ($(window).width() < 960 || $(window).height() < 690) {
		$('body').addClass('small');
	} else {
		$('body').removeClass('small');
	}
}

function checkImageSize() {
	var $this = $(this);
	var imgRatio = $this.width() / $this.height();
	if ($this.width() > 0 && $this.height() > 0) {
		// need to scale
		var winHeight = $('#main').height();
		var winWidth = $('#main').width();
		var winRatio = winWidth / winHeight;

		var newWidth = 0;
		var newHeight = 0;
		var scaleBy = 'width';
		if (winRatio <= imgRatio) {
			var widthDiff = winWidth - $this.width();
			$this.css('left', widthDiff / 2);
		} else {
			$this.css('left', 'auto');
		}
	}
}
var scrollWidth = -1;
function scrollbarWidth() { 
	if (scrollWidth == -1) {
		var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>'); 
		$('body').append(div); 
		var w1 = $('div', div).innerWidth(); 
		div.css('overflow-y', 'scroll'); 
		var w2 = $('div', div).innerWidth(); 
		$(div).remove(); 
		scrollWidth = (w1 - w2); 
	}
	return scrollWidth;
}

