/**
 * @file naaf_jury.js
 * NAAF Jury Javascript
 *
 * @author Matthew Oliveira<matt@tricorpweb.com>
 * @version 6.x.1.0
 * @date October 1, 2009
 */

$(document).ready(function() {
  // Enable the Divide Evenly button
  $('#edit-divide-evenly').show();
  $('#edit-divide-evenly').bind('click', function() {
    
    divide_evenly();
    return false;
  });
});

/**
 * Take the number of submitted applications from the hidden field and 
 * use it to divide them evenly between the jurors.
 */
function divide_evenly() {
  var num_submitted = $('#edit-num-submitted').val();
  var num_jurors = $('#naaf-jury-assign-table input').length;
  var common;
  var left;
  var jurors = new Array(num_jurors);
  
  // Initialize the array
  for(var i = 0; i < num_jurors; i++) {
    jurors[i] = 0;
  }
  
  if (num_submitted < num_jurors) {

    left = num_submitted;
  } else {
    // Assign a common amount to each and then divide up the rest one at a time from
    // the top.
    common = Math.floor(num_submitted / num_jurors);
    for (var i = 0; i < num_jurors; i++) {
      jurors[i] = common;
    }
    left = num_submitted - (common * num_jurors);
  }
  
  // Assign the leftovers one at a time starting from the top
  for (var i = 0; i < left; i++) {
    jurors[i]++;
  }
  
  // Set the values to the textboxes
  $('#naaf-jury-assign-table input').each(function(i) {
  
    $(this).val(jurors[i]);
  });
}