
var osis = (osis) ? osis : {};

osis.headline = {};

osis.headline = function( title, data ){
    this.data = data;
    
    var header = jQuery('#header');
    
    var title_anchor = jQuery('<span class="blueFont"></span>');
    title_anchor.html(title);
    var outer = jQuery('<div class="headlineContainer">');
    var outer2 = jQuery('<div class="headlineTitle">');
    outer2.html(title_anchor);
    this.container = jQuery('<div class="headlineContent"><div></div></div>');
    
    header.append(outer);
    outer.append(outer2);
    outer.append(this.container);

    this.showTime = 6000;
    this.speed = 1000;
    this.position = 0;
    this.timer;
    this.pause = false;
    this.shownAtLeastOnce = false;
    this.showNext();
};
 
osis.headline.prototype.getNext = function() {
    if( this.data.length < 1 ) {
        return null;
    }

    if( this.position >= this.data.length ) {
        this.position = 0;
    }

    var data = this.data[this.position];
    this.position++;
    return data;
};
 
 osis.headline.prototype.createHeadline = function( obj ) {
    var self = this;
    if( obj !== null ) {
        var div = jQuery('<div>');
        var a = jQuery('<a>');
        a.attr('href', '/insd/news.php?ins=' + obj.key);
        a.text(obj.headline);
        div.html(a);
        div.hide();
        div.mouseover(function(){
            //jQuery(this).css({"background": "#99ccff"});
            clearTimeout(self.timer);
            self.pause = true;
        }).mouseout(function(){
            //jQuery(this).css({"background": "#FFF"})
            clearTimeout(self.timer);
            self.pause = false;
            self.timer = setTimeout(function(){
                self.showNext();
            }, self.showTime);
        });
        
        return div;
    }
};
 
osis.headline.prototype.showNext = function() {
    if( this.pause == true ) {
        return false;
    }

    if( this.data.length == 1 && this.shownAtLeastOnce == true ) {
        return false;
    }

    var self = this;

    var next = this.getNext();

    if( next !== null ) {
        
        var div = this.createHeadline( next );
        jQuery('div', this.container).fadeOut(self.speed, function(){
            jQuery(this).remove();
            
            self.container.html(div);
            div.fadeIn(self.speed, _showNext);
        });
        this.shownAtLeastOnce = true;
    }

    var _showNext = function() {
        self.timer = setTimeout(function(){
            self.showNext();
        }, self.showTime)
    }
};

osis.createHeadlines = function( title, data ) {
    new osis.headline(title, data);
};
