// DHTML bidirectional marquee effect
// only initialize when all material has loaded
// otherwize not all dimensions may be known
Element.observe(window, 'load', function()
{
    new Marquee('homeclip', 2, 0.05);
});

// requires the id of the element that needs to slide
// this slide element should have a direct decendent that contains all images
// also, the slide element should perform some form of clipping
var Marquee = Class.create({
    initialize: function(el, step, interval)
    {
        // properties
        this.frame = el;
        this.speed = step;
        this.interval = interval;
        this.stop = false;
        var slideElm = $(this.frame).firstChild;
        // ad hoc determination of width of slide based on dimensions of images
        //var list = slideElm.select('img');
        var list = Element.select(slideElm, 'img');
        this.imgCount = list.length;
        this.slideWidth = 0;
        list.each(function(i)
        {
            this.slideWidth += i.width +
                parseInt(i.getStyle('padding-left')) + parseInt(i.getStyle('border-left-width')) + parseInt(i.getStyle('margin-left')) +
                parseInt(i.getStyle('padding-right')) + parseInt(i.getStyle('border-right-width')) + parseInt(i.getStyle('margin-right'));
        }, this);
        // assign id to slider
        slideElm.id = this.frame + '1';
        slideElm.absolutize();
        slideElm.setStyle({width: this.slideWidth + 'px'});
        var initLeft = parseInt(slideElm.getStyle('left'));
        // duplicate slider
        var tmpElm = slideElm.cloneNode(true); // deep copy
        tmpElm.id = this.frame + '2';
        $(this.frame).insert(tmpElm);
        $(this.frame + '2').setStyle({left: this.slideWidth + initLeft + 'px', width: this.slideWidth + 'px'});
        // events: stop on mouseover, start on mouseout
        $(this.frame).observe('mouseover', function() {this.stop = true}.bindAsEventListener(this));
        $(this.frame).observe('mouseout', function() {this.stop = false}.bindAsEventListener(this));
        // run
        new PeriodicalExecuter(this.run.bind(this), this.interval);
    },

    // run animation
    run: function()
    {
        if (!this.stop) {
            var pos1 = $(this.frame + '1').positionedOffset().left - this.speed;
            var pos2 = $(this.frame + '2').positionedOffset().left - this.speed;
            if (pos1 + this.slideWidth < 0) {
                // switch sections, place the old left section to the right the of new left section
                pos1 = pos2;
                pos2 = pos1 + this.slideWidth;
                $(this.frame + '1').id = 'tempsection';
                $(this.frame + '2').id = this.frame + '1';
                $('tempsection').id = this.frame + '2';
            }
            // move sections to the left
            $(this.frame + '1').setStyle({left: pos1 + 'px'});
            $(this.frame + '2').setStyle({left: pos2 + 'px'});
        }
    }
});

