
var playPhotos = true;
var playPhotosDelay = 3000;
var photosTransition = 500;

// On DOM ready
jQuery(function() {
    if(jQuery('div#photoViewer').length > 0 ) {
        initPhotoViewer();
    }
});

function initPhotoViewer() {

    playThroughPhotos();

    jQuery('div#photoViewer').hover(
        function() { jQuery('div#photoController').animate({ right: "20px" }, 200, "linear" ) }, 
        function() { jQuery('div#photoController').animate({ right: "-205px" }, 200, "linear" ) } 
/* For fadeIn controllers
        function() { jQuery('div#photoController').fadeIn(200) }, 
        function() { jQuery('div#photoController').fadeOut(400) } 
*/
    );
    
    jQuery('#photoPrevious a').click( function(e) {
        e.preventDefault();
        navigateThroughPhotos('prev');
        jQuery('#photoPause').hide();
        jQuery('#photoPlay').show();
        playPhotos = false;
    });

    jQuery('#photoNext a').click( function(e) {
        e.preventDefault();
        navigateThroughPhotos('next');
        jQuery('#photoPause').hide();
        jQuery('#photoPlay').show();
        playPhotos = false;
    });

    jQuery('#photoPlay a').click( function(e) {
        e.preventDefault();
        jQuery('#photoPlay').hide();
        jQuery('#photoPause').show();
        playPhotos = true;
        playThroughPhotos();
    });

    jQuery('#photoPause a').click( function(e) {
        e.preventDefault();
        jQuery('#photoPause').hide();
        jQuery('#photoPlay').show();
        playPhotos = false;
    });

    jQuery('#photoView a').click( function(e) {
        e.preventDefault();
    });

}

function navigateThroughPhotos(direction) {
        var el = jQuery('div#photoViewer div.active');
        var nextElem = 0;
        if(direction == 'next'){
            if(jQuery(el).next('div.item').length > 0 ) {
                nextEl = jQuery(el).next('div.item');
            } else {
            
                nextEl = jQuery(el).parent('div').children('div.item:first');
            }
        } else {
            if(jQuery(el).prev('div.item').length > 0 ) {
                nextEl = jQuery(el).prev('div.item');
            } else {
            
                nextEl = jQuery(el).parent('div').children('div.item:last');
            }
        }
        jQuery(el).fadeOut(photosTransition);
        jQuery(el).removeClass('active');
        jQuery(nextEl).fadeIn(photosTransition);
        jQuery(nextEl).addClass('active');
}

function playThroughPhotos() {
    if(playPhotos==true) {
        navigateThroughPhotos('next');
        setTimeout(function() {
            playThroughPhotos()
          }, playPhotosDelay);
    }
}