﻿$(document).ready(function() {
    // get the width of the images to be rotated, including any right margin you have
    var picWidth = $(".rotator li:first").width() + parseInt($(".rotator li:first").css("marginRight"));

    // get the total number of images and total scrolling size
    var numPics = $(".rotator li").size();
    var totalWidth = picWidth * numPics;
    var currentPic = 0; 	// used for scrolling
    var picCounter = 1; 	// used for caption total counter

    //add arrows
    $(".rotator-container").prepend("<a href='#' class='leftArrow'></a>").append("<a href='#' class='rightArrow'></a>");

    //add total counter to caption
    $(".caption").each(function() {
    $(this).append("<em class='counter'>Image " + picCounter + " of " + numPics + "</em>");
        picCounter++;
    });
    updateElements();

    //set actions on left and right arrows
    $(".leftArrow").click(function() {
        if (currentPic > 0) {
            currentPic--;
            updateElements();
        }
		// The following sets the picture to the last one.
		else
		{
			currentPic = numPics - 1;
			updateElements();
		}
		
        return false;
    });

    $(".rightArrow").click(function() {
        if (currentPic < numPics - 1) {
            currentPic++;
            updateElements();
        }
		// The following sets the picture to the first one.
		else
		{
			currentPic = 0;
			updateElements();
		}
		
        return false;
    });

    //this function updates the height and position of the rotator
    function updateElements() {
        //resize box to account for varying caption length
        var currentHeight = $(".rotator li:nth-child(" + (currentPic + 1) + ")").height();
        $(".rotatorShell").height(currentHeight);

        //scroll rotator box
        $(".rotator").animate({ marginLeft: -(picWidth * currentPic) },0);
    };
});

