﻿(function ($) {
    $.fn.heroRotator = function (options) {
        var rootObj = this;
        var opts = $.extend({}, $.fn.heroRotator.defaults, options);
        var timerCookie = null;
        var current = 0;
        var heros = $("div.hero", rootObj);
        var buttonContainer = $("#hero-buttons", rootObj);

        if (heros.length == 0) {
            alert('No hero layers found');
            return;
        }

        if (buttonContainer.length != 1) {
//            alert('No button layer found');
            return;
        }

        for (i = 0; i < heros.length; i++) {
            var id = $(heros[i]).attr('id').replace('hero-', '');

            if (i == 0)
                buttonContainer.append('<a href="#" class="current-hero" id="btn-' + id + '">' + (i + 1) + '</a>');
            else
                buttonContainer.append('<a href="#" id="btn-' + id + '">' + (i + 1) + '</a>');
        }

        var buttons = $("#hero-buttons > a", rootObj);

        //--show first image if called for
        if (opts.animateInitialImage)
            changeHero($(buttons[current]));
        else
            wireTimer();

        //--wire click events
        $("#hero-buttons a", rootObj).each(
        function () {
            var link = $(this);
            link.click(function () {
                changeHero(link);
                return false;
            }
            );
        }
        );

        function wireTimer() {
            //--start timer
            if (timerCookie != null)
                clearTimeout(timerCookie);

            timerCookie = setTimeout(nextImage, opts.wait);
        }

        function nextImage() {
            if (current < buttons.length - 1)
                current++;
            else
                current = 0;

            changeHero($(buttons[current]));
        }

        function changeHero(selectedLink) {
            var id = selectedLink.context.id.replace("btn-", "");
            $("#hero-buttons a.current-hero").toggleClass("current-hero", false);
            selectedLink.addClass("current-hero", true);

            $("div.hero:visible", rootObj).fadeOut(opts.fade);
            $("#hero-" + id, rootObj).fadeIn(opts.fade);

            current = parseInt(id) - 1;
            wireTimer();
        }
    };
    // private function for debugging
    function debug(line) {
        if (window.console && window.console.log)
            window.console.log(line);
    };
    $.fn.heroRotator.defaults = {
        wait: 2000,
        fade: 400,
        animateInitialImage: false
    };
})(jQuery);

