﻿
(function ($) {
    $.fn.bannerFlipper = function (options) {
        var rootObj = this;
        var opts = $.extend({}, $.fn.bannerFlipper.defaults, options);
        var timerCookie = null;
        var current = 0;
        var buttons = $("div.photobutton > a", rootObj);

        //--check that we have images and buttons
        if (buttons.length == 0) {
            //alert('No buttons found');
            return;
        }


        if ($("div.photo", rootObj).length == 0) {
            alert('No photos found');
            return;
        }

        //--wire click events and fade the images.
        $("div.photobutton a", rootObj).each(
        function () {
            var link = $(this);
            link.click(function () {
                changeImage(link);
                return false;
            }

            );
            $(this).children("img").fadeTo(opts.fade, opts.buttonOpacity);
        }
        );

        //--show first image if called for
        if (opts.animateInitialImage)
            changeImage($(buttons[current]));
        else
            wireTimer();



        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;

            changeImage($(buttons[current]));
        }

        function changeImage(selectedLink) {
            var id = selectedLink.context.id.replace("photobutton-", "");
            debug(id);
            $("div.photobutton a.current-photo img").fadeTo(opts.fade, opts.buttonOpacity);
            $("div.photobutton a.current-photo").toggleClass("current-photo", false);
            //debug($("div.photobutton a.current-photo").children().length);
            selectedLink.addClass("current-photo", true);
            $(selectedLink).children("img").fadeTo(opts.fade, 1);
            //debug($(selectedLink).children("img").length);
            //debug($(selectedLink).children("img").length);

            $("div.photo:visible", rootObj).fadeOut(opts.fade);
            $("div.phototext:visible", rootObj).fadeOut(opts.fade);

            $("#phototext-" + id, rootObj).fadeIn(opts.fade);
            $("#photo-" + 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.bannerFlipper.defaults = {
        wait: 2000,
        fade: 400,
        buttonOpacity: 0.2,
        animateInitialImage: true
    };
})(jQuery);
