jQuery(document).ready(function($) {

    // Directory path of this plugin
    var plugin_directory = "/wp-content/plugins/bitvolution-image-galleria";

    // Thumbnail hover fade effects
    $('.gallery li img').hover(
        function() {jQuery(this).fadeTo('fast',1);},
        function() {jQuery(this).not('.selected').fadeTo('fast','0.3');}
    );

    // Allow user to click thumbnails to select main image
    $('.gallery li a').click(function() {

        var currentThumbLink = this;
        var currentGallery = jQuery(currentThumbLink).parents('div.gallery');

        jQuery(currentGallery).find('img.mainImage').each(function() {
            // Display a "loading" image so there is something in view until the proper one has downloaded
            jQuery(this).attr('src', plugin_directory+'/images/icons/loading.gif');
            // Display the proper image
            jQuery(this).attr('src', jQuery(currentThumbLink).attr('href'));
        });

        // Remove 'selected' from other thumbnails and add it to current one
        jQuery(currentGallery).find('img.selected').removeClass('selected').fadeTo('fast','0.3');
        jQuery(currentThumbLink).children('img').addClass('selected').fadeTo('fast',1);

        // Put black border around currently selected li element
        // jQuery(currentGallery).find("li").css('border','3px double #AAA');
        // jQuery(this).closest("li").css('border','3px double #000');

        return false;
    });

    // Allow user to click the image to go to the next one
    $('.gallery img.mainImage').click(function() {

        // Display a "loading" image so there is something in view until the proper one has downloaded
        jQuery(this).attr('src', plugin_directory+'/images/icons/loading.gif');

        var currentGallery = jQuery(this).parents('div.gallery');

        var selectedThumb = jQuery(currentGallery).find('img.selected');

        var selectedLI = jQuery(selectedThumb).closest("li");
        var nextLI = jQuery(selectedLI).is(':last-child') ? jQuery(selectedLI).siblings(':first-child') : jQuery(selectedLI).next();

        // Remove 'selected' from other thumbnails and add it to current one
        jQuery(currentGallery).find('img.selected').removeClass('selected').fadeTo('fast','0.3');
        jQuery(nextLI).find('img').addClass('selected').fadeTo('fast',1);

        // Display the proper image
        jQuery(this).attr('src', jQuery(nextLI).find('a').attr('href'));

        // Put black border around currently selected li element
        // jQuery(currentGallery).find("li").css('border','3px double #AAA');
        // jQuery(nextLI).css('border','3px double #000');
    });

});
