buttonOn = false;
mainpicOn = false;
imgIdx = 0;
images = null;

$(document).ready(function () {
	$("#main_picture").hover(function() {
		buttonOn = true;
		mainpicOn = true;
		if(images) {
			showButtons();
		}
	}, function() {
		buttonOn = false;
		mainpicOn = false;
		setTimeout(function () { hideButtons(); }, 200)
	});
	
	$(".gallery_btn").hover(function() {
		buttonOn = true;
	}, function() {
		buttonOn = false;
		setTimeout(function () { hideButtons(); }, 200)
	});
	
	$("#next_btn").click(function() {
		imgIdx++;
		imgIdx %= images.length;
		changeImage(imgIdx);
	});
	
	$("#prev_btn").click(function() {
		imgIdx--;
		if(imgIdx < 0) {
			imgIdx = images.length-1;
		}
		changeImage(imgIdx)
	});
});

function showButtons() {
	if(!buttonOn && !mainpicOn) return;	
	if(imgIdx > 0) {
		//Show Prev
		$("#prev_btn").fadeIn();
	} else {
		$("#prev_btn").fadeOut();
	}
	
	if(imgIdx < images.length-1) {
		//Show Next
		$("#next_btn").fadeIn();
	} else {
		$("#next_btn").fadeOut();
	}
}

function hideButtons() {
	if(buttonOn) return;
	
	$(".gallery_btn").fadeOut();
}

function changeImage (idx) {
	$("#main_picture").fadeOut('slow', function() {
		showButtons();
		this.src = images[idx].src;
		this.alt = images[idx].alt;
		$("#caption").text(images[idx].alt);
		$(this).load(function() {
			$("#main_picture").fadeIn();
		});
	});
}