"use strict";

var $ = require('jquery')
  , Backbone = require('../backbone')
  , d3 = require('d3')
  , ItemCollections = require('../collections/collection')

require('jquery-bootstrap');

// whatever
global.d3 = d3;
require('d3-timeline');

module.exports = Backbone.View.extend({
  initialize: function () {
    this.collections = new ItemCollections([]);
    this.render();
  },
  render: function () {
    this.$el.html('');

    var chart
      , svg = d3.select('#' + this.$el.attr('id')).append('svg').attr('width', 1000)
      , data = this.getData()
      , beg = new Date(0)
      , end = new Date(0)

    beg.setFullYear(1916);
    end.setFullYear(1918);

    chart = d3.timeline()
      .width(1000)
      .orient('top')
      .beginning(beg.getTime())
      .ending(end.getTime())
      .tickFormat({
        format: d3.time.format('%b %Y'),
        tickTime: d3.time.months,
        tickInterval: 4,
        tickSize: 4
      })
      .margin({
        left: 150,
        right: 30,
        top: 30,
        bottom: 30
      })
      .display('circle')
      .stack()
      .itemMargin(30);
    svg.datum(data).call(chart);

    this.$('circle[id^="timelineItem"]').tooltip({
      title: function () {
        return this.__data__.label;
      },
      container: 'body'
    });
  },
  getData: function () {
    return this.collections.map(function (collection) {
      return {
        label: collection.get('name'),
        times: collection.items.toD3Data()
      }
    });
  },
  addCollection: function (collection) {
    var that = this;
    collection.fetchItems().then(function () {
      that.collections.add(collection);
      that.render();
    });
  },
  removeCollection: function (collection) {
    this.collections.remove(collection);
    this.render();
  }
});

@@ -12,17 +12,17 @@
 %22;%0A%0Avar 
-$
+_
  = requi
@@ -25,22 +25,26 @@
 equire('
-jquery
+underscore
 ')%0A  , B
@@ -563,112 +563,517 @@
 a()%0A
-      , beg = new Date(0)%0A      , end = new Date(0)%0A%0A    beg.setFullYear(1916);%0A    end.setFullYear(1918
+%0A    var times = _.chain(data).pluck('times').flatten().value()%0A      , beg = _.chain(times).pluck('starting_time').min().value()%0A      , end = _.chain(times).pluck('endingTime').max().value()%0A%0A    beg = new Date(beg);%0A    if (beg.getMonth %3C 2) %7B%0A      beg.setFullYear(beg.getFullYear() - 1);%0A      beg.setMonth(5);%0A      beg.setDate(0);%0A    %7D else %7B%0A      beg.setMonth(0);%0A      beg.setDate(0);%0A    %7D%0A    end = new Date(end);%0A    end.setFullYear(end.getFullYear() + 1);%0A    end.setMonth(5);%0A    end.setDate(0
 );%0A%0A
@@ -1316,17 +1316,17 @@
 terval: 
-4
+3
 ,%0A      

Make timeline endpoints responsive to data