$(document).ready(function() {

    var timerId = 0;
    var fadeTime = 1200;
    var i = 0;


    // preset HTML from non-DHTML to DHTML state (JavaScript enabled)
    $("#keypager ul").removeClass("invisible");
    var prevBanner = $('#banner_image1');
    prevBanner.addClass("hide_banner");
    prevBanner.show();


    var stop = function() {
        clearTimeout(timerId);
        timerId = 0;
    };

    var resume = function(e) {
    	// set wait time between banner changes
    	var pause = $('#banner_pause');
        timerId = window.setTimeout(e, parseInt(pause.val()));
    };

    // load next banner by timer
    var autoSwitchBanner = function() {
        var current = $('#banner_current_image');
        var nmbOfImg = $('#banner_number_of_images');
        if(current.val() != '') {
            var c = parseInt(current.val()) + 1;
            
            // reached end of list?
            if (c > parseInt(nmbOfImg.val()))
              c = 1;

            switchBanner(c);
            current.val(c);
        }
    }; 

    // switch to the new banner [i]
    var switchBanner = function(i) {

        if (i == 0) 
            return;

        stop();

        var banner = $('#banner_image'+i);
        var current = $('#banner_current_image');

        if(current.val() != i) {

            if(current.val() != '') {

                var c = parseInt(current.val());

                // prepare previous banner
                var prevBanner = $('#banner_image'+current.val());
                prevBanner.css("z-index", "10");

                // prepare new banner
                banner.hide();
                banner.css("z-index", "5");
                banner.show();

                // fade out an hide previous banner
                prevBanner.fadeOut(fadeTime);

                // activate hyperlink of the new banner
                $("#keypager a:eq(" + (i - 1) + ")").addClass("current");

                // deactivate hyperlink
                $("#keypager a:eq(" + (c - 1) + ")").removeClass("current");
            }

            // save the id of the current banner in the
            // hidden field for the next run
            current.val(i);    
        }

        resume(autoSwitchBanner);
    };


    // init keypager
    $("#keypager a").each(function(i) {
        i++;

        $(this).click(function() {
            switchBanner(i);
        });
    });

    resume(autoSwitchBanner);
});
