(function($){"use strict";

$('.sp-widget-showcase').live('registered', function() {
    var $showcase = $(this).find('.sp-showcase-simple_horizontal');

    if ($showcase.length == 0) {
        return;
    }

    var $area = $('.sp-showcase-area', $showcase).append("<ul/>");
    var $items = $('.sp-showcase-items', $showcase);

    function display($item) {
        var $cur = $(">ul>li", $area);
        var $new = $item.clone();

        $item.addClass("sp-state-active").animate({ marginTop: "-10px" }, 200);
        $item.siblings().filter(".sp-state-active").removeClass("sp-state-active").animate({ marginTop: 0 }, 500);

        if ($new.is(".sp-showcase-type-video")) {
            $new.click(function() {
                $items.fadeOut();

                var $video = $('.sp-showcase-item-video-overlay', $new);

                shiftpress.media_player($video, {
                    url: $('.sp-showcase-item-media-url', $new).attr('href'),
                    autoplay: 1,
                    width: 660,
                    height: 364
                });

                clearTimeout(timer);
            });
        }

        $('.sp-showcase-item-title', $new).after('<span class="sp-readmore"><span class="sp-arrow">&gt;</span> Full Story</span>');

        $cur.css({ zIndex: 4 });
        $new
            .css({ zIndex: 5, marginTop: 0 })
            .hide()
            .fadeIn(function() { $cur.remove(); })
            .appendTo($("ul", $area))
        ;

        restartRotate();
    }

    $('>ul>li', $items)
        .hover(function() {
            if (!$(this).is(".sp-state-active")) {
                $(this).stop().animate({ marginTop: "-10px" }, 100);
            }
        }, function() {
            if (!$(this).is(".sp-state-active")) {
                $(this).stop().animate({ marginTop: "0" }, 500);
            }
        })
        .click(function() { display($(this)); })
    ;
    
    var timer = null;
    var rotateDelay = 5000;

    function rotate() {
        var $item = $(">ul>li.sp-state-active", $items).first();

        if ($item.length > 0) {
            $item = $item.next();
        }

        if ($item.length == 0) {
            $item = $(">ul>li:first-child", $items);
        }

        display($item);
    }

    function restartRotate() {
        clearTimeout(timer);
        timer = setTimeout(rotate, rotateDelay);
    }


    $(window).blur(function() { clearTimeout(timer); }).focus(function() { restartRotate(); });

    rotate();

    $('.sp-showcase-item-title, .sp-readmore', $area).live('click', function() {
        var $item = $(this).closest('li');
        var url = $('.sp-showcase-item-url', $item).attr('href');
        window.location.href=url;
    });
});

})(jQuery);

