// JavaScript Document
$(document).ready(function(){
	$('#prev').hide();
	var curimg = 1;
	var totalimages = $('#numimages').attr("class");
	$(".thumb").click(function() { //call when thumbnail image is clicked
		ID = $(this).attr("ID");
		changeimage(ID);
		return false;
	});
	function changeimage(ID) { // change image once ID of the image has been discovered
		//hide current image and caption
		$('#gallery .caption').hide();
		$('#displayimage').hide();
		//set vars
		imagename = $('#'+ ID +' img.thumbimg').attr("name");
		curimg = parseInt($('div #'+ ID).attr("name"));
		headline = $('#'+ ID +' div.headline').html();
		caption =  $('#'+ ID +' div.caption').html();
		newcaption = "<b>"+headline+"</b>"+caption+"";
		//place vars
		$('#gallery .caption').html("<b>"+headline+"</b><br />"+caption);
		$('#displayimage').attr("src", '/data/upfiles/'+ imagename);
		$('.boxselected').attr("class", 'box');
		$('.thumb_row #'+ ID).attr("class", 'boxselected');
		checkposition(curimg);
		return false;
	};
	$('#displayimage').load(function() { //this will run once new image loads
		$('#displayimage').fadeIn();
		$('#gallery .caption').fadeIn();
		return false;
	});
	$('#next').click(function() {//advance 2 next image
		var nxtimg = parseInt(curimg) + 1;
		if (nxtimg <= parseInt(totalimages)) {
			ID = $('#'+ nxtimg +' div:first').attr("ID");
			changeimage(ID);
		};
		if (curimg > 4) {
			var imgsize = 166;
			var maxpos = $('#numimages').html();
			var maxpos = -((maxpos - 4) * imgsize);
			var pos = $('.thumb_row').css("margin-left");
			var textSplit = pos.split("px");
				 pos = textSplit[0];
			if (maxpos < pos) {
				$('.thumb_row').hide();
				pos = (pos - imgsize) + "px";
				$('.thumb_row').css("margin-left", parseInt(pos));
				$('.thumb_row').fadeIn();
			};
		};
		return false;
	});
	$('#prev').click(function() {
		var nxtimg = parseInt(curimg) - 1;
		if (nxtimg > 0) {
			ID = $('#'+ nxtimg +' div:first').attr("ID");
			changeimage(ID);
		};
			var imgsize = 166;
			var minpos = 0;
			var pos = $('.thumb_row').css("margin-left");
			var textSplit = pos.split("px");
				 pos = textSplit[0];
		if  (nxtimg <= parseInt(-(pos / imgsize))) {
			if (minpos > pos) {
				$('.thumb_row').hide();
				pos = (parseInt(pos) + parseInt(imgsize)) + "px";
				$('.thumb_row').css("margin-left", parseInt(pos));
				$('.thumb_row').fadeIn();
			};
		};	 
		return false;
	});
	function checkposition(pos) {//checks image position
		if (parseInt(pos) == 1) {
			$('#prev').hide();
		} else {
			$('#prev').show();
		};
		if (parseInt(pos) == parseInt(totalimages)) {
			$('#next').hide();
		} else {
			$('#next').show();
		};
		return false;
	};
	
});