// version 1.0 at http://www.flester.com/
// Published under the GNU General Public License v2.
// You have specific rights under this license, read
// about them at http://www.fsf.org/licensing/licenses/gpl.html
// Author: Mike Flester, http://www.flester.com/, (c) 2005

// Look through the document and add our
// shift-click handler to all checkboxes found.
function shiftclick_init() {
  if (!document.getElementsByTagName) return;

  var boxen = document.getElementsByTagName("input");
  if (!boxen || boxen.length <= 1) return;

  for (var i=0; i<boxen.length; i++) {
    boxen[i].onclick=boxClick;
  }
}

function boxClick(ev) {
  boxClickHandler(this,ev);
}

// Called when a box is clicked. If it is a shift
// click this handler processes other checkboxes
// of the same name as the clicked one that should
// be changed to the same status as the clicked one.
function boxClickHandler(el,ev) {

  ev = ev || window.event || {};
  if (!ev || ev.shiftKey != true || !el) {
    return; // normal click or other problem
  }

  var nval = el.checked;
  var boxen = document.getElementsByName(el.name);
  if (!boxen || boxen.length <= 1) return;

  var lastChecked = -1;
  var lastUnchecked = -1;
  var thisIdx = -1;

  for (var i=0; i<boxen.length; i++ ) {
    if (boxen[i] == el) {
      thisIdx = i;
      break;
    }

    if (boxen[i].checked) {
      lastChecked = i;
    } else {
      lastUnchecked = i;
    }

  }

  var last = nval ? lastChecked : lastUnchecked;
  if (last > -1) {
    for (var j=last; j<thisIdx; j++) {
      boxen[j].checked = nval;
    }
  }
}


// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
function addEvent(elm, evType, fn, useCapture)
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

addEvent(window, "load", shiftclick_init);

