// remap jQuery to $
(function($){})(window.jQuery);

$(document).ready(function (){

    var slideshowSpeed = 4000;
    var slideshowFadeSpeed = 1000;
    var interval;
    var activeContainer = 1;
    var numPhotos = 0;
    var currentImg = 0;
    var leftSide = true;
    var animating = false;
    var currentZindex = -1;
    
    /**
     * Handles determining which photo to show next.
     */
    var navigate = function() {
        if (animating) return;
        
        currentImg++;
        if (currentImg == photos.length + 1) {
            currentImg = 1;
        }

        showImage(photos[currentImg - 1]);
    };
    
    /**
     * Show an image.
     */
    var showImage = function(photoObj) {
        animating = true;
        
        // reference both current images
        var $leftImg = $('#img-block-left').find('img');
        var $rightImg = $('#img-block-right').find('img');
        
        // get the next image in the queue
        var $nextImg = $('<img src="' + photoObj.image + '" />').css('z-index', 1);
        
        // update the old image z-indexes to allow new ones on bottom
        $leftImg.css('z-index', 2);
        $rightImg.css('z-index', 2);
        
        // determine if fading in left or right image
        if (leftSide) {
            // append next image in set
            $nextImg.appendTo('#img-block-left');
            // update the left image
            $leftImg.fadeOut(slideshowFadeSpeed, function() {
                $leftImg.remove();
            });
        } else {
            // append next image in set
            $nextImg.appendTo('#img-block-right');
            // update the right image
            $rightImg.fadeOut(slideshowFadeSpeed, function() {
                $rightImg.remove();
            });
        }
        
        // alternate side
        leftSide = !leftSide;
        
        // set to non-animating
        setTimeout(function() {
            animating = false;
        }, slideshowFadeSpeed);
    };

    // if we have photos
    if (typeof photos != 'undefined') {
        // get the length of photos
        numPhotos = photos.length;
        if (numPhotos > 2) {
            
            // reverse the array
            photos.reverse();
            
            // set interval for updating photos
            interval = setInterval(function() {
                navigate();
            }, slideshowSpeed);
        }
    }
});
