$(document).ready(function() {
	$(document).mousemove(archiveMouseMove);
	$(window).resize(archiveReset);
	archiveLength = $('div#a_pages a').length - 6;
	$('div#a_pages a').mouseover(archiveOver);
	$('div#a_pages a').mouseout(archiveOut);
	$('div#a_left').click(archiveRight);
	$('div#a_right').click(archiveLeft);
});

archiveCurrent = null;
archivePosition = 0;
archiveLength = 0;

function archiveHideBalloon() {
	$('div#a_balloon').hide();
	$('div#a_balloon_arrow').hide();
}

function archiveShowBalloon() {
	$('div#a_balloon').show();
	$('div#a_balloon_arrow').show();
}

function archiveLeft() {
	if (archivePosition < archiveLength) {
		//console.log("left: " + (archivePosition+1) + '/' + archiveLength);
		var d = 6;
		if (archivePosition + d >= archiveLength)
			d = archiveLength - archivePosition;
		archivePosition += d;
		archiveMove();
	}
}

function archiveRight() {
	if (archivePosition > 0) {
		//console.log("right: " + (archivePosition-1) + '/' + archiveLength);
		var d = 6;
		if (archivePosition - d < 0)
			d = archivePosition;
		archivePosition -= d;
		archiveMove();
	}
}

function archiveMove() {
	$('div#a_pages').animate({ 'marginLeft': (archivePosition * -147) + 'px' });
}

function archiveReset(e) {
}

function archiveOver(e) {
	var img = $(e.target);
	if (!img[0].src)
		return;
	var newsrc = img[0].src.replace(/_small\./, '_large.');
	$('div#a_balloon_content').empty();
	var newimg = $('<img />', { src: newsrc, alt: '' } ).appendTo($('div#a_balloon_content'));
	archiveShowBalloon();
	archiveCurrent = newimg;
}

function archiveOut(e) {
	archiveCurrent = null;
	archiveHideBalloon();
}

function archiveMouseMove(e) {
	var arrow = $('div#a_balloon_arrow');
	var balloon = $('div#a_balloon');
	var archive = $('div#archive');
	var ol = archive.offset().left;
	var ot = archive.offset().top;
	var ob = ot + archive.height();
	var rml = e.pageX - ol;
	var targetX = 0;

	var arrowLimit = [50, 900];
	var balloonLimit = [214, 757];

	if (e.pageY < ot || e.pageY > ob || rml < 0 || rml > archive.width() || archiveCurrent == null) {
		archiveHideBalloon();
		return;
	}

	if (rml < arrowLimit[0])
		targetX = ol + arrowLimit[0];
	else if (rml > arrowLimit[1])
		targetX = ol + arrowLimit[1];
	else
		targetX = rml + ol;

	var targetX2 = 0;
	if (rml < balloonLimit[0])
		targetX2 = ol + balloonLimit[0];
	else if (rml > balloonLimit[1]) 
		targetX2 = ol + balloonLimit[1];
	else
		targetX2 = rml + ol;

	balloon.offset( { left: targetX2 - 192 } );		

	arrow.offset( { left: targetX - 10 } );

	archiveShowBalloon();

}


