//
//	js by Yuri Koval'ov
//

var debug = false;
// Disable logging on IE and such to prevent crash
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };
if (!debug) {
	var console = { log: function() {} };
}

// image preload function from http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    $("<img>").attr("src", arguments[i]);
  }
}

// set image size/workarea size
function setImageSize( imgWidth, imgHeight )
{
	var max = 1024;
	var min = 300;
	var ratio = imgHeight/imgWidth;
	var fh = window.innerHeight - 160;
	var fw = window.innerWidth - (60 + 35)*2;
	
	if (fh > max) { fh = max;} else if (fh < min) {fh = min};
	if (fw > max) { fw = max;} else if (fw < min) {fw = min};
	
	var height, width;
	
	if (fw > fh) {
		// adjust to width
		height = fh;
		width = Math.round(height*(1/ratio));

	} else {
		// adjust to height
		width = fw;
		height = width*ratio;
	}
	
	// check for overflows + minimums
	if ( (height > fh) ) {
		height = fh;
		width = Math.round(height*(1/ratio));
	}
	
	if ( (width > fw) ) {
		width = fw;
		height = width*ratio;
	}
	// center image
	var halfheight = Math.round(height/2 - 40);
	var halfwidth = Math.round(width/2);
	$("#work").width(width);
	$("#work").height(height);
	$("#work").css("margin-top", "-" + halfheight + "px");
	$("#work").css("margin-left", "-" + halfwidth + "px");
}

// define starting point
var album, hash; // do not set values
var default_album = "default";
var current = 0;
var animateSpeed = 1000;

var nextdisabled = false;
var previousdisabled = false;
$(document).ready(function(){
	// define buttons
	$("#name").click(function () {window.location='/';}).attr("title", "Yuri Koval'ov");
	$("#about").click(function () {window.location='/about';}).attr("title", "About");
	$("#works").click(function () {window.location='/works';}).attr("title", "Works");
	
	$("#error").dialog({
		autoOpen: false,
		disabled: true
	});
	// Go to next by clicking
	$("#next").click( function() {$.loadNext();}).hide();
	// Go previous
	$("#previous").click( function() {$.loadPrevious();}).hide();
	// trigger navigation by keyboard
	$(window).keydown(function(event){
		if (event.keyCode == 39) {$("#next").click();}
		if (event.keyCode == 37) {$("#previous").click();}
	});

	hash = document.location.hash; // get first image from URL

	try {
		if ( worklist != undefined && collections != undefined ) {
			// direct access to image
			if (hash.substring(1) != "") {
				try {
					hash = hash.substring(1);
					// find the first album of the image
					loop1: // break here when done
					if (album == undefined) {
						for (var collection in collections) {
							for (var image in collections[collection].collection) {
								if (collections[collection].collection[image] == hash) {
									current = image;
									album = collection;
									break loop1;
								};
							}
						}
					}
				} catch(e){
					$("#error").html("Collections Could not be loaded: "+e);
					$("#error").dialog("open");
					console.log(e);
				}
			} else {
				// There is no direct access to image
//				if (album == undefined) album = default_album;
			}
			// display initial image
			$.loadImage(current);
		}
	} catch (e){}
}); // close $(
// Load Next
jQuery.loadNext = function () {
	if (nextdisabled) return 0;
	$.loadImage(current+1);
	return 0;
}
// Load Previous
jQuery.loadPrevious = function () {
	if (previousdisabled) return 0;
	$.loadImage(current-1);
	return 0;
}

// Load Image function
jQuery.loadImage = function ( currentToDisplay ) {
	currentToDisplay = eval(currentToDisplay);
	try {
			if ((album == undefined && worklist[hash] == undefined) || collections[album] == undefined ) { // check if image exists
				album = default_album; current = 0;
			}
			if ( album != undefined ) { // image is NOT in a collection
				// load collection
				var collection = collections[album].collection;
				var loop = eval(collections[album].loop);
				// get number of images in a collection
				var lastImage = eval(collection.length) - 1;

				// adjust current index
				if ( currentToDisplay < 0 ) currentToDisplay = lastImage;
				if ( currentToDisplay > lastImage ) currentToDisplay = 0;
				//adjust next image index
				if (currentToDisplay == lastImage) { // if image is last one 
					if (loop == false) {var nextToDisplay = false; nextdisabled = true;}  // no looping so disable next
					if (loop == true) var nextToDisplay = 0; // looping so set next image
					} else {
						var nextToDisplay = currentToDisplay + 1;
						nextdisabled = false;
					}
				//adjust previous image index
				if (currentToDisplay == 0) { // if image is first one
					if (loop == false) {var previousToDisplay = false; previousdisabled = true;}
					if (loop == true) var previousToDisplay = lastImage; // looping so set previous image
					} else {
						var previousToDisplay = currentToDisplay - 1;
						previousdisabled = false;
					}
				
				var currentToDisplayName = collection[currentToDisplay];
			} else {
				var currentToDisplayName = hash;
			}
		} catch (e) {
			$("#error").html("Collections could not be loaded: "+e).dialog("open");
			console.log(e);
		}

	try {
			
			var imgSrc = worklist[currentToDisplayName].src;
			var imgTitle = worklist[currentToDisplayName].title;
			var imgDesc = worklist[currentToDisplayName].description;
			
			$.preloadImages(imgSrc);
			// take care of next
			if (album != undefined) { // image is NOT standaloe and not in a collection
				if (nextdisabled) {
					$("#next").animate({opacity: 0.0},  animateSpeed, "linear", function() {$(this).hide();});
				} else {
					var nextToDisplayName = collection[nextToDisplay];
					$("#next").show().animate({opacity: 1.0}, animateSpeed );
					$("#next").attr("title", "Next: "+worklist[nextToDisplayName].title);
				}
				
				// take care of previous
				if (previousdisabled) {
					$("#previous").animate({opacity: 0.0},  animateSpeed, "linear", function() {$(this).hide();});
				} else {
					var previousToDisplayName = collection[previousToDisplay];
					$("#previous").show().animate({opacity: 1.0}, animateSpeed );
					$("#previous").attr("title", "Previous: "+worklist[previousToDisplayName].title);
				}
			}
			
			// load current image
			$("#content").animate({opacity: 0.0},  animateSpeed, "linear",function(){
				$("#content").html($("<img>").attr("src", imgSrc).attr("id", "work"));
				setImageSize( $("#work").attr("naturalWidth"), $("#work").attr("naturalHeight") );
			}).delay(300).animate({opacity: 1.0}, animateSpeed );
			document.location.hash = currentToDisplayName;
			current = currentToDisplay;
	} catch(e) {
			$("#error").html("Image could not be loaded: "+e).dialog("open");
			console.log(e);
	}
};
