var scrolling = false;
var pBtn = new Button($('#prevButton'));
var nBtn = new Button($('#nextButton'));

$(document).ready(function () {
	$('#hotspotLeft').click(function() {if (cID!=0) scrollPhotos(-1); });
	$('#hotspotLeft').hover(
		function(){if (cID!=0) pBtn.show();}, 
		function(){pBtn.hide();}
	);
		
	$('#hotspotRight').click(function() {if (cID!=maxID+1) scrollPhotos(1); });
	$('#hotspotRight').hover(
		function(){if (cID!=maxID+1) nBtn.show();}, 
		function(){nBtn.hide();}
	);
		
	getPic(1);
	getPic(-1);
	
	setCaption();
});

function setCaption() {$('#caption p').html($('.mainPic img').attr('alt'));}

// define a simple Button class
function Button(el) {
	this.el = el;
	this.show = function() {this.el.css('display', 'block');}
	this.hide = function() {this.el.css('display', 'none');}
}

function scrollPhotos(i) {

	// only one scrolling effect at a time, please!
	if (scrolling) return false;
	scrolling = true;

	var el = $('#wrap');

	// hide the buttons while scrolling
	pBtn.hide();
	nBtn.hide();
	
	// get scroll-to position
	var curPos = parseInt(el.css('margin-left'));
	var newPos = curPos + (-722 * i);
	
	el.animate({marginLeft:newPos+'px'}, 'normal', function(){
		// strip old photo styles
		$('.nextPic').removeClass('nextPic');
		$('.mainPic').removeClass('mainPic');
		$('.prevPic').removeClass('prevPic');

		// update cID counter
		cID += i;

		// assign new photo styles
		assignDisplayClasses();
		setCaption();
		
		if (i==1 && cID!=maxID+1) nBtn.show();
		else if (i==-1 && cID!=0) pBtn.show();
		
		getPic(i);
		
		// mark scrolling complete
		scrolling = false;
	});

}
	
function getPic(i) {
	var getID = cID + (2 * i);
	
	// check if outside extant pics
	if (getID < 0 || getID > maxID+1) return false; 
	
	// check if already downloaded
	if (jQuery.inArray(getID, aIDs) != -1) return false;
	else {
		// insert the DIV before calling the AJAX
		s = '<div class="pic" id="p' + getID + '"><img src="/img/loader.gif" height="466px" width="700px" /><' + '/div>';
		
		var el = $('#wrap');
		var nWidth = el.width() + 722;
		var nPos = parseInt(el.css('margin-left')) - 722;
			
		if (i==1) el.append(s).css('width',nWidth+'px');
		else el.prepend(s).css({'margin-left':nPos+'px','width':nWidth+'px'});

		if (getID == 0 || getID == maxID+1) {
			$('#p'+getID+' img').attr({
					alt: 'the end',
					src: '/img/img_end.jpg'
				});
			aIDs.push(getID);
		} else {
			$.getJSON('getPhoto.php',{id:getID},function(r){
				$('#p'+getID+' img').attr({
						alt: r.caption,
						src: '/img/img_' + r.photo + '.jpg'
					});
						
				aIDs.push(parseInt(r.id));
			});
		}
	}
}

function assignDisplayClasses() {
	if (!$('#p'+(cID-1)).hasClass('prevPic')) $('#p'+(cID-1)).addClass('prevPic');
	if (!$('#p'+cID).hasClass('mainPic')) $('#p'+cID).addClass('mainPic');
	if (!$('#p'+(cID+1)).hasClass('nextPic')) $('#p'+(cID+1)).addClass('nextPic');
}