var Ticker = Class.create({
    initialize: function(container, options) {
        this.container = container;
        this.options = Object.extend(options || {},{
            frequency: 500,
            item_frequency: 1000,
            char_frequency: 50,
            endBits: ['_','-'],
            readMore: "news-read-more",
            defaultButton: "/img/more.png",
            pdfButton: "/img/d-pdf.png"
        });
        this.current = 0;
        this.currentChar = 0;
        this.startTick();
    },
    startTick: function() {
        this.container.each(function(item) {
            item.hide();
        });
        setTimeout(this.onTick.bind(this), this.options.frequency);
    },
    onTick: function() {
        if(this.currentChar==0) {
            if (this.current_item) {
                this.current_item.hide();
            }
            this.current_item = this.container[this.current%this.container.length];
            this.current_item.show();
            this.current_element = this.current_item.firstDescendant()
            this.current_title = this.current_element.innerHTML;
            this.current++;

            var url = this.current_item.childElements()[0].href;
            var ext = url.split('.').pop();
            var button = this.options.defaultButton;

            if (ext == 'pdf') {
                button = this.options.pdfButton;
            }

            // Set the read more link to the current item's link
            $(this.options.readMore).href = url;
            $$('#' + this.options.readMore + ' img')[0].src = button;
        }

        this.current_element.innerHTML = this.current_title.substring(0,this.currentChar) + this.options.endBits[this.currentChar&this.options.endBits.length-1];
        if(this.currentChar==this.current_title.length) {
            this.current_element.innerHTML = this.current_title.substring(0,this.current_title.length);
            this.currentChar=0;
            var t = this.options.item_frequency || 1000;
        } else {
            this.currentChar++;
            var t = this.options.char_frequency || 50;
        }
        setTimeout(this.onTick.bind(this),t);
    }
});


