$(document).ready(function(){

var enableClick = true;	

	function doSlideAnimation(leftPosition){
		enableClick = false;		
		$("#galleryContainer").animate({
			"left" : "-"+leftPosition+"px"
		}, 500, function(){
			enableClick = true;
		})

	}

	var itemWidth = 510;
	var totalItems = $("#gallery .item").length;
	var totalItemWidth = totalItems * itemWidth;
	
	
		$("#gallery .item").click(function(){
			
			var leftPosition = $("#galleryContainer").css("left").replace("px","").replace("-","");
			leftPosition = parseInt(leftPosition) + parseInt(itemWidth);
			
			if (leftPosition == (totalItemWidth - itemWidth)){
				firstImgSrc = $("#galleryContainer .item:first img").attr("src");
				firstImgTitle = $("#galleryContainer .item:first h2.blackTitleRight").text();

				$("#galleryContainer").append('<div class="item rewind"><img src="'+firstImgSrc+'" width="420" height="272" alt="ETS/Acas" /><div class="itemTitle rewind"><h2 class="blackTitleRight">'+firstImgTitle+'</h2></div></div>');

			
			} else if (leftPosition == totalItemWidth){
				leftPosition = 0;
			}
			
			else if (leftPosition > totalItemWidth){
				$("#galleryContainer .rewind").remove();
			}
			
			if (enableClick) {
				doSlideAnimation(leftPosition);
			}
		})	
})
