

function commas(num) {
  // Renders the number as an integer with commas every 3rd decimal place
  var str = "";
  while( num > 999 ) {
    newdigits = Math.floor(num%1000) + "";
    while( newdigits.length < 3 ) {
      newdigits = "0" + newdigits;
    }
    str= "," + newdigits + str;
    num= Math.floor(num/1000);
  }
  str = num + str;

  return str;
}

 

var numpts = spilldata.length;
var points = pv.range(numpts).map(function(p) {
  return {
    color: spilldata[p][8],
    x: spilldata[p][2],
    y: spilldata[p][3],
    ymin: spilldata[p][6],
    ymax: spilldata[p][7],
    title: spilldata[p][0],
    where: spilldata[p][4],
    when: spilldata[p][5]
  };
});


/*
var us_productionData = pv.range( us_raw_productiondata.length ).map( function(p) {
  return {
    x: us_raw_productiondata[p][0],
    y: us_raw_productiondata[p][1] * 1e6 * 0.9 * 159 / 1e3 / 24
    // convert million barrels per day to tons per hour
    // 0.9 density of oil (kg/liter)
    // 159 liters in a barrel
    // 1e3 kg in a ton
    // 24 hours per day
  };
};
*/
        
var global_productionData = pv.range( global_raw_productiondata.length ).map( function(p) {
  return {
    x: global_raw_productiondata[p][0],
    y: global_raw_productiondata[p][1] * 1e6 * 0.9 * 159 / 1e3 / 24
    // convert million barrels per day to tons per hour
    // 0.9 density of oil (kg/liter)
    // 159 liters in a barrel
    // 1e3 kg in a ton
    // 24 hours per day
  };
});
        

 

function shared_graph_stuff(vis,x,y,use_log, detail_div) {
        /* Add the x-axis rules */
        vis.add(pv.Rule)
            .data(x.ticks(10))
            .left(x)
            .strokeStyle(function(d) { return d ? d % 5 ? "#eee" : "#ccc" : "#000"; })
          .anchor("bottom").add(pv.Label)
            .visible(function(d) { return !(d & 1); })
            .text( function(n) {return n; }  ) // gotta be an easier way.
            ;


        /* X-axis label. */
        vis.add(pv.Label)
            .data(["Year"])
            .left(w/2)
            .bottom(-30)
            .textAlign("center")
            .font("bold 11px sans-serif");
         

        /* Add the y-axis rules (lines) */
        vis.add(pv.Rule)
            .data(y.ticks())
            .bottom(y)
            .strokeStyle(function(d) {
                // If first digit of string representation is 1, use the darker line
                if( (d+"")[0] == 1 ) 
                  return "#aaa";
                return "#eee";
            })
            .visible(function(d) { return !(d & 1); })
            ;

        var ylabels;
        if( use_log ) {
            ylabels = [1,10,100,1e3,1e4,1e5,1e6];
        } else {
            ylabels = y.ticks();
        }
        /* Add the y-axis scale labels */
        vis.add(pv.Rule)
            .data(ylabels)
            .bottom(y)
            .strokeStyle("#aaa")
            .anchor("right").add(pv.Label)
            .text(commas)
            ;


        /* Y-axis text label. */
        vis.add(pv.Label)
            .data(["Tons of oil spilled"])
            .right(-55)
            .top(h / 2)
            .textAlign("center")
            .textAngle(-Math.PI / 2)
            .font("bold 11px sans-serif");

        /* US production line */
        /*
        var line = vis.add(pv.Line)
                      .data(us_productionData)
                      .left(function(d) { return x(d.x); })
                      .bottom(function(d) { return y(d.y); })
                      .strokeStyle("#ff8833")
                      .lineWidth(3);

        vis.add(pv.Label)
            .data(["US daily production"])
            .left(x(1934))
            .bottom(y(2e5))
            .textAlign("center")
            .font("11px sans-serif");
        */



        /* Add a panel for each data point */
        var blobs = vis.add(pv.Panel)
            .data(points)
            .left(function(d) { return x(d.x); })
            .bottom(function(d) { return y(d.y); });
         
        /* Add y-error indicators */
        blobs.add(pv.Rule)
            .left(0)
            .bottom(function(d) {
                return y(d.ymin)- y(d.y);
            })
            .height(function(d) {
                return y(d.ymax) - y(d.ymin);
            });
         
        blobs.add(pv.Rule)
            .data(function(d) { return [-1, 1]; })
            .bottom(function(s, d) {
                if( s < 0 ) {
                  return y(d.ymin) - y(d.y);
                } else {
                  return y(d.ymax) - y(d.y);
                }
             })
            .left(-k)
            .width(2 * k);
         
        /* Add the data dots 
        and interaction actions. */
        blobs.add(pv.Dot)
            .left(0)
            .bottom(0)
            .radius(k)
            .def("detail", function(d) {
              // Render the detail box 
              var amt; // Pretty rendering of the spill amount
              if( d.ymin == d.ymax ) {
                amt = commas(d.ymin);
              } else {
                amt = "Between " + commas(d.ymin) + " and " + commas(d.ymax);
              }
              return('<b>'+d.title+'</b><br/>'
                + amt + " tons of oil spilled <br/>"
                + d.where + "<br/>" 
                + d.when + "<br/>"
                );
            })
            .def("defcolor", function(d) { return d.color; })
            .strokeStyle(null)
            .fillStyle(function() { return this.defcolor(); } )
            .event("point", function() {
              $(detail_div).html( this.detail() ).css('visibility','visible');
              this.fillStyle("red");
              return this; // necessary to re-render
            })
            .event("unpoint", function() {
              $('#spilldetails').css('visibility','hidden');
              this.fillStyle( this.defcolor() );
              return this; // necessary to re-render
            })
            ;

}

// setup for the log graph
var w = 500,
    h = 400,
    k = 3,
    x = pv.Scale.linear(1900,2013).range(0, w),
    y = pv.Scale.log(1, 3e6).range(0, h);

/* the root panel */
var vis = new pv.Panel()
  .canvas('logfig')
  .width(w)
  .height(h)
  .left(10)
  .right(60)
  .top(10)
  .bottom(30)
  .cursor("hand")
  .events("all")
  .event("mousemove", pv.Behavior.point());
  ;
shared_graph_stuff(vis,x,y,true, '#spilldetails');
vis.render();



// setup for the linear
var w = 500,
    h = 400,
    k = 3,
    x = pv.Scale.linear(1960,2012).range(0, w),
    y = pv.Scale.linear(0, 1e6).range(0, h)
    ;

/* the second panel */
var vis2 = new pv.Panel()
  .canvas('linefig')
  .width(w)
  .height(h)
  .left(10)
  .right(60)
  .top(10)
  .bottom(30)
  .cursor("hand")
  .events("all")
  .event("mousemove", pv.Behavior.point());
  ;
shared_graph_stuff(vis2,x,y,false, '#spilldetails2');

/* Global production line */
var line = vis2.add(pv.Line)
               .data(global_productionData)
               .left(function(d) { return x(d.x); })
               .bottom(function(d) { return y(d.y); })
               .strokeStyle("#eeaa33")
               .lineWidth(3);


vis2.add(pv.Label)
    .data(["Global hourly production"])
    .left(x(1968))
    .bottom(y(3.4e5))
    .textAlign("center")
    .font("11px sans-serif");

vis2.render();
 
