/*
 Copyright 2005 Google Inc.  All Rights Reserved.
 Description: Library for generic javascript functions
 Author: Pablo Bellver

*/

/** namespace */
// TODO (jc): move all functions in this file to this namespace, rename file
// as well.
function AW_Utils() {}

var debugEnabled = false;
var debugWindow;

function debug(message) {
  if (!debugEnabled)
    return;

  if (!debugWindow || debugWindow.closed) {
    debugWindow = window.open('', 'debugWindow', 'width=400,height=600');
    debugWindow.document.bgColor = "#eeeeee";
  }
  debugWindow.opener.focus();
  debugWindow.document.body.innerHTML += '> ' + message + '<br/>';
  debugWindow.scroll(0, 5000000);
}

/**
 * Returns true if the web browser is Safari.
 */
function isSafari() {
  return navigator.userAgent.indexOf("Safari") > -1;
}

/**
* Function to go back to the previous displayed page
*/
function goBack() {
 history.go(-1);
 return false;
}

/**
* Function to check all the check boxes in a form
* sampleCheckBox: sample check box from which the checked values are read
* name: name of the check boxes that match within this form
*/
function toggleBoxes(sampleCheckBox,name) {
  var f = sampleCheckBox.form;
  for (var i=0; i < f.elements.length; i++) {
    var box = f.elements[i];
    if (box.name == name) {
      box.checked = sampleCheckBox.checked;
    }
  }
}

/**
 * Adds an event handler to an event source without clobbering the existing
 * handler(s). NB: if multiple event handlers are attached to a source, the
 * order in which they will fire is undefined.
 *
 * TODO(rjrjr) Need a removeEvent method
 *
 * @param eventSrc A reference to the object to which the event handler
          should be attached
 * @param event A STRING representation of the event (e.g. "onclick")
 * @param handler A reference to the handler function
 */
AW_Utils.addEvent = function(eventSrc, eventString, handler) {
  if (eventSrc.addEventListener) {
    debug("AW_Utils.addEvent via addEvent: " + eventSrc + "." + eventString.substr(2));
    eventSrc.addEventListener(eventString.substr(2), handler, false);
    return;
  }

  if (eventSrc.attachEvent) {
    debug("AW_Utils.addEvent via attachEvent: " + eventSrc + "." + eventString);
    eventSrc.attachEvent(eventString, handler);
    return;
  }

  debug("AW_Utils.addEvent fall through: " + eventSrc + "." + eventString);
  if (typeof eventSrc[eventString] != 'function') {
    eventSrc[eventString] = handler;
  } else {
    var old = eventSrc[eventString];
    eventSrc[eventString] = AW_Utils.chainFunctions(old, handler);
  }
}

/**
 * Given two functions, returns a new function that calls each of them
 * sequentially.
 * Note, for adding an event handler, use the AW_Utils.addEvent function
 * (which calls this function internally if necessary)
 */
AW_Utils.chainFunctions = function (firstFunction, secondFunction) {
  return function () {
    firstFunction();
    secondFunction();
  }
}

