var DIAGRAM_TEACUP_SLOPE = 5 / 3;

// Get total height of a teacup (bottom width is asssumed to be half top width)
function teacupHeight(width) {
  return Math.floor(DIAGRAM_TEACUP_SLOPE * width / 4);
}

function changeTeacupSize(canvas, delta_width) {
  var width = canvas.parent().width() + delta_width;
  canvas.parent().width(width);
  var height = teacupHeight(width);
  canvas.parent().height(height);
  if ($.browser.msie) {drawTeacup(canvas);} // only IE doesn't scale automatically
  var diagram_object_id = canvas.parent().attr("id").replace(/\D/g, '');
  $.post("/diagram_objects/" + diagram_object_id + ".js", { _method: 'put', 'diagram_object[width]': width });
}

function drawTeacup(e) {
  // Fix size inconsistencies between browsers
  e[0].width = e.parent().width();
  e[0].height = e.parent().height();
  // Horrible IE workaround for new teacups and sporadic loading failures
  if (!e[0].getContext) {window.location.href = window.location.href;}
  ctx = e[0].getContext("2d");
  ctx.clearRect(0, 0, e.width(), e.height());
  var width = parseFloat(e.parent().width());
  var percentage = parseFloat(e.siblings('span').text().replace(/[^\d.]/g, '')) / 100;
  var height = teacupHeight(width);
  // Get height of water by solving a quadratic equation
  var a = 1 / DIAGRAM_TEACUP_SLOPE;
  var b = width / 2;
  var c = -3.0 / 16 * DIAGRAM_TEACUP_SLOPE * percentage * width * width;
  var water_height = Math.floor((-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a));
  var empty_height = height - water_height;
  drawTeacupTrapezoid(ctx, 0, 0, width, empty_height, 'fill', 'white');
  drawTeacupTrapezoid(ctx, empty_height, Math.floor(empty_height / DIAGRAM_TEACUP_SLOPE), Math.floor(width - 2 * (empty_height / DIAGRAM_TEACUP_SLOPE)), water_height, 'fill', 'blue');
  drawTeacupTrapezoid(ctx, 0, 0, width, height, 'stroke', 'black');
}

// Start at top left and go clockwise
function drawTeacupTrapezoid(ctx, top, left, width, height, fill_or_stroke, color) {
  ctx.beginPath();
  ctx.moveTo(left, top);
  ctx.lineTo(left + width, top);
  ctx.lineTo(left + width - height / DIAGRAM_TEACUP_SLOPE, top + height);
  ctx.lineTo(left + height / DIAGRAM_TEACUP_SLOPE, top + height);
  if (fill_or_stroke == 'stroke') {
    ctx.closePath();
    ctx.strokeStyle = color;
    ctx.stroke();
  } else {
    ctx.fillStyle = color;
    ctx.fill();
  }
}
