﻿(function ($) {
    $.fn.simpleSpy = function (options) {
        // declare defaults
        var settings = {
            buffer: 0,
            direction: 'vertical', // needed to determine direction of wrapping div
            interval: 4000,
            limit: 4
        };
        if (options) {
            var options = $.extend(settings, options);
        }
        return this.each(function () {
            // if user declares defaults, change default
            // variable values to user-defined values
            var o = options;
            // 1. Set Up
            //Capture Cache of all items
            //limit number of <li> tags to number of  "var limit"
            var $list = $(this),
                items = [],
                currentItem = o.limit + 1,
                total = 0,
                height = $list.find('> li:first').height(),
                width = $list.find('> li:first').width();

            $list.find('> li').each(function () {
                items.push('<li>' + $(this).html() + '</li>');
            });
            total = items.length;
            if (o.direction == 'vertical') {
                var divHeight = (height * o.limit) + o.buffer
                $list.wrap('<div class="spyWrapper" />').parent().css({ height: divHeight });
            } else if (o.direction == 'horizontal') {
                var divWidth = (width * o.limit) + o.buffer
                $list.wrap('<div class="spyWrapper" />').parent().css({ width: divWidth });
            }
            $list.find('> li').filter(':gt(' + (o.limit - 1) + ')').remove();
            // 2. Animate
            function spy() {
                // insert new item with opacity and height/width of 0
                var $insert = $(items[currentItem]).css({
                    height: 0,
                    width: 0,
                    opacity: 0
                }).prependTo($list);
                // fade last item out
                $list.find('> li:last').animate({ opacity: 0 }, 1000, function () {
                    $insert.animate({ width: width, height: height }, 1000).animate({ opacity: 1 }, 1000);
                    // simultaneously fade out last item
                    $(this).remove();
                });
                currentItem++;
                if (currentItem >= total) {
                    currentItem = 0;
                }
                miscFunction();
                setTimeout(spy, o.interval);
            }
            spy();
        });
    };
})(jQuery);

function miscFunction() {
    $("a[rel^='prettyPhoto']").prettyPhoto({
        theme: 'dark_rounded'
    });
}
