var canvasWidth;
var canvasHeight;
var photoNo = 0;
var photoset = new Array();
var photosetTitle = '';
var loadingInProgress = false;
var fadingTimeOut;

$(document).ready(function() {
	if (!$('#photoset').length) return;
	
	var no;
	if (no = window.location.hash.match(/^#[0-9]+$/)) {
		photoNo = Number(no.toString().substr(1));
	}
	canvasWidth = $('#canvas').width();
	canvasHeight = $('#canvas').height();
	
	$('#photoset li a').each(function() {
		photoset.push({ uri: $(this).attr('href'), title: $(this).find('img').attr('alt'), meta: $(this).find('img').attr('longdesc') });
	});
	$('#photoset').remove();

	$('#canvas').after('<div id="imagecontrols"><a href="#" id="prev-image">&lt;</a><span id="indicator">1/' + photoset.length + '</span><a href="#" id="next-image">&gt;</a></div><div id="photo-description"></div>');

	drawPicture(photoNo);
	window.setTimeout(checkLocationHash, 4000);


	$('#prev-image').click(function() {
		if (!loadingInProgress) {
			photoNo--;
			if (photoNo < 0) photoNo = photoset.length-1;
			drawPicture();
		}
		window.location.hash = '#'+photoNo;
		return false;
	});

	$('#next-image').click(function() {
		if (!loadingInProgress) {
			photoNo++;
			if (photoNo > photoset.length-1) photoNo = 0;
			drawPicture();
		}
		window.location.hash = '#'+photoNo;
		return false;
	});

	fadingTimeOut = window.setTimeout(nextImage, 4000);
});

function nextImage() {
	$('#next-image').trigger('click');
	window.setTimeout(nextImage, 4000);
}


function drawPicture() {
	loadingInProgress = true;
	var p = photoset[photoNo];

	if ((typeof p.meta) == 'string') eval('p.meta = ' + p.meta);
	
	var ratio = canvasHeight / p.meta.o_height;
	
	var mtags = p.meta.machine_tags.split(/ /);
	var options = {};
	for (var i in mtags) {
		var tmp = mtags[i].split(/\=/);
		options[tmp[0].substr(tmp[0].indexOf(':')+1)] = tmp[1];
	}
	
	$('#canvas').prepend('<div class="imagecontainer" style="width: ' + (canvasWidth) + 'px; height: ' + (canvasHeight) + 'px;' + (options.align ? 'text-align: ' + options.align : '') + '"><img src="' + p.uri + '" alt="' + p.title + '" width="' + (canvasWidth-20) + '" /></div>');
	$('#canvas div.imagecontainer:first-child img').load(function() {
		$('#indicator').text((photoNo+1) + '/' + photoset.length);
		$('#photo-description').fadeOut(200, function() {
			$('#photo-description').text(p.meta.description).fadeIn(1000);
		});
		if (photoNo+1 == photoset.length) $('#photoset-to-list').show();
		else $('#photoset-to-list').hide();
		var second = $('#canvas div.imagecontainer:nth-child(2)');
		if (second.length) {
			second.fadeOut(1200,function() {
				second.remove();
				loadingInProgress = false;
			});
		} else {
			loadingInProgress = false;
		}
	});
}

function checkLocationHash() {
	var no;
	if (no = window.location.hash.match(/^#[0-9]+$/)) {
		no = Number(no.toString().substr(1));
		if (no != photoNo) {
			photoNo = no;
			drawPicture();
		}
	}
	window.setTimeout(checkLocationHash, 1000);
}
