function findItems(button) {
  var mainDiv = $(button).parent();
  while ( !mainDiv.hasClass('massInput') ) {
    mainDiv = $(mainDiv).parent();
  }
  return $('.massInputItem', mainDiv);
}
function addItem(button) {
  var items = findItems(button);
  var item = $(items[items.length-1]);
  var newItem = item.clone(true);
  var i;

  // We have to change the raw html because IE doesn't allow the
  // name field to be changed.
  newItem.html(newItem.html().replace(/fval\[(\d+\.)*(\d+)\.(\d+)\]/g, 
    function(a, b, c, d) {
      var newC = parseInt(c)+1;
      return a.replace(/\d+\.\d+\]/, newC+'.'+d+']');
    }
  ));
  newItem.appendTo(item.parent());

  // Copy the values of all children that had the name attribute set.
  // The direct html insertion does not preserve the most current
  // values.  It only preserves default values, so if we want values
  // copied, we have to use an approach like this.
  var items2 = findItems(button);
  var newLast = $(items2[items2.length-1]);
  var c1 = $('[name]', item);
  var c2 = $('[name]', newLast);
  if ( c1.length == c2.length ) {
    for ( i = 0; i < c1.length; i++ ) {
      $(c2[i]).val($(c1[i]).val());
    }
  }
}
function removeItem(button) {
  var items = findItems(button);
  if ( items.length > 1 ) {
    var item = $(items[items.length-1]);
    item.remove();
  } else {
    alert('Cannot remove any more rows');
  }
}
function facebook_onlogin() {
  $(document).reload(); 
}
function setDates() {
  var today = new Date();
  $('.date_trio_day').val(today.getDate()-1);
  $('.date_trio_month').val(today.getMonth());
  $('.date_trio_year').val(today.getFullYear());
}
function pubFeed(fullbody) {
  var attachment = {"name":"Noscrolls workout", "description":fullbody, "href":"http://www.facebook.com/apps/application.php?id=84057637134"};
  FB.Connect.streamPublish('', attachment, null, null, 'Message to go with workout');
}
$(document).ready(function(){
    setDates();
});

function formatTimeTick(val) {
  var m = val / 60;
  var s = val % 60;
  if ( s < 10 ) {
    s = '0'+s;
  }
  return m.toFixed(0)+":"+s;
}

function formatWeightTick(val) {
  return val+' lbs';
}

var timeAxis = {
  tickFormatter: formatTimeTick,
  autoscaleMargin: 0.05,
  minTickSize: 60
}

var weightAxis = {
  tickFormatter: formatWeightTick,
  minTickSize: 5
}

function maleSeries(values) {
  this.color = "blue";
  this.label = "Males";
  this.data = values;
}

function femaleSeries(values) {
  this.color = "pink";
  this.label = "Females";
  this.data = values;
}

function buildPlot(id, data) {
  $.plot($('#'+id),
         data,
         { lines: { show: false },
           points: { show: true },
           legend: { show: true },
           xaxis: timeAxis,
           yaxis: weightAxis,
           grid: { hoverable: false,
                   clickable: false,
                   autoHighlight: false }
         }
        );
}

