﻿jQuery(document).ready(function() {
    try {
        ActivateCarousel();
    } catch (e) {
        DhtmlLoadScript("/scripts/jquery.jcarousel.pack.js");
        ActivateCarousel();
    };

    function equalHeight(group) {
        tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }
    equalHeight($("#panels .grid_4"));

    jQuery.jcarousel.fn.startAuto = function(s) {

    var containerWidth = $('ul#carousel').width();
    var totalItems = $('ul#carousel li').length;
    var itemWidth = (containerWidth / totalItems);
    var totalShown = Math.floor(totalItems - 3);
    var cutMeOff = -(totalShown * itemWidth);
    var locationPlease = $('#carousel').position();
    var doItNow = locationPlease.left;
    
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0 || doItNow == cutMeOff)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        }

});

function mycarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function ActivateCarousel() {
    jQuery('#carousel').jcarousel({
        start: 1,
        auto: 4,
        wrap: 'last',
        animation: 2000,
        initCallback: mycarousel_initCallback
    });
}