/**
 * @author Rob
 */

/**
 * An informational popup box that disappears when it or another element is clicked.
 * 
 * @param {String} contentElemId
 * @param {String} positionElemId
 * @param {Array} noHideOnClickElemIds  IDs of elements that should not cause the popup to disappear when clicked
 */
var PopupBox = function(contentElemId, positionElemId, noHideOnClickElemIds)
{
  this.contentElem = $(contentElemId);
  this.positionElem = $(positionElemId);
  this.noHideOnClickElemIds = noHideOnClickElemIds;
  
  this.autoHideSeconds = 0;
  
  this.width = '250px';
  this.height = '200px';
  
  this.documentClickedListener = this.documentClicked.bindAsEventListener(this);
}

/**
 * Show the popup box.
 */
PopupBox.prototype.show = function()
{
  var el = this.contentElem;

  if (!el.hasClassName('popupbox'))
    el.addClassName('popupbox');

  var p = this.positionElem.positionedOffset();
  el.style.left = (p[0] + this.positionElem.getWidth()) + 'px';
  el.style.top = p[1] + 'px';
  
  el.style.width = this.width;
  el.style.height = this.height;

  el.show();

  // observe clicks on all elements in order to hide the box
  document.observe('click', this.documentClickedListener);

  // automatically hide after a set time
  if (this.autoHideSeconds)
    this.hideTimer = this.hide.bind(this).delay(this.autoHideSeconds);
}
 
/**
 * Hide popup
 */  
PopupBox.prototype.hide = function()
{
  if (this.hideTimer)
    window.clearTimeout(this.hideTimer);
  
  this.contentElem.hide();
  
  document.stopObserving('click', this.documentClickedListener);
}

/**
 * Returns true if the box is visible.
 */
PopupBox.prototype.visible = function()
{
  return this.contentElem.visible();
}

/**
 * Returns true if the visible and showing the specified content element.
 * 
 * @param {int} id
 */
PopupBox.prototype.isShowing = function(id)
{
  return this.visible() && this.contentElem.id == id; 
}

/**
 * Document clicked event handler.
 * @param {Object} event
 */
PopupBox.prototype.documentClicked = function(event)
{
  // hide the popup box unless the clicked element is one of the 
  // ones specified that we do not want to cause it to be hidden 
  // (or a descendant)
  for(var i=0; i < this.noHideOnClickElemIds.length; ++i)
  {
    var noHideElemId = this.noHideOnClickElemIds[i];
    var t = event.target;
    if (t.id == noHideElemId || Element.descendantOf(t, noHideElemId))
      return;
  }
  
  this.hide();
}


  
