$(function() {
    // Generated by TimeObserver renderData
    var data = window.data.processes;
    var beginningMillis = window.data.beginningMillis;
    var endingMillis = window.data.endingMillis;
    var elapsed = window.data.elapsed;

    var handler=null;

    function getTickFormat() {
      var MIN = 1000 * 60
      var HOUR = MIN * 60
      var DAY = HOUR * 24
      var delta = (endingMillis - beginningMillis)

      if( delta < 2 * MIN ) {
        return {
          format: d3.time.format("%S"),
          tickTime: d3.time.seconds,
          tickInterval: 5,
          tickSize: 6
        }
      }

      if( delta < 2 * HOUR ) {
        return {
          format: d3.time.format("%M"),
          tickTime: d3.time.minutes,
          tickInterval: 5,
          tickSize: 6
        }
      }

      if( delta < 2 * DAY ) {
        return {
          format: d3.time.format("%H:%M"),
          tickTime: d3.time.hours,
          tickInterval: 1,
          tickSize: 6
        }
      }

      if( delta <= 7 * DAY ) {
        return {
          format: d3.time.format("%b %e %H:%M"),
          tickTime: d3.time.hours,
          tickInterval: 6,
          tickSize: 6
        }
      }

      return {
        format: d3.time.format("%b %e"),
        tickTime: d3.time.days,
        tickInterval: 1,
        tickSize: 6
      }
    }

    function getLabelMargin(scale) {
        $('<span class="labelSpan" style="display: none"></span>').appendTo('body');

        var labelMargin = 0
        $.each(data, function (key, value) {
          labelMargin = Math.max(labelMargin, $('.labelSpan').html(value.label).width());
        });

        $('.labelSpan').remove();

        return (labelMargin * scale);
    }

    function render() {
      handler=null;
      $("#timeline").empty()
      $('#label_elapsed').text(elapsed)
      $('#label_launch').text( d3.time.format('%d %b %Y %H:%M')(new Date(beginningMillis)) )

      var width = $(window).width();
      var chart = d3.timeline()
        .stack() // toggles graph stacking
        .margin({left:getLabelMargin(0.85), right:100, top:0, bottom:0})
        .tickFormat( getTickFormat() )
        .rowSeperators('#f5f5f5')
        .showTimeAxisTick()
        ;
      var svg = d3.select("#timeline").append("svg").attr("width", width).datum(data).call(chart);
    }

    function hrz() {
    if( handler != null ) clearTimeout(handler)
      handler = setTimeout(render, 150);
    }

    $(document).ready(render)
    $(window).resize(hrz); // resize the applet on window resize

});