var selectedPhoto;
var windowInfo = new Array();
var activePhotos = new Array();
var slideshowStatus = false;
var overlayStatus;
var hashCheck;
var si_slideShow;
var si_reCheckHash;

function getWindowInfo() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	windowInfo['h'] = myHeight;
	windowInfo['w'] = myWidth;
	windowInfo['vMid'] = myHeight/2;
	windowInfo['hMid'] = myWidth/2 + $(window).scrollLeft();
}

function markSelected() {
	var i = activePhotos.length;
	while (i--){
		if (windowInfo['hMid'] > $('.photo').get(activePhotos[i]).offsetLeft) {
			$('.photo.selected').removeClass("selected");
			$('.photo').eq(activePhotos[i]).addClass("selected");
			selectedPhoto = activePhotos[i];
			i = 0; // found selected, exit loop
		}
	}
	$('#debug').css("left",windowInfo['hMid']);
}

function scroll(_obj) {
	// main event
	if ($(_obj).parent().attr('class').indexOf('selected') > -1) {
		// if user clicked on active photo
		if (slideshowStatus){
			// if playing slideshow, pause
			playSlideshow(false);
		} else if (jQuery.inArray(selectedPhoto, activePhotos) >= activePhotos.length - 1) {
			// if at last photo, go to first
			scrollToFirst();
		} else {
			// go to next photo
			scrollToNext();
		}
	} else {
		// if user clicked on non active photo, go to that photo, pause slideshow just incase
		playSlideshow(false);
		var targetOffset = $(_obj).parent().get(0).offsetLeft - (windowInfo['w'] - $(_obj).parent().get(0).offsetWidth)/2;
		$('html,body').animate({scrollLeft: targetOffset}, scrollDelay);
	}
	toggleOverlay(false,'scroll');
}

function scrollToPhoto(photoIndex) {
	var targetOffset = $('.photo').get(photoIndex).offsetLeft - (windowInfo['w'] - $('.photo').get(photoIndex).offsetWidth)/2;
	$('html,body').animate({scrollLeft: targetOffset}, scrollDelay);
	toggleOverlay(false,'scrollToPhoto');
}

function scrollToFirst(){
	scrollToPhoto(activePhotos[0]);
}

function scrollToPrevious(){
	if (jQuery.inArray(selectedPhoto, activePhotos) <= 0)
		scrollToPhoto(activePhotos[activePhotos.length - 1]);
	else
		scrollToPhoto(activePhotos[jQuery.inArray(selectedPhoto, activePhotos) - 1]);	
}

function scrollToNext(){
	if (jQuery.inArray(selectedPhoto, activePhotos) >= activePhotos.length - 1)
		scrollToPhoto(activePhotos[0]);
	else
		scrollToPhoto(activePhotos[jQuery.inArray(selectedPhoto, activePhotos) + 1]);
}

function scrollToLast(){
	scrollToPhoto(activePhotos[activePhotos.length - 1]);
}

function repositionFilmstrip() {
	activePhotos = new Array();
	getWindowInfo();
	$('.photo').each(function(intIndex) {
		if($('.photo').eq(intIndex).css("display") != 'none')
			activePhotos.push(intIndex);
	});
	$('.filmstrip')[0].style.top = (windowInfo['h'] - $('.filmstrip').innerHeight())/2 + "px";
	$('.filmstrip')[0].style.paddingLeft = (windowInfo['w'] - $('.photo').eq(activePhotos[0]).innerWidth())/2 + "px";
	$('.filmstrip')[0].style.paddingRight = (windowInfo['w'] - $('.photo').eq(activePhotos[activePhotos.length - 1]).innerWidth())/2 + "px";
}

function playSlideshow(_status) {
	toggleOverlay(false, 'slideshow');
	slideshowStatus = _status;
	slideshowLoop();
	if (_status) {
		$('#slideshowToggle').html("Pause Slideshow");
		$('#slideshowToggle').attr("title","Pause Slideshow (space)");
		si_slideShow = setInterval("slideshowLoop()", slideshowDelay);
	} else {
		$('#slideshowToggle').html("Play Slideshow");
		$('#slideshowToggle').attr("title","Play Slideshow (space)");
		clearInterval(si_slideShow);
	}
}

function slideshowLoop() {
	if (slideshowStatus) {
		if (jQuery.inArray(selectedPhoto, activePhotos) >= activePhotos.length - 1)
			scrollToFirst();
		else
			scrollToNext();
	}
}

function toggleContact(_status) {
	$('a#contactToggle').addClass("selected");
	if(_status) {
		if (overlayStatus == 'contact' + selectedPhoto)
			_status = false;
		else
			$('#overlay > .container').html($('#contactDetails').html());
	}
	toggleOverlay(_status, 'contact');
}

