/* Create a photo slideshow
TLB
May 3, 2011
*/
(function( $ ){
    $.fn.wmPhotoset = function(options) {
	return this.each(function() {
	    var numPhotos = $("#wm-photoset li").length;
	    if (numPhotos == 1) return;
	    var currentPhoto = 1;
	    
	    // hide all but the first photo
	    $("#wm-photoset li").hide();
	    $("#wm-photoset li").first().show();
	    
	    // create the bases for the previous and next buttons
	    var prevBtn = '<button id="prev-photo"></button>';
	    var nextBtn = '<button id="next-photo"></button>';
	    
	    // add navigation
	    pagination = '<div id="pagination">';
	    for (j = 1; j <= numPhotos; j++) {
		pagination += '<a name="goto-photo'+j+'"';
		pagination += '>'+j+'</a> ';
	    }
	    pagination += '</div>';
	    $(this).append('<div id="wm-photo-nav">'+prevBtn+nextBtn+pagination+'</div>');
	    
	    checkPrevNext();
	    $("#wm-photo-nav a:first-child").addClass("active");
	    $("#pagination a").click(function() {
		goToPhoto(parseInt($(this).attr("name").substr(10)));

	    });    
	    
	    $("#prev-photo").click(function() {
		goToPhoto(currentPhoto - 1);	
	    });
	    
	    $("#next-photo").click(function() {
		goToPhoto(currentPhoto + 1);	
	    });
	    
	    function checkPrevNext() {
		$('#prev-photo').removeAttr("disabled");
		$('#next-photo').removeAttr("disabled");
		if (currentPhoto == 1) {
		    $('#prev-photo').attr("disabled", "disabled");
		} else if (currentPhoto == numPhotos) {
		    $('#next-photo').attr("disabled", "disabled");
		}
	    }
	    
	    function goToPhoto(photoIndex) {
		if (photoIndex < 1) {
		    photoIndex = 1;
		} else if (photoIndex > numPhotos) {
		    photoIndex = numPhotos;
		}
		$("#wm-photoset li").fadeOut();
		$("#wm-photoset li:nth-child("+photoIndex+")").fadeIn();
		$("#wm-photo-nav a").removeClass("active");
		$("#wm-photo-nav a:nth-child("+photoIndex+")").addClass("active");
		currentPhoto = photoIndex;
		checkPrevNext();
	    }
	});
    }
}) ( jQuery );
