/**
 * Created by JetBrains PhpStorm.
 * User: thomaskasper
 * Date: 20.10.11
 * Time: 12:34
 * To change this template use File | Settings | File Templates.
 */

$(function() {
    var newsFader = new NewsFader();
});

function NewsFader() {
    this.TIMEOUT_LENGTH = 5000;
    this.$newsContainer = $('#news .news-list-container');
    this.$newsContainerHeight = 0;
    this.$newsItemContainer = $('#news .news-list-container .news-list-item');
    this.itemsCount = this.$newsItemContainer.length;
    this.timeoutHandler = null;
    this.currentElement = 0;
//    Wenn gewünscht einblenden
//    this.adjustHeight();
    this.hideItems();
    this.showFirstItem();
    if(this.itemsCount > 1) {
        this.setTimeout();
    }
}

NewsFader.prototype.hideItems = function() {
    this.$newsItemContainer.each(function(){
        $(this).hide();
    });
};

NewsFader.prototype.showFirstItem = function() {
    this.$newsItemContainer.first().show();
};

NewsFader.prototype.fadeItem = function() {
    var _this = this;
    this.$newsItemContainer.eq(this.currentElement).fadeOut(1000,function() {
        _this.currentElement++;
        if(_this.currentElement >= _this.itemsCount) {
            _this.currentElement = 0;
        }
        _this.$newsItemContainer.eq(_this.currentElement).fadeIn(1000, function() {
            _this.setTimeout();
        });
    });
};

NewsFader.prototype.adjustHeight = function() {
    var _this = this;
    var currentElementHeight;
    this.$newsItemContainer.each(function() {
        currentElementHeight = $(this).height();
        if( currentElementHeight > _this.$newsContainerHeight) {
            _this.$newsContainerHeight = currentElementHeight;
        }
    });
    this.$newsContainer.css('height', this.$newsContainerHeight);
}

NewsFader.prototype.setTimeout = function() {
    var _this = this;
    this.clearTimeout();

    this.timeoutHandler = window.setTimeout(
        function() {
            _this.hideItems();
            _this.fadeItem();
        },
        this.TIMEOUT_LENGTH
    );
};

NewsFader.prototype.clearTimeout = function() {
    if(null != this.timeoutHandler) {
        window.clearTimeout(this.timeoutHandler);
        this.timeoutHandler = null;
    }
};
