/*
 * This javascript is part of the BatchHelper.
 */

/**
 * Appends all selected values as an array in a hidden element.
 *
 * @param string id Form id
 */
function batch_append_selected_values(id)
{
  for (g = 0; g < batch_checkboxes[id]['GROUPS'].length; g++)
  {
    group = batch_checkboxes[id]['GROUPS'][g];

    if (group == 'ALL') continue;

    for (i = 0; i < batch_checkboxes[id][group].length; i++)
    {
      if (document.getElementById(batch_checkboxes[id][group][i]).checked == true &&
        document.getElementById(batch_checkboxes[id][group][i]).name != 'checkall')
      {
        newInput = document.createElement('input');
        newInput.setAttribute('type', 'hidden');
        newInput.setAttribute('name', group+'[]');
        newInput.setAttribute('value', document.getElementById(batch_checkboxes[id][group][i]).value);
        document.getElementById(id).appendChild(newInput);
      }
    }
  }
}

/**
 * Appends selected checkbox values and a batch action and submits the form.
 *
 * @param string id Form id
 * @param string action Batch action
 */
function batch_submit(id, action, confirm_message)
{
  if (confirm_message != null)
  {
    if (!confirm(confirm_message))
    {
      return;
    }
  }

  batch_append_selected_values(id);

  newInput = document.createElement('input');
  newInput.setAttribute('type', 'hidden');
  newInput.setAttribute('name', 'batch_action');
  newInput.setAttribute('value', action);
  document.getElementById(id).appendChild(newInput);

  document.getElementById(id).submit();
}

/**
 * Checks or unchecks all batch checkboxes of a given form. 
 *
 * @param string id Form id
 */
function batch_check_all(id)
{
  num_boxes = num_checked = 0;

  for (g = 0; g < batch_checkboxes[id]['GROUPS'].length; g++)
  {
    group = batch_checkboxes[id]['GROUPS'][g];

    for (i = 0; i < batch_checkboxes[id][group].length; i++)
    {
      // ignore checkall checkboxes
      if (document.getElementById(batch_checkboxes[id][group][i]).name == 'checkall')
      {
        continue;
      }

      num_boxes++;

      // cound checked boxes
      if (document.getElementById(batch_checkboxes[id][group][i]).checked == true)
      {
        num_checked++;
      }
    }
  }

  //alert(num_checked+' / '+num_boxes);

  // "naturally" check/uncheck based on the number of checked boxes
  check = (num_checked < num_boxes / 2);

  for (g = 0; g < batch_checkboxes[id]['GROUPS'].length; g++)
  {
    group = batch_checkboxes[id]['GROUPS'][g];

    for (i = 0; i < batch_checkboxes[id][group].length; i++)
    {
      document.getElementById(batch_checkboxes[id][group][i]).checked = check;
    }
  }
}