﻿(function($) {

    $.fn.JGallery = function(options) {

        // default configuration properties
        var defaults = {
            showCaption: true
        };

        var opts = $.extend(defaults, options);

        var index = 0;

        $('ul#gallery-list').each(function() {
            $('ul#gallery-list li img').addClass('gallery-element');

            $(this).click(
                function($e) {
                    var _src = $e.target.src;
                    $('div#gallery-viewport img').replaceWith('<img src=' + _src + ' alt="none" style="opacity:0"/>\n');
                    $('div#gallery-viewport img').animate({ opacity: '1' }, 2000);

                    var cap = $e.target.alt;
                    $('div#gallery-caption span').replaceWith('<span>' + cap + '</span>');
                });
        });

        var obj = $(this);
        var s = $("li", obj).length;

        $("ul#gallery-list").css({
            width: (s + 1) * 110,
            height: 102
        });

        //Need to add id's and wrap the list with gallery-slider.
        $(this).prepend('<div id="gallery-viewport"></div>');
        var pic = $('ul#gallery-list li img').attr('src');
        var cap = $('ul#gallery-list li img').attr('alt');
        $('div#gallery-viewport').append('<img src=' + pic + ' alt="none" />\n');
        $('div#gallery-viewport').append('<div id="gallery-caption"></div>');
        $('div#gallery-caption').append('<span>' + cap + '</span>');

        $('img#left').click(function($e) {
            previous($e);
        });

        $('img#right').click(function($e) {
            next($e);
        });
        
        $('div#gallery-slider').hover(function() {
            $('img#right').css('opacity', .7);
            $('img#left').css('opacity', .7);
        }, function() {
            $('img#right').css('opacity', 0);
            $('img#left').css('opacity', 0);
        });

        if (opts.showCaption) {
            $('div#gallery-viewport').hover(function() {
                $('div#gallery-caption').animate({ opacity: '.5' }, 500);
            }, function() {
                $('div#gallery-caption').animate({ opacity: '0' }, 500);
            });
        }

        function next($e) {
            var ml = $('ul#gallery-list').css('margin-left');
            var val = parseInt(ml);
            index = Math.abs(val / 110);
            if (index < (s - 5)) {
                ml = val + -110;
                $('ul#gallery-list').animate({ marginLeft: ml });
            }
        };

        function previous($e) {
            var ml = $('ul#gallery-list').css('margin-left');
            var val = parseInt(ml);
            index = Math.abs(val / 110);
            if (index > 0) {
                ml = val + 110;
                $('ul#gallery-list').animate({ marginLeft: ml });
            }
        };
    };
})(jQuery);


