/* @requires jQuery, jQuery-scrollTo, river, timeline */

var HistoryBrowser = function(timestamps, items, id, options) {
    this.timestamps = timestamps;
    this.items = items;
    this.element = jQuery("#" + AXIS.escapeCSS(id));
    this.options = options || {};

    /* inject the div's required for river, timeline and lens */
    this.timeline_id = id + "-timeline";
    this.river_id = id + "-river";
    this.lens_id = id + "-lens";

    this.element.append(jQuery(
        '<div id="' + this.timeline_id + '" class="history-timeline">' +
            '<div id="' + this.lens_id + '" class="history-lens"></div>' +
        '</div>' +
        '<div id="' + this.river_id + '" class="history-river"></div>'
    ));

    /* initialize the river, timeline and lens */
    this.timeline = new Timeline(this.timestamps, this.timeline_id);
    this.river = new River(this.items, this.river_id, this.options);

    /* compute points_accum */
    this.points_accum = [];
    this.points_accum[0] = this.timeline.points[0];
    var i;
    for(i=1; i<this.timeline.points.length; i++) {
        this.points_accum[i] = this.timeline.points[i] + this.points_accum[i-1];
    };

    /* register listeners */
    jQuery("#" + AXIS.escapeCSS(this.timeline_id)).click(jQuery.context(this, this.onTimelineClick));
    jQuery("#" + AXIS.escapeCSS(this.river_id)).scroll(jQuery.context(this, this.onRiverScroll));
};

HistoryBrowser.prototype = {
    get_position: function(river_index) {
        var i = 0;
        while(i < this.points_accum.length && this.points_accum[i] < river_index) {
            i++;
        }
        return i;
    },

    onTimelineClick: function(e) {
        var i = Math.floor((e.clientY - jQuery("#" + AXIS.escapeCSS(this.timeline_id)).offset().top - this.timeline.H0)/this.timeline.delta);
        var index = this.points_accum[i];
	if (jQuery("#" + AXIS.escapeCSS(this.river_id) + '-' + index).length) {
            var offset = jQuery("#" + AXIS.escapeCSS(this.river_id) + '-' + index).offset().top - jQuery("#" + AXIS.escapeCSS(this.river_id)).scrollTop();
            jQuery("#" + AXIS.escapeCSS(this.river_id)).scrollTo({ top: offset }, 800);
	}
    },

    onRiverScroll: function() {
        var index_i = Math.ceil(jQuery("#" + AXIS.escapeCSS(this.river_id)).scrollTop()/jQuery("#" + AXIS.escapeCSS(this.river_id) + '-1').height());
        var num_entries = Math.floor(jQuery("#" + AXIS.escapeCSS(this.river_id)).height() / jQuery("#" + AXIS.escapeCSS(this.river_id) + '-1').height());
        var index_j = index_i + num_entries;
        var i = this.get_position(index_i);
        var j = this.get_position(index_j);
        jQuery("#" + AXIS.escapeCSS(this.lens_id)).css({
            height: (j - i + 1) * this.timeline.delta,
            top: this.timeline.H0 + i * this.timeline.delta
        });
    }
};
