$(function() {


// add controls to the main picture
  
$("#photos .thumbs").prepend('<span class="controls"><a id="previous" href="#"><em>&#171;</em></a><a id="next" href="#"><em>&#187;</em></a></span>');
	
$(".pictures").before('<img id="loader" src="http://www.oceancityhilton.com/images/ajax-loader.gif" alt="" />');

// set up thumbs img for click event

$(".thumbs img").click(function(){
	
	var x = $(this).parent().attr('href');
	
	var y = $(this).attr("title");

	pic(x, y);
	
	$(".thumbs img").removeClass("selected");
	
	$(this).addClass("selected");
	
	return false;
})



// #next button: (1)set variable for currently selected thumbnail and (2)if the selected thumbnal is the last image, move to first image and set large picture to match or else (3) select the next thumb and set large picture

$("#next").click(function(){

	var n = $(".thumbs img").index($(".thumbs img.selected")[0]);  // (1)
	
	if(n==($(".thumbs img").length - 1)) { 		// (2)
	
	$(".thumbs img").removeClass("selected");
	
	$(".thumbs img").eq(0).addClass("selected");
	
	var x = $(".thumbs img").eq(0).parent().attr('href');	
	var y = $(".thumbs img").eq(0).attr("title");
	pic(x, y);
	 
	}
	
	else{	// (3)

//
	var x = $(".thumbs img").eq(n+1).parent().attr('href');	
	var y = $(".thumbs img").eq(n+1).attr("title");

	pic(x, y);

	$(".thumbs img").removeClass("selected");
 	$(".thumbs img").eq(n+1).addClass("selected");
	} 
	
	

})


// #previous button: same as next, only reversed

$("#previous").click(function(){

	var n = $(".thumbs img").index($(".thumbs img.selected")[0]);
	
	if(n==(0)) {
	
 	
	var lastImg = $(".thumbs img").length - 1;
	var x = $(".thumbs img").eq(lastImg).parent().attr('href');	
	var y = $(".thumbs img").eq(lastImg).attr("title");
	pic(x, y);
	
	$(".thumbs img").removeClass("selected");
 	$(".thumbs img").eq(lastImg).addClass("selected");

	}
	
	else{

	

//
	var x = $(".thumbs img").eq(n-1).parent().attr('href');	
	var y = $(".thumbs img").eq(n-1).attr("title");


  	pic(x, y);


	

	$(".thumbs img").removeClass("selected");
 	$(".thumbs img").eq(n-1).addClass("selected");
	}

})

function pic(source, title){

$('.picContainer').css('display','block').css('position','relative').height($('.pictures').height());

$("#loader").show();
$(".pictures").hide();
  
          
	$(".pictures img").attr({
		src: source
	});
	
	$(".pictures p").text(title)

		 $(".pictures img").load(function(){
		 	$("#loader").hide();
		 	$(".pictures").fadeIn(1000);
		 	$('.picContainer').css('display','block').css('position','relative').height($('.pictures').height());

		 	
		 	});
		
};




});

