﻿window.addEvent('domready', function () {
    news_ticker.init('news_content');
});

var news_ticker = {
    init: function(container_id) {
        this.showDuration = 3000;
        this.scrollDuration = 1000;
        this.list = $(container_id);
        this.handles = this.list.getParent().getElements('ul li a');
        this.handles.each( function(a,idx){ a.addEvent('click', function() { return news_ticker.load(idx);}); });
        this.load(0);
        return false;
    },
    load: function(type) {
        this.setSelected(type);
        if ( $chk(this.timer) ) clearInterval(this.timer);
        this.list.setStyle('top', 0);
        this.list.set('html', 'טוען...');
        new Request.HTML({ noCache: true, url: '/handlers/news_ticker.ashx', onSuccess: this.loaded.bind(this) }).get({ 'type': type});
    },
    loaded: function(tree, elements, html) {
        this.list.set('html', html);        
        /* settings */
        this.items = this.list.getElements('div.item');
        if ( this.items.length == 0 ) {this.list.set('html', 'אין חדש תחת השמש.. :)');return;}
        this.index = -1;
        this.height = this.items.pick().getSize().y;
        this.play = true;
        /* action func */
        this.move = function () { if (!this.play) return;this.list.set('tween', { duration: this.scrollDuration, onComplete: function () { if (this.index == this.items.length - 1) { this.index = - 1; } }.bind(this) }).tween('top', 0 - (++this.index * this.height)); };
        if (this.items.length > 3) { 
            this.move(); this.timer = this.move.bind(this).periodical(this.showDuration);
            this.list.addEvent('mouseover', function(){this.play=false;}.bind(this));
            this.list.addEvent('mouseout', function(){this.play = true;}.bind(this)); 
        } 
    },
    setSelected: function (type) {
        this.handles.removeClass('selected');
        this.handles[type].addClass('selected');
    }
}