function toggleInfo(_status) {
	$('a#infoToggle').addClass("selected");
	if(_status) {
		if (overlayStatus == 'info' + selectedPhoto) {
			_status = false;
		} else {
			if ($('.photo.selected > a > img').attr('title').length == 0)
				$('h1#photoTitle').html("<em style='color: #ccc;'>Untitled</em>");
			else
				$('h1#photoTitle').html($('.photo.selected > a > img').attr('title'));
			$('p#photoAlt').html($('.photo.selected > a > img').attr('alt'));
			if ($('.photo.selected > a > img').attr('title').length == 0)
				$('a#photoPermalink').html("this photo");
			else
				$('a#photoPermalink').html($('.photo.selected > a > img').attr('title'));
			if ($('.photo.selected > a > img').attr('rel').length == 0)
				$('span#tagList').html("<em>none</em>");
			else {
				$('span#tagList').html("");
				jQuery.each($('.photo.selected > a > img').attr('rel').split(", "), function(){
					$('span#tagList').append("<a href=\"#\" onclick=\"filterFilmstrip('" + this + "');\">" + this + "</a>");
					if (this != $('.photo.selected > a > img').attr('rel').split(", ")[$('.photo.selected > a > img').attr('rel').split(", ").length - 1])
						$('span#tagList').append(", ");
				});
			}
			$('a#photoPermalink').attr('href', "#" + (selectedPhoto + 1));
			$('p#photoCount').html("Photo " + (jQuery.inArray(selectedPhoto, activePhotos) + 1) + "/" + activePhotos.length);
			$('#overlay > .container').html($('#infoDetails').html());
		}
	}
	toggleOverlay(_status, 'info');
}

function toggleHelp(_status) {
	$('a#helpToggle').addClass("selected");
	if (_status) {
		if (overlayStatus == 'help' + selectedPhoto)
			_status = false;
		else
			$('#overlay > .container').html($('#helpDetails').html());
	}
	toggleOverlay(_status, 'help');
}

function toggleOverlay(_status, _caller) {
	if (_status) {
		$('#overlay').removeClass("hidden");
		repositionOverlay();
		overlayStatus = _caller + selectedPhoto;
	} else {
		$('ul#footerNavigation > li > a.selected').removeClass("selected");
		$('#overlay').addClass("hidden");
		overlayStatus = '';
		$('#overlay > .container').html("");
	}
}

function repositionOverlay() {
	$('#overlay').css("width",$('.photo.selected > a > img').outerWidth() + "px");
	$('#overlay').css("height",$('.photo.selected > a > img').outerHeight() + "px");
	$('#overlay').css("left",$('.photo.selected > a > img').get(0).offsetLeft + "px");
	$('#overlay').css("top",$('.filmstrip').get(0).offsetTop + "px");
}

function checkHash() {
	if (location.hash.length > 0 && location.hash != hashCheck && !isNaN(location.hash.substring(1,location.hash.length))) {
		scrollToPhoto((location.hash.substring(1,location.hash.length) - 1));
		hashCheck = location.hash;
	}
}

function filterFilmstrip(_tag) {
	$('ul#tagNavigation > li > a.selected').removeClass("selected");
	if (_tag === false) {
		$('.photo').css("display","inline");
		$('ul#tagNavigation > li > a:last').eq(0).addClass("selected");
	} else {
		$('.photo').each(function(intIndex) {
			if($('.photo').eq(intIndex).children().children().eq(0).attr('rel').indexOf(_tag) > -1)
				$('.photo').eq(intIndex).css("display","inline");
			else
				$('.photo').eq(intIndex).css("display","none");
		});
	}
	$('ul#tagNavigation > li > a').each(function(intIndex){
		if($('ul#tagNavigation > li > a').eq(intIndex).html().toLowerCase() == _tag) {
			$('ul#tagNavigation > li > a').eq(intIndex).addClass("selected");
		}
	});
	toggleOverlay(false, 'filterFilmstrip');
	repositionFilmstrip();
	markSelected();
}

function debug() {
	$('#debug').toggleClass('hidden');
}

function init() {
	// setup the ui
	$('#photos > ul.filmstrip > li').addClass('photo');
	$('.photo > a').click(function(){
		scroll(this);
		return false;
	});
	$('#slideshowToggle').click(function(){
		playSlideshow(!slideshowStatus);
		return false;
	});
	$('a#contactToggle').click(function(){
		toggleContact(true); 
		return false;
	});
	$('a#infoToggle').click(function(){
		toggleInfo(true); 
		return false;
	});
	$('a#helpToggle').click(function(){
		toggleHelp(true); 
		return false;
	});
	
	// setup the ux
	$('.photo > a').each(function(intIndex){
		$(this).attr('href','#' + (intIndex + 1));
		$(this).attr('name',intIndex + 1);
	});
	$(window).scroll(function () {
		getWindowInfo();
		markSelected();
	});
	$(window).resize(function () {
		repositionFilmstrip();
		repositionOverlay();
	});
	$(window).load(function () {
		repositionFilmstrip();
	});
    $(document).keypress(function (e) {
    	switch ((e.keyCode ? e.keyCode : e.which)) {
    		case 106:
    		case 37:
    			// j or [left]: previous
    			scrollToPrevious();
    			break;
    		case 107:
    		case 39:
    			// k or [right]: next
    			scrollToNext();
    			break;
    		case 32:
    			// space: play/pause
    			playSlideshow(!slideshowStatus);
    			break;
    		case 105:
    			// i: image info;
    			toggleInfo(true);
    			break;
    		case 99:
    			// c: contact form;
    			toggleContact(true);
    			break;
    		case 63:
    			// ?: help;
    			toggleHelp(true);
    			break;
    		case 102:
    			// f: first;
    			scrollToFirst();
    			break;
    		case 108:
    			// l: last;
    			scrollToLast();
    			break;
    		case 100:
    			// d: debug;
    			// debug();
    			break;
    	}
	});

    // start things off
	repositionFilmstrip();
	checkHash(); 
	markSelected();
	si_reCheckHash = setInterval("checkHash()", 200); 
}