/*
 * constants
 */
var DEBUG_MODE = true;
var URL_GET_DIR_LISTING = "com/php/get_dir_listing.php";
var DIR_ROOT_IMAGES = "assets/images";
var THUMB_OVER_COLOR = '#fcaf17';
var THUMB_OUT_COLOR = THUMB_UP_COLOR;
var THUMB_UP_COLOR = '#ffffff';
var THUMB_DOWN_COLOR = '#ffffff';
var APPEAR_DURATION = 100;
var HASH_INDEX = 'index';
var HASH_THUMBS_PRE = 'thumbs&';
var LOAD_MSG_ALBUMS = 'Loading Albums...';
var LOAD_MSG_THUMBS = 'Loading Album Content...';
var MODE_VIEW_PAGES = "viewPages";
var MODE_VIEW_ALL = "viewAll";
var MSG_DISABLED = "This button is disabled";
var MSG_NO_CONTENT = "Nothing here, <a onclick='history.back();'>go back</a>";
var VOS_PER_PAGE = 30;

/*
 * global variables
 */

var imagesXML = '';
var albumsXML = '';
var thumbnails = new Array();
var albums = new Array();
var currentVOs = new Array();
var thumbIndex = -1;
var albumIndex = -1;
var viewIndex = -1;
var pageIndex = -1;
var canFade = true;
var showingOverlay = false;
var showingAlbums = false;
var gettingRootAlbums = false;
var viewMode = MODE_VIEW_PAGES;

/*
 * on document ready
 */
$(function() {
	
	init();

});

function init()
{
	getBrowser();
	
	getInitHash();
	
	//browser history plugin
	$(window).history(function(e, currentHash, previousHash) {
		trace('User navigated to: ' + currentHash);
    });

    $(window).historyadd(function(e, currentHash, previousHash) {
    	trace('Navigation added: ' + currentHash);
    });

    $(window).history(function(e, hash) {
        hashChangeHandler(hash);
    });
    
    setButtonHandlers();
    
    hideAlbums();
    
    onPageLoaded();
    
    //setup thumbnail container
    onWindowResize(); //account for initial load
    $(window).bind('resize', onWindowResize);
}

function getHash()
{
	var url = String(window.location);
	var startIndex = url.indexOf("#");
	var hash = startIndex==-1 ? "" : url.substring(startIndex, url.length);
	trace("Hash is " + hash);
	return hash;
}

function getInitHash()
{
	var hash = getHash();
	if(hash == "" || hash.indexOf('index') != -1){
		if(hash == ""){
			setHash(HASH_INDEX);
		}
		getAlbums(''); //send empty string to get root directory listing
	}
	else{
		hashChangeHandler(hash);
	}
}

/*
 * public functions
 */
function getAlbums(dir)
{
	hideContentMsg();
	
	if(dir == ''){
		gettingRootAlbums = true;
		onViewModeChange(true);
	}
	else{
		gettingRootAlbums = false;
		onViewModeChange(false);
	}
	
	showLoadMsg(LOAD_MSG_ALBUMS);
	
	var date = Date();
	$.ajax({
		type: "GET",
		url: URL_GET_DIR_LISTING + "?dir=" + dir + "&date=" + date,
		success: function(msg){
			albumsXML = $(msg);
			parseAlbumsXML();
		},
		error: function(msg){
			hideLoadMsg();
			$('#thumb_container').html('');
			showContentMsg(MSG_NO_CONTENT);
		}
	});
}

function getThumbnails(dir)
{
	hideContentMsg();
	hideAlbums();
	onViewModeChange(false);
	
	showLoadMsg(LOAD_MSG_THUMBS);
	
	setHash(HASH_THUMBS_PRE + dir);
	
	var date = Date();
	$.ajax({
		type: "GET",
		url: URL_GET_DIR_LISTING + "?dir=" + dir + "&date=" + date,
		success: function(msg){
			imagesXML = $(msg);
			parseImagesXML();
		},
		error: function(msg){
			hideLoadMsg();
			$('#thumb_container').html('');
			showContentMsg(MSG_NO_CONTENT);
		}
	});
}

function getCover(dir, albumId)
{
	var date = Date();
	$.ajax({
		type: "GET",
		url: URL_GET_DIR_LISTING + "?dir=" + dir + "&coverOnly=true&date=" + date,
		success: function(msg){
			setCover(msg, albumId);
		}
	});
}

function setCover(msg, albumId)
{
	var url = $(msg).find('image').text();
	var image = "<img src='" + DIR_ROOT_IMAGES + url + "'/>";
	$(image).appendTo("#albums_container #" + albumId);
	$(image).appendTo("#thumb_container #" + albumId);
}

function showZoom(url)
{
	showOverlay();
	var image = "<img  src='" + DIR_ROOT_IMAGES + url + "' alt='Full resolution image' title='" + url + "'/>"
	$('#overlay #whitebox #imageContainer').html(image);
	
	$('#overlay .loader').show();
	trace("Show zoomed image: " + image);
	
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	if(!is_chrome){
		$('#overlay #whitebox #imageContainer img').load(function(){
			zoomLoadedHandler();
		});
	}
	else{
		zoomLoadedHandler();
	}
	
	//determine view index
	for(var i=0; i<currentVOs.length; i++){
		if(url == currentVOs[i]){
			viewIndex = i;
			break;
		}
	}
	onThumbnailCountChange();
}

function hideOverlay()
{
	$('#overlay #whitebox').animate({opacity: 0, filter: 'alpha(opacity=0)'}, 250);
	$('#overlay #blackbox').animate({opacity: 0, filter: 'alpha(opacity=0)'}, 250, function(){
		$('#overlay').css('display', 'none');
	});
	showingOverlay = false;
}

/*
 * private functions
 */
function parseAlbumsXML()
{
	var hash = getHash();
	if(hash.indexOf("index") != -1){
		$('#thumb_container').html('');
		terminateLoad();
	}
	
	albumsXML.find('album').each(function(){
		var url = $(this).text();
		var name = $(this).attr('name');
		var album = {url: url, name: name};
		albums.push(album);
		trace("Adding to load queue: " + name);
	});
	
	albumIndex = 0;
	
	if(gettingRootAlbums){
		$('#albums_container').html('');
	}
	
	if(albums.length > 0)
		createAlbum(albums[albumIndex]);
	else{
		onContentLoaded();
		trace("No sub directories in this album.");
	}
}

function parseImagesXML()
{
	terminateLoad();
	imagesXML.find('image').each(function(){
		var url = $(this).text();
		thumbnails.push(url);
	});
	
	thumbIndex = 0;
	$('#thumb_container').html('');
	if(thumbnails.length > 0)
		loadFirstPage();
	else{
		onContentLoaded();
		trace("No images in this album.");
	}
}

function loadFirstPage()
{
	showLoadMsg(LOAD_MSG_THUMBS);
	
	var endIndex = 0;
	if(viewMode == MODE_VIEW_ALL)
		endIndex = thumbnails.length;
	else if(viewMode == MODE_VIEW_PAGES){
		viewIndex = 0;
		endIndex = thumbnails.length<VOS_PER_PAGE ? thumbnails.length : VOS_PER_PAGE;
	}
	
	currentVOs = new Array();
	for(var i=0; i<endIndex; i++){
		currentVOs.push(thumbnails[i]);
	}
	
	pageIndex = 0;
	thumbIndex = 0;
	$('#thumb_container').html('');
	createThumbnail(currentVOs[thumbIndex]);
	onPageLoaded();
}

function loadNewPage()
{
	trace("Loading new page: " + pageIndex);
	showLoadMsg(LOAD_MSG_THUMBS);
	
	var max = (pageIndex+1) * VOS_PER_PAGE;
	var endIndex = max>thumbnails.length ? thumbnails.length : max;
	var startIndex = pageIndex * VOS_PER_PAGE;
	
	currentVOs = new Array();
	for(var i=startIndex; i<endIndex; i++){
		currentVOs.push(thumbnails[i]);
	}
	
	thumbIndex = 0;
	$('#thumb_container').html('');
	createThumbnail(currentVOs[thumbIndex]);
	onPageLoaded();
}

function nextPage()
{
	pageIndex++;
	var max = Math.ceil(thumbnails.length / VOS_PER_PAGE);
	if(pageIndex > max)
		pageIndex = max;
		
	loadNewPage();
}

function prevPage()
{
	pageIndex--;
	if(pageIndex < 0)
		pageIndex = 0;
	
	loadNewPage();
}

function createThumbnail(url)
{
	var thumb = "<li><div class='thumbnail' onclick='showZoom(\"" + url + "\");'><img src='" + DIR_ROOT_IMAGES + url + "' title='" + url + "' alt='Click to enlarge thumbnail'/></div></li>";
	$(thumb).appendTo('#thumb_container');
	
	$(".thumbnail").unbind('mouseover').unbind('mouseout').mouseover(function(){
		$(this).css('border-color', THUMB_OVER_COLOR);
      }).mouseout(function(){
    	$(this).css('border-color', THUMB_UP_COLOR);
      });
	
	$(".thumbnail").css("position", "relative").css("overflow", "hidden").css("background", "#000000").css("border", "3px solid " + THUMB_UP_COLOR);
	var w = $(".thumbnail").width();
	var h = $(".thumbnail").height();
	$(".thumbnail img").css('position', 'absolute').css("width", w).css("height", h);
	
	if(canFade){
		$('ul#thumb_container li:last').animate({opacity: 0, filter: 'alpha(opacity=0)'}, 0, function(){
			$('ul#thumb_container li:last').animate({opacity: 1, filter: 'alpha(opacity=100)'}, APPEAR_DURATION, function(){
				thumbIndex++;
				if(thumbIndex < currentVOs.length)
					createThumbnail(currentVOs[thumbIndex]);
				else{
					onContentLoaded();
					trace("Thumbnails fin!");
				}
			});
		});
	}
	else{
		$('ul#thumb_container li:last').css('display', 'none');
		setTimeout(function(){
			$('ul#thumb_container li:last').css('display', 'inline');
			thumbIndex++;
			if(thumbIndex < currentVOs.length)
				createThumbnail(currentVOs[thumbIndex]);
			else{
				onContentLoaded();
				trace("Thumbnails fin!");
			}
		}, APPEAR_DURATION);
	}
	trace("Thumbnail created: " + url + "|index: " + thumbIndex);
}

function createAlbum(album)
{
	var id = album.name.replace(/ /g, "_");
	var thumb = "<li><div id='" + id + "' class='album' onclick='getThumbnails(" + '"' + album.url + '"' 
		+ ");' title='" + album.name + "' alt='Click to load album'>" + "<div id='label'>" + album.name + "</div></div></li>";
	
	var hash = getHash();
	if(hash.indexOf("index") != -1){
		$(thumb).appendTo('#thumb_container');
	}
	
	if(gettingRootAlbums)
		$(thumb).appendTo('#albums_container');
	
	var originalBg = $(".album").css("background-color");
	$(".album").unbind('mouseover').unbind('mouseout').mouseover(function(){
		$(this).css('background', '#fcaf17');
      }).mouseout(function(){
    	$(this).css('background', originalBg);
      });
	
	getCover(album.url, id);
	//apply album styles
	var rotate = "rotate(" + Math.round(Math.random() * 20 - 10) + "deg)";
	var shadow = "rgba(125, 35, 0, 0.75) 5px 5px 5px";
	$('#thumb_container #' + id).css("-webkit-transform", rotate).css("-moz-transform", rotate)
								.css("-webkit-box-shadow", shadow).css("-moz-box-shadow", shadow);
	
	//create thumbtack
	$("<div class='thumbtack'></div>").appendTo('#thumb_container #' + id);
	var tackId = Math.round(Math.random() * 4);
	var x = Math.round(Math.random() * $(".thumbtack").width());
	var y = Math.round(Math.random() * $(".thumbtack").height() - $(".thumbtack img").height());
	$('#thumb_container #' + id + " .thumbtack").css("background", "url('assets/res/thumbtack" + tackId + ".png') no-repeat")
												.css("left", x).css("top", y);
	
	if(canFade){
		$('ul#thumb_container li:last').animate({opacity: 0, filter: 'alpha(opacity=0)'}, 0, function(){
			$('ul#thumb_container li:last').animate({opacity: 1, filter: 'alpha(opacity=100)'}, APPEAR_DURATION, function(){
				albumIndex++;
				if(albumIndex < albums.length)
					createAlbum(albums[albumIndex]);
				else{
					hideLoadMsg();
					onPageLoaded();
					trace("Albums fin!");
				}
			});
		});
	}
	else{
		$('ul#thumb_container li:last').css('display', 'none');
		setTimeout(function(){
			$('ul#thumb_container li:last').css('display', 'inline');
			albumIndex++;
			if(albumIndex < albums.length)
				createAlbum(albums[albumIndex]);
			else{
				hideLoadMsg();
				onPageLoaded();
				trace("Albums fin!");
			}
		}, APPEAR_DURATION);
	}
	trace("Album Thumb created: " + album.url + "|name: " + album.name + "|index: " + albumIndex);
}

function setHash(hash)
{
	var new_hash = '#' + hash;
	$.history.add(new_hash);
	trace('Hash added: ' + $.history.getCurrent());
}

function hashChangeHandler(hash)
{
	terminateLoad();
	
	if(hash == HASH_INDEX)
		getAlbums('');
	else if(hash.indexOf(HASH_THUMBS_PRE) != -1){
		var dir = hash.split("&")[1];
		getThumbnails(dir);
	}
}

function terminateLoad()
{
	thumbnails = new Array();
	thumbIndex = -1;
	
	//only clear que for the following when entering non-index pages
	var hash = getHash();
	if(hash.indexOf('index') != -1){
		currentVOs = new Array();
		pageIndex = -1;
		albums = new Array();
		albumIndex = -1;
	}
	
	trace("Clearing load queue");
}

function trace(text)
{
//	if(DEBUG_MODE)
//		console.log(text);
}

function getBrowser()
{
	var browser = navigator.appName;
	trace("User browser is: " + browser);
	if(browser.toLowerCase().indexOf('microsoft') != -1)
		canFade = false;
}

function zoomLoadedHandler()
{
	var img = $('#overlay #whitebox #imageContainer img');
	var docW = $(document).width();
	var docH = $(document).height();
	var imgH = img.height();
	var imgW = img.width();
	
	var ratio = 1;
	if(img.height() > img.width() && img.height() > docH-150){
		ratio = (docH-150) / img.height();
	}
	else if(img.width() > img.height() && img.width() > docW-150){
		ratio = (docW-150) / img.width();
	}
	imgH = Math.round(img.height() * ratio);
	imgW = Math.round(img.width() * ratio);
	
	var t = 0;
	$('#overlay .loader').hide();
	$('#whitebox #imageContainer img').animate({width: imgW+'px',height: imgH+'px'}, t);
	$('#whitebox #imageContainer').css({width: imgW+'px', height: imgH+'px'});
	$('#whitebox').animate({opacity: 1, filter: 'alpha(opacity=100)', width: imgW+30+'px', height: imgH+65+'px', left: (docW-imgW)/2+'px', top: (docH-imgH)/2-17+'px'}, t, function(){
		setTimeout(function(){$('#whitebox #options').slideDown(250)}, 250);
	});
	
	//thumbtack
	var tackId = Math.round(Math.random() * 4);
	var tackBg = "url('assets/res/thumbtack_large" + tackId + ".png') no-repeat";
	var l = Math.round(Math.random() * $("#overlay #whitebox").width());
	$("#overlay #whitebox .thumbtack").css("background", tackBg).css("left", l);
	
}

function showOverlay()
{
	$('#overlay').css('display', 'inline');
	$('#overlay #blackbox').animate({opacity: 0.85, filter: 'alpha(opacity=85)'}, 500);
	
	$('#whitebox').css({opacity: 0, filter: 'alpha(opacity=0)'});
	$('#whitebox #options').slideUp(0);
	
	showingOverlay = true;
}

function setButtonHandlers()
{
	//zoom overlay buttons
	$('#overlay #options .leftArrow').mouseover(function(){
		$(this).css('background-position', '-13px');
	}).mouseout(function(){
		$(this).css('background-position', '0px');
	}).click(function(){
		prevImage();
	});
	
	$('#overlay #options .rightArrow').mouseover(function(){
		$(this).css('background-position', '-13px');
	}).mouseout(function(){
		$(this).css('background-position', '0px');
	}).click(function(){
		nextImage();
	});
	
	$('#overlay #options .x').mouseover(function(){
		$(this).css('background-position', '-20px');
	}).mouseout(function(){
		$(this).css('background-position', '0px');
	}).click(function(){
		hideOverlay();
	});
	
	//topbar buttons
	$('#logo').mouseover(function(){
		$(this).css('background-position', '0px -184px');
	}).mouseout(function(){
		$(this).css('background-position', '0px 0px');
	}).click(function(){
		setHash(HASH_INDEX);
		getAlbums('');
	});
	
	$('#topbar .home').mouseover(function(){
		$(this).css('background-position', '-25px');
	}).mouseout(function(){
		$(this).css('background-position', '0px');
	}).click(function(){
		setHash(HASH_INDEX);
		getAlbums('');
	});
	
	$('#topbar .viewAlbums').mouseover(function(){
		$(this).css('background-position', '-30px');
	}).mouseout(function(){
		$(this).css('background-position', '0px');
	}).click(function(){
		if(showingAlbums)
			hideAlbums();
		else
			showAlbums();
	});
}

function prevImage()
{
	viewIndex--;
	if(viewIndex < 0)
		viewIndex = currentVOs.length-1;
	showZoom(currentVOs[viewIndex]);
}

function nextImage()
{
	viewIndex++;
	if(viewIndex > currentVOs.length-1)
		viewIndex = 0;
	showZoom(currentVOs[viewIndex]);
}

function onThumbnailCountChange()
{
	$('#overlay #options .display').attr('title', 'Currently viewing image ' + (viewIndex+1) + ' / ' + currentVOs.length)
								   .attr('alt', 'Currently viewing image ' + (viewIndex+1) + ' / ' + currentVOs.length)
								   .text(viewIndex+1 + " / " + currentVOs.length);
}

function onWindowResize()
{
	var containerH = $(window).height() - 210 + 'px';
    //$('#thumb_container').css('height', containerH);
    $('#thumb_container').css('margin-top', '210px');
    
    var msgTop = 210 + ($(window).height() - 210 -99)/2 + 'px';
    $('#msg').css('top', msgTop);
    
    $('#albums_container').css('width', $(window).width() - 235 + 'px');
    
    if(showingOverlay){
		zoomLoadedHandler();
	}
    
    alignFooter();
}

function alignFooter()
{
	var marginTop = $("#thumb_container").css("margin-top").replace(/px/g, "");
	var paddingTop = $("#thumb_container").css("padding-top").replace(/px/g, "");
	var marginBottom = $("#thumb_container").css("margin-bottom").replace(/px/g, "");
	var paddingBottom = $("#thumb_container").css("padding-bottom").replace(/px/g, "");
    var h = $(window).height() - marginTop - marginBottom - paddingTop - paddingBottom - $('#footer').height();
    $('#thumb_container').css('min-height', h);
}

function onContentLoaded()
{
	hideLoadMsg();
	if($('#thumb_container').html() == '')
		showContentMsg(MSG_NO_CONTENT);
	else
		hideContentMsg();
}

function showLoadMsg(msg)
{
	$('#topbar .loader').show();
	$('#topbar .loader .text').text(msg);
}

function hideLoadMsg()
{
	$('#topbar .loader').hide();
	$('#topbar .loader .text').text('');
}

function onViewModeChange(loadingRoot)
{
	if(loadingRoot){
		$('#topbar .viewMultipage').css('background-position', '-42px')
		   .unbind('mouseover')
		   .unbind('mouseout')
		   .unbind('click');
		
		$('#topbar .viewSinglepage').css('background-position', '-36px')
		   .unbind('mouseover')
		   .unbind('mouseout')
		   .unbind('click');
	}
	else if(viewMode == MODE_VIEW_PAGES){
		$('#topbar .viewMultipage').css('background-position', '-42px')
								   .unbind('mouseover')
								   .unbind('mouseout')
								   .unbind('click');
		
		$('#topbar .viewSinglepage').css('background-position', '0px');
		$('#topbar .viewSinglepage').mouseover(function(){
			$(this).css('background-position', '-18px');
		}).mouseout(function(){
			$(this).css('background-position', '0px');
		}).click(function(){
			viewMode = MODE_VIEW_ALL;
			onViewModeChange(false);
			loadFirstPage();
		});
	}
	else if(viewMode == MODE_VIEW_ALL){
		$('#topbar .viewSinglepage').css('background-position', '-36px')
		   .unbind('mouseover')
		   .unbind('mouseout')
		   .unbind('click');
		
		$('#topbar .viewMultipage').css('background-position', '0px');
		$('#topbar .viewMultipage').mouseover(function(){
			$(this).css('background-position', '-21px');
		}).mouseout(function(){
			$(this).css('background-position', '0px');
		}).click(function(){
			viewMode = MODE_VIEW_PAGES;
			onViewModeChange(false);
			loadFirstPage();
		});
	}
}

function onPageLoaded()
{
	if(viewMode == MODE_VIEW_PAGES){
		var totalPage = Math.ceil(thumbnails.length / VOS_PER_PAGE);
		$('#topbar #pageControls .display').text(pageIndex+1 + " / " + totalPage);
	}
	else
		$('#topbar #pageControls .display').text("1 / 1");
	
	//reset button handlers
	$('#topbar #pageControls .rightArrow').unbind('click').unbind('mouseover').unbind('mouseout')
										  .css('background-position', '-26px');
	$('#topbar #pageControls .leftArrow').unbind('click').unbind('mouseover').unbind('mouseout')
	  									  .css('background-position', '-26px');
	
	//update buttons handlers
	if(pageIndex+1 < totalPage){
		$('#topbar #pageControls .rightArrow').css('background-position', '0px');
		$('#topbar #pageControls .rightArrow').mouseover(function(){
			$(this).css('background-position', '-13px');
		}).mouseout(function(){
			$(this).css('background-position', '0px');
		}).click(function(){
			nextPage();
		});
	}
	if(pageIndex+1 > 1){
		$('#topbar #pageControls .leftArrow').css('background-position', '0px');
		$('#topbar #pageControls .leftArrow').mouseover(function(){
			$(this).css('background-position', '-13px');
		}).mouseout(function(){
			$(this).css('background-position', '0px');
		}).click(function(){
			prevPage();
		});
	}
}

function showContentMsg(msg)
{
	$('#msg').show();
	$('#msg .text').html(msg);
}

function hideContentMsg()
{
	$('#msg').hide();
	$('#msg .text').html('');
}

function showAlbums()
{
	//if albums have not been loaded, go load them
	if(albumsXML == ""){
		getAlbums("");
	}
	
	showingAlbums = true;
	$('#albumBar').slideDown(250);
	$('#albumBar #albums_container').slideDown(250);
}

function hideAlbums()
{
	showingAlbums = false;
	$('#albumBar').slideUp(250);
	$('#albumBar #albums_container').slideUp(150);
}

