// Newsticker Component

var Newsticker = Class.create();
Newsticker.prototype = {
    initialize: function(obj)
    {
        this.elem        = obj;
        this.items       = $A();
        this.active_item = null;
        this.paging      = null;
        this.height      = 0;

        this.initItems();

        if (this.items.length > 0) this.items[0].show();
        if (this.height > 0 )
          this.elem.style.height = this.height+"px";

        new PeriodicalExecuter(this.cycle.bind(this), 5);
    },
    cycle: function()
    {
      try {
        var active_item = this.items.indexOf(this.active_item)+1;
        if (active_item == this.items.length) active_item = 0;
        this.items[active_item].show();
      }
      catch(e) {
        // silent catch: cycle not possible
      }
    },
    createPaging: function()
    {
        var paging_container = new Element("ul", {"class": "paging"});
        this.elem.appendChild(paging_container);
        this.paging = paging_container;
    },
    initItems: function()
    {
        var items = $A(this.elem.select(".entry"));

        if (items.length == 0) {  // no paging needed if there is only one item
          return;
        }
        if (items.length == 1) { // no paging needed if there is only one item
          this.height = items[0].getHeight();
          return;
        }
        this.createPaging();

        items.each(function(item) {
            var news_item = new Newsitem(item, this);
            if (news_item.height > this.height) this.height = news_item.height;
        }.bind(this))
    }
}

var Newsitem = Class.create();
Newsitem.prototype = {
    initialize: function(obj, parent)
    {
        this.elem   = obj;
        this.parent = parent;
        this.height = this.elem.getHeight();

        this.parent.items.push(this);
        this.createPagingItem();
        this.elem.hide();
    },
    createPagingItem: function()
    {
        this.paging_item = new Element('li').update(new Element('a', { "href": '#' }).update("paging"));
        Event.observe(this.paging_item, "click", this.show.bindAsEventListener(this), false);
        this.parent.paging.appendChild(this.paging_item);
    },
    show: function(e)
    {
        if (e) Event.stop(e);
        if (this.parent.active_item != null) this.parent.active_item.hide();

        this.parent.active_item = this;
        Effect.Appear(this.elem);
        this.paging_item.addClassName("active");
    },
    hide: function()
    {
        Effect.Fade(this.elem);
        this.paging_item.removeClassName("active");
    }
}

function initNewsticker() {
    var newstickers = $A($$(".hw_news"));
    newstickers.each(function(obj)
    {
        new Newsticker(obj);
    });
}

utiljs_registerWindowOnloadFunction(initNewsticker);

