(function($){

    var defaultVars = {
        loops: 1,
        timeOut: 4000,
        stopAt: 'first'
    };

    $.fn.rexxReferenceSlider = function(vars) {

        vars = (vars != undefined) ? vars : {};
        vars = $.extend({}, defaultVars, vars);

        var element = this;

        var timeOut = vars.timeOut;
        var loops   = vars.loops;
        
        $(element).find('li:not(:first)').css({
            'z-index': 1,
            opacity: 0,
            display: 'none'
        });

        var current = $(element).find('li:first').css({
            'z-index': 2,
            opacity: 1,
            display: 'block'
        });

        var slide = function() {

            var loop = current.prop('loop');
            loop = loop != undefined ? loop : 0;

            if(loop >= loops && loops != 0) {
                return;
            }

            current.prop('loop', (parseInt(loop)+1));

            var next = current.next();
            
            if(next.length <= 0 && vars.stopAt == 'last' && vars.loops > 0) {
                return;
            }
            
            next = (next.length > 0) ? next : $(element).find('li:first');

            next.css({
                display: 'block'
            });

            next.css({
                'z-index': 3
            });

            setTimeout(function() {
                next.animate({opacity: 1},(timeOut/2), function() {
                    current.css({
                        'z-index': 1,
                        opacity: 0,
                        display: 'none'
                    });
                    next.css('z-index', 2);
                    current = next;
                    slide();
                });
            }, (timeOut/2));
        }

        slide();
    }

})(jQuery);



$(document).ready(function() {
    $('#referenceImages').rexxReferenceSlider({loops: 0});
});
