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

var debug = true;
// 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() {} };
}

// set image size/workarea size
var setImageSize = function( originalW, originalH )
{
	var max = 1024,
		min = 300,
		ratio = originalH/originalW,
		fh = window.innerHeight - 160,
		fw = window.innerWidth - (60 + 35)*2,
		height,
		width;
	
	if (fh > max) { fh = max; } else if (fh < min) { fh = min; };
	if (fw > max) { fw = max; } else if (fw < min) { fw = min; };
	
	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),
		halfwidth = Math.round(width/2);

	$("#work")	.attr('width', width)
				.attr('height', height)	// IE6 does not render .css() and .height()/.width()
				.attr('style', 'margin-top:-' + halfheight + 'px;margin-left:-' + halfwidth + 'px;');
	return true;
}

// Load Next
var loadNext = function () {
	if (nextdisabled) return true;
	loadImage(current+1);
	return true;
}
// Load Previous
var loadPrevious = function () {
	if (previousdisabled) return true;
	loadImage(current-1);
	return true;
}

// Load Image function
var loadImage = function ( currentToDisplay ) {
	currentToDisplay = parseInt(currentToDisplay);
	var currentToDisplayName;
//	(function(){	// process request and return currentToDisplayName
		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 = collections[album].loop;
					// get number of images in a collection
					var lastImage = 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;
						}
					
					currentToDisplayName = collection[currentToDisplay];
				} else {
					currentToDisplayName = hash;
				}
			} catch (e) {
				console.log(e);
			}
//	})();

	(function(){	// display image
		try {
				
				var imgSrc = worklist[currentToDisplayName].src;
				var imgTitle = worklist[currentToDisplayName].title;
				var imgDesc = worklist[currentToDisplayName].description;
				
				// 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();});
						$("#next").fadeOut(animateSpeed);
					} else {
						var nextToDisplayName = collection[nextToDisplay];
						$("#next")	.attr("title", "Next: "+worklist[nextToDisplayName].title)
									.fadeIn(animateSpeed);
					}
					
					// take care of previous
					if (previousdisabled) {
						$("#previous").fadeOut(animateSpeed);
					} else {
						var previousToDisplayName = collection[previousToDisplay];
						$("#previous")	.attr("title", "Previous: "+worklist[previousToDisplayName].title)
										.fadeIn(animateSpeed);
					}
				}
				
				// create new image
				var img = new Image();
				img.src = imgSrc;
				
				// load current image
				$("#content").fadeOut(animateSpeed, function(){
					document.getElementById("content").innerHTML = '<img id="work" />';
					document.getElementById("work").src = imgSrc;
					document.getElementById("work").onload = function() {
						setImageSize(this.naturalWidth, this.naturalHeight);
						$("#content").fadeIn(animateSpeed);
						return true;
					};
				});
				document.location.hash = currentToDisplayName;
				current = currentToDisplay;
				console.log("Current: "+current);
		} catch(e) {
				console.log(e);
		}
	})();
	return true;
};

// define starting point
var album, hash; // do not set values
var default_album = "default_collection";
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");

	// 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.split("#")[1] != "") {
				try {
					hash = hash.split("#")[1];
					
					// find the first album of the image
					(function(){	// wrap function
						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;
										return;
									}
								}
							}
						}
					})();
				} catch(e){
					console.log(e);
				}
			}
			
			// display initial image
			$('#content').append('<img id="work">');
			loadImage(current);
		}
	
	} catch (e){ console.log(e); }
}); // close $(

