/* Copyright:	 Ing. R.J. van Dongen, 2007
 *
 * Any details for this script can be found at
 * http://www.dsone.nl/projects/scripts/js/MessageBox
 *
 * This script is licensed under the LGPL licensing method, to be found 
 * at http://www.gnu.org/licenses/lgpl.html
 *
 */

Object.getAbsolutePos = function(el) {
	var SL=0, ST=0;
	var is_div = /$div^/i.test(el.tagName);
	if (is_div && el.scrollLeft)
	{
		SL = el.scrollLeft;
	}
	if (is_div && el.scrollTop)
	{
		ST = el.scrollTop;
	}
	var pos = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent)
	{
		var tmp = this.getAbsolutePos(el.offsetParent);
		pos.x += tmp.x;
		pos.y += tmp.y;
	}
	return pos;
}

Object.getElementDimensions = function(el) {
  var dim = { x: 0, y: 0 };
  if (el.style.pixelWidth) {
    dim.x += el.style.pixelWidth;
    dim.y += el.style.pixelHeight;
  } else {
    dim.x += el.offsetWidth;
    dim.y += el.offsetHeight;
  }
  return dim;
}

Object.removeClass = function(el, className) {
	if (!(el && el.className))
	{
		return;
	}
	var cls = el.className.split(" ");
	var c = new Array();
	for (var i=0; i<cls.length; i++)
	{
		if (cls[i] != className)
		{
			c[c.length] = cls[i];
		}
	}
	el.className = c.join(" ");
}

Object.addClass = function(el, className) {
	this.removeClass(el, className);
	el.className += " " + className;
}

Object.stopEvent = function(ev) {
	ev || (ev=window.event);
	//IE?
	if (window.event)
	{
		ev.cancelBubble = true;
		ev.returnValue = false;
	}
	//Other
	else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
}

Object.addEvent = function(el, event, func) {
	//IE: attachEvent
	if (el.attachEvent)
	{
		el.attachEvent("on"+event, func);
	}
	//W3C: addEventListener
	else if (el.addEventListener)
	{
		el.addEventListener(event, func, true);
	}
	//other: "on"+~
	else {
		el["on"+event] = func;
	}
}

Object.removeEvent = function(el, event, func) {
	//IE: detachEvent
	if (el.detachEvent)
	{
		el.detachEvent("on"+event, func);
	}
	//W3C: removeEventListener
	else if (el.removeEventListener)
	{
		el.removeEventListener(event, func, true);
	}
	//other: "on"+~
	else {
		el["on"+event] = null;
	}
}

Object.createElement = function(type, _parent) {
	var el = null;
	if (document.createElementNS)
	{
		el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
	}
	else {
		el = document.createElement(type);
	}
	if (typeof _parent != 'undefined')
	{
		_parent.appendChild(el);
	}
	return el;
}

Object.removeElement = function(el, _parent) {
	try {
		if (typeof _parent != 'undefined')
		{
			if (_parent.hasChildren ) {
				_parent.removeChild(el);
				
			}
		}
	} catch (e) { alert(e); }
}

/** MODAL RESULTS [mapped from C#] **/
/** Obligatory Object Reference **/
ModalResult = function() {}
ModalResult.None = 0;
ModalResult.OK = 1;
ModalResult.Cancel = 2;
ModalResult.Abort = 3;
ModalResult.Retry = 4;
ModalResult.Ignore = 5;
ModalResult.Yes = 6;
ModalResult.No = 7;

/** MESSAGE BOX BUTTONS [mapped from C#] **/
/** Obligatory Object Reference **/
MessageBoxButtons = function() {}
MessageBoxButtons.OK = 0;
MessageBoxButtons.OKCancel = 1;
MessageBoxButtons.AbortRetryIgnore = 2;
MessageBoxButtons.YesNoCancel = 3;
MessageBoxButtons.YesNo = 4;
MessageBoxButtons.RetryCancel = 5;

/** (bitwise) Message Box Event Modes **/
/** Obligatory Object Reference **/
MessageBoxEvents = function() {}
MessageBoxEvents.None = 0;
MessageBoxEvents.Focus = 1;
MessageBoxEvents.Blur = 2;
MessageBoxEvents.MouseOver = 4;
MessageBoxEvents.MouseOut = 8;
MessageBoxEvents.Click = 16;
MessageBoxEvents.All = 31;
MessageBoxEvents.Default = 7;			//focus, blur, mouseover

/** Message Box Icons **/
MessageBoxIcon = function() {}
MessageBoxIcon.Asterisk = 64;
MessageBoxIcon.Error = 16;
MessageBoxIcon.Exclamation = 48;
MessageBoxIcon.Hand = 16;
MessageBoxIcon.Information = 64;
MessageBoxIcon.None = 0;
MessageBoxIcon.Question = 32;
MessageBoxIcon.Stop = 16;
MessageBoxIcon.Warning = 48;

/** Button States **/
ButtonState = function() {}
ButtonState.Normal = 0;		//The button has its normal appearance (three-dimensional).
ButtonState.Inactive = 256;	//The button is inactive (grayed).
ButtonState.Pushed = 512;	//The button appears pressed.
ButtonState.Checked = 1024;	//The button has a checked or latched appearance. Use this appearance to show that a toggle button has been pressed.
ButtonState.Flat = 16384;	//The button has a flat, two-dimensional appearance.
ButtonState.All	= 18176;	//All flags except Normal are set.

/** Caption Buttons **/
CaptionButton = function() {}
CaptionButton.Close = 0;		//A close button
CaptionButton.Minimize = 1;		//A minimize button
CaptionButton.Maximize = 2;		//A maximize button
CaptionButton.Restore = 3;		//A restore button
CaptionButton.Help = 4;			//A help button

/** MessageBox object constructor */
MessageBox = function () {
	this.DialogResult = ModalResult.None;
	this.DialogButtons = null;
	this.EventMode = MessageBoxEvents.All;
	this.icon = MessageBoxIcon.Information;

	this.canClose = true;		//renders a closing cross at right top
	this.caption = null;		//if null, output type
	this.forceCaption = true;	//if null, output type

	this.message = "";
	this.className = "";
	this.cache = false;

	//internal
	this.element = null;				//main DOM element for identifying the MessageBox object
	this._ibox = null;					//main information container [div]
	this.table = null;					//main caption container [table]
	this._mbicon = null;				//main icon [img]
	this._mbcaption = null;				//main caption container [div]
	this._mbcaptionbuttons = null;		//caption button(s) layer [div]

	this._msgRegister = {};				//the message registry
	this.debugMessageRegistry = true;	//shows a MessageBox instance displaying the message registry debug information
	this._regDebug = null;				//registry denug string
	this.hidden = true;
	this.timed = false;
	this.canDrag = true;
	this.dragging = false;
	this.xOffs=0;
	this.yOffs=0;
}

/** 
 * DEFAULT LANGUAGE SETTINGS.
 * For any customized language, create a file MessageBox-<lang>.js, 
 * defining the MessageBox._CLANG attribute. (Yes, _CLANG... NOT _DLANG)
 * This file should then be included in the HTML header to override the default setting below.
 */
MessageBox._DLANG = {};
MessageBox._DLANG["language"] = "en";
MessageBox._DLANG["caption_INFORMATION"] = 'Information';
MessageBox._DLANG["caption_ERROR"] = 'Error';
MessageBox._DLANG["caption_WARNING"] = 'Warning';
MessageBox._DLANG["caption_QUESTION"] = 'Acknowledge';
MessageBox._DLANG["caption_NONE"] = '';

MessageBox._DLANG["caption_OK"] = 'OK';
MessageBox._DLANG["caption_CANCEL"] = 'Cancel';
MessageBox._DLANG["caption_ABORT"] = 'Abort';
MessageBox._DLANG["caption_RETRY"] = 'Retry';
MessageBox._DLANG["caption_IGNORE"] = 'Ignore';
MessageBox._DLANG["caption_YES"] = 'Yes';
MessageBox._DLANG["caption_NO"] = 'No';

MessageBox._DLANG["caption_CLOSE"] = 'Close';
MessageBox._DLANG["caption_MINIMIZE"] = 'Minimize';
MessageBox._DLANG["caption_MAXIMIZE"] = 'Maximize';
MessageBox._DLANG["caption_RESTORE"] = 'Restore';
MessageBox._DLANG["caption_HELP"] = 'Help';

/** 
 * DEFAULT ICON SETTINGS.
 * To override these default settings, override them in the language file.
 */
MessageBox._ICONS = {};
//MessageBox._ICONS[MessageBoxIcon.Asterisk] = 'mb-information.gif';		//64
MessageBox._ICONS[MessageBoxIcon.Information] = 'mb-information.gif';		//64
//MessageBox._ICONS[MessageBoxIcon.Exclamation] = 'mb-warning.gif';	//48
MessageBox._ICONS[MessageBoxIcon.Warning] = 'mb-warning.gif';			//48
MessageBox._ICONS[MessageBoxIcon.Question] = 'mb-questionmark.gif';		//32
MessageBox._ICONS[MessageBoxIcon.Error] = 'mb-error.gif';	//16
//MessageBox._ICONS[MessageBoxIcon.Hand] = 'mb-error.gif';	//16
//MessageBox._ICONS[MessageBoxIcon.Stop ] = 'mb-error.gif';	//16
MessageBox._ICONS[MessageBoxIcon.None] = '';	//0

/** internal static variable to store the current active object in [used for event handling] **/
MessageBox._C = null;
MessageBox._DEBUG = true;
/// detect a special case of "web browser"
MessageBox.isIE = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );
MessageBox.isIE5 = ( MessageBox.isIE && /msie 5\.0/i.test(navigator.userAgent) );
/// detect Opera browser
MessageBox.isOpera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
MessageBox.isKHTML = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);


if (typeof MessageBox._CLANG == 'undefined') { MessageBox._CLANG = MessageBox._DLANG; }
/**
 * Creates a new instance of the DOM element, appends it to the document body
 * for usage, then hides the element.
 */
MessageBox.prototype.create = function() {
	_parent = document.getElementsByTagName("body")[0];

	//main DOM object layer
	this.element = Object.createElement('div');
	this.element.style.position = 'absolute';
	this.element.style.display = 'inline';
	this.element.className = "MessageBox";

	//caption layer
	this._caption = Object.createElement('div', this.element);
	this._caption.style.width = "auto";
	this._caption.style.height = "15px";
	this._caption.style.display = "block";
	Object.addClass(this._caption, 'caption');
	//caption table
	var table = Object.createElement('table');
	this.table = table;
		table.border = '0';
		table.cellPadding = '0';
		table.cellSpacing = '0';
	Object.addEvent(this.table, 'mousedown', MessageBox.tableMouseDown);
	var tbody = Object.createElement('tbody', this.table);
	var row = Object.createElement('tr', tbody);
	var cell = null;

	//table cells
	// icon
	cell = Object.createElement('td', row);
	cell.style.width = "16px";
	cell.className = "mb-icon";
	if ((typeof this.icon=='number')) {
		this._mbicon = Object.createElement('img', cell);
        this._mbicon.style.border = '0px none';
        this._mbicon.style.width = 'auto';
        this._mbicon.style.height = 'auto';
        this._mbicon.src = MessageBox._ICONS[this.icon];
	}
	// caption
	cell = Object.createElement('td', row);
	cell.style.width = "100%";
	cell.className = "mb-caption";
	if (!this.caption && this.forceCaption) {
      switch (this.icon) {
          case 0:
              this.caption=MessageBox._CLANG['caption_NONE'];
              break;
          case 16:
              this.caption=MessageBox._CLANG['caption_ERROR'];
              break;
          case 32:
              this.caption=MessageBox._CLANG['caption_QUESTION'];
              break;
          case 48:
              this.caption=MessageBox._CLANG['caption_WARNING'];
              break;
          case 64:
              this.caption=MessageBox._CLANG['caption_INFORMATION'];
              break;
          default :
              this.caption=MessageBox._CLANG['caption_NONE'];
      } 
	}
	this._mbcaption = Object.createElement('span', cell);
	this._mbcaption.style.border = '0px none';
	this._mbcaption.style.width = 'auto';
	this._mbcaption.style.height = 'auto';
	this._mbcaption.innerHTML = this.caption;
	// captionbutton
	cell = Object.createElement('td', row);
	cell.style.width = "16px";
	cell.className = "mb-captionbutton";
    if (this.canClose) {	    
  	    this._mbcaptionbuttons = Object.createElement('div', cell);
        this._mbcaptionbuttons.style.display = 'inline';
        this._mbcaptionbuttons.style.border = '0px none';
        this._mbcaptionbuttons.style.width = 'auto';
        this._mbcaptionbuttons.style.height = 'auto';
        this._mbcaptionbuttons.style.align = 'right';
        var el = Object.createElement('img');
		el.src='close.gif';
		el.title = MessageBox._CLANG["caption_CLOSE"];
		el.alt = MessageBox._CLANG["caption_CLOSE"];
		Object.addEvent(el, 'click', MessageBox._closeTarget);
		cell.appendChild(el);
    }
	this._caption.appendChild(this.table);

	//main content layer
	this._ibox = Object.createElement('div', this.element);
	this._ibox.style.width = "auto";
	this._ibox.style.height = "auto";
	this._ibox.style.display = "block";
	Object.addClass(this._ibox, 'message');

	this._btnbox = Object.createElement('div', this.element);
	this._btnbox.style.width = "auto";
	this._btnbox.style.height = "auto";
	this._btnbox.style.display = "block";
	Object.addClass(this._btnbox, 'footer');

	_parent.appendChild(this.element);
	MessageBox._C = this;
	this.hide();
}

/**
 * Initializes the MessageBox basic attributes
 */
MessageBox.prototype._init = function(message, caption, buttons, icon, events, width) {
  try {
    if (!message) { return; }
    if (this.element==null) { this.create(); }
    if (this.hidden==false) { this.hide(); }
    this.message = message.replace(/\n/g, '<br />');
	this._ibox.innerHTML = this.message;
	if (icon) { this.icon = icon; }
	else { this.icon = MessageBoxIcon.Information; }

    this.caption=caption;
	if (!this.caption && this.forceCaption) {
      switch (this.icon) {
          case 0:
              this.caption=MessageBox._CLANG['caption_NONE'];
              break;
          case 16:
              this.caption=MessageBox._CLANG['caption_ERROR'];
              break;
          case 32:
              this.caption=MessageBox._CLANG['caption_QUESTION'];
              break;
          case 48:
              this.caption=MessageBox._CLANG['caption_WARNING'];
              break;
          case 64:
              this.caption=MessageBox._CLANG['caption_INFORMATION'];
              break;
          default :
              this.caption=MessageBox._CLANG['caption_NONE'];
      } 
	}
	this._mbcaption.innerHTML = this.caption;

	var icon = Object.createElement('img');
    icon.style.border = '0px none';
	icon.style.width = 'auto';
	icon.style.height = 'auto';
	icon.src = MessageBox._ICONS[this.icon];
	this._mbicon.parentNode.replaceChild(icon, this._mbicon);
	this._mbicon = icon;

	if (buttons) { this.DialogButtons = buttons; }
	else { this.DialogButtons = null; }

	if (events) { this.EventMode = events; }
	else { this.EventMode = MessageBoxEvents.All; }

/*
    if (this.canClose && this._mbcaptionbuttons!=null) { 
        var btn = this._mbcaptionbuttons.firstChild;
		if (typeof btn!='indefined') {
            var el = Object.createElement('img');
            el.src='close.gif';
            el.title='close';
            el.alt='close';
            Object.addEvent(el, 'click', MessageBox._closeTarget);
            btn.parentNode.replaceChild(el, btn);
        }
    }
*/
	//todo: buttons, event handlers
	this.resetWidth(width);
    //this.show();
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * Registers an array of messages for elements having an id.
 * Based on the MessageBox.EventMode, events are assigned to the elements.
 */
MessageBox.prototype.registerMessages = function(register) {
  if (!(register instanceof Array)) {
    alert("Register is not an Array");
    return;
  }

  var debug = '';
  //register defaults
  function set_default(reg, param, value) { if (typeof reg[param]=='undefined') { reg[param]=value; } }
  for (i=0;i<register.length;i++) {
    set_default(register[i], 'id', null);
    set_default(register[i], 'text', null);
    set_default(register[i], 'EventMode', this.EventMode);
	if (register[i].id==null || register[i].text==null) {
	    debug += "<b>Registry Error</b>: Register["+i+"] is not in a correct format { id, text[, EventMode] }\n";
	}
	else {
		this._msgRegister[register[i].id] = register[i];	    
	}
  }

  for (var i in this._msgRegister) {
    try {
      debug += this._msgRegister[i].id + ' => ';
      var el = document.getElementById(this._msgRegister[i].id);
      var eMode = this._msgRegister[i].EventMode;

	  if (eMode==MessageBoxEvents.None) {
	    debug += '<b>Warning</b>: No EventMode!';
	  }
	  if (eMode & MessageBoxEvents.Focus) {
	    debug += 'focus, ';
		Object.addEvent(el, 'focus', MessageBox._showTarget);
	  }
	  if (eMode & MessageBoxEvents.Blur) {
	    debug += 'blur, ';
		Object.addEvent(el, 'blur', MessageBox._closeTarget);
	  }
	  if (eMode & MessageBoxEvents.MouseOver) {
	    debug += 'mouseover, ';
		Object.addEvent(el, 'mouseover', MessageBox._showTarget);
	  }
	  if (eMode & MessageBoxEvents.MouseOut) {
	    debug += 'mouseout';
		Object.addEvent(el, 'mouseout', MessageBox._closeTarget);
	  }
	  if (eMode & MessageBoxEvents.Click) {
	    debug += 'click';
		Object.addEvent(el, 'click', MessageBox._showTarget);
	  }
	  debug += "\n";
    } catch (e) { alert(e); }
  }
  //display debugging information?
  if (this.debugMessageRegistry) {
    this._regDebug = debug;
	//MessageBox.ShowDebug();
	//setTimeout('MessageBox.Hide()',1000);
  }

}

/**
 * Resets the width of the main container.
 * This can be used to override the CSS class .MessageBox (a div)
 */
MessageBox.prototype.resetWidth = function(width) {
  try {
    if (typeof width!='undefined') { this.element.style.width = width; }
    else { this.element.style.width = null; }
  } catch (e) { }
}

/**
 * Removes the MessageBox object from the DOM and destroys the instance
 */
MessageBox.prototype.destroy = function() {
  try {
    this.element.parentNode.removeChild(this.element);
    this.element = null;
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * show the MessageBox at a specific position.
 * Warning: the position is set through DOM style, thus meaning that 
 * the position can be absolute or relative to another [container] element.
 */
MessageBox.prototype.showAt = function(x,y) {
	this.element.style.left = x + 'px';
	this.element.style.top = y + 'px';
	this.show();
}

/**
 * show() shows the message box.
 */
MessageBox.prototype.show = function() {
  try {
    if (!this.hidden) this.hide();
    this.element.style.visibility = "visible";
    this.element.style.height = "auto";
    this.element.style.display = "inline";
	this.hidden = false;
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * hide() hides the message box.
 */
MessageBox.prototype.hide = function() {
  try {
    this.element.style.visibility = "hidden";
    this.element.style.height = "0px";
    this.element.style.display = "none";
	this.hidden = true;
	this.timed = false;
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * close() closes the message box;
 */
MessageBox.prototype.close = function() {
  try {
    if (this.cache) { this.hide(); }
    else { this.destroy(); }
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * Moves the MessageBox object by x,y pixels.
 */
MessageBox.prototype.move = function(x,y) {
	var el = this.element;
	if (!el.style.position) { 
		el.style.position = "relative"; 
	}
	var L = parseInt(el.style.left.replace('px', "")) || 0;
	var T = parseInt(el.style.top.replace('px', "")) || 0;
	el.style.left = L+x;
	el.style.top = T+y;
}

/**
 * Changes the z-index of the main MessageBox container element.
 */
MessageBox.prototype.zmove = function(zval) {
	var el = this.element;
	if (el.style && el.style.zIndex) {
		el.style.zIndex += zval;
	}
}

/**
 * returns the current language
 */
MessageBox.GetCurrentLanguage = function() {
  return MessageBox._CLANG.language;
}

/** STATIC CLASS METHODS **/
/**
 * MessageBox.Show( string, string, MessageBoxButtons, MessageBoxIcon, MessageBoxEvents) hides the MessageBox
 */
MessageBox.Show = function(message, caption, buttons, icon, events, width) {
  try {
    if (!MessageBox._C) {
      var box = new MessageBox();
	  box.create();
    }
	else {
      var box = MessageBox._C;
	}
	box._init(message, caption, buttons, icon, events, width);
	box.show();
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/** STATIC CLASS METHODS **/
/**
 * MessageBox.RegisterHelp( string, MessageBoxEvents ) registers the MessageBox _showHelp() event to an element with a given ID
 * for the given event modes.
 * id : element id
 * events: the MessageBoxEvents event mode
 */
MessageBox.RegisterHelp = function(id, events) {
  try {
    if (typeof id=='undefined') return;
	events = events || MessageBoxEvents.Click;

    var el = document.getElementById(id);
    if (events & MessageBoxEvents.Focus) { Object.addEvent(el, 'focus', MessageBox._showHelp); }
    if (events & MessageBoxEvents.Blur) {  Object.addEvent(el, 'blur', MessageBox._closeTarget); }
    if (events & MessageBoxEvents.MouseOver) { Object.addEvent(el, 'mouseover', MessageBox._showHelp); }
    if (events & MessageBoxEvents.MouseOut) { Object.addEvent(el, 'mouseout', MessageBox._closeTarget); }
    if (events & MessageBoxEvents.Click) { Object.addEvent(el, 'click', MessageBox._showHelp); }
	el.title = "Click me to show MessageBox Help";
	el.style.className = "mb-help";
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.ShowHelp( string ) shows the MessageBox Help
 */
MessageBox.ShowHelp = function(type) {
  try {
    var msg = '';
    msg += "<b>help</b>: "+(MessageBox._CLANG['help_NAV'] || MessageBox._DLANG['help_NAV']);
	if (MessageBox._C.debugMessageRegistry) {
	    msg += "<a href=\"#\" onclick=\"MessageBox.ShowDebug('REGISTER',true)\" title=\"Registry Debug\">Debug</a>";
	}
	msg += "\n\n";
    if (typeof MessageBox._CLANG['help_'+type]!='undefined') {
      msg += MessageBox._CLANG['help_'+type];
    }
    else if (typeof MessageBox._DLANG['help_'+type]!='undefined') {
      msg += MessageBox._DLANG['help_'+type];
    }
    MessageBox.ShowAt(200,200,msg, 'MessageBox Help: '+(type || 'Index'), null, MessageBoxIcon.Question, MessageBoxEvents.None, 400);
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.ShowDebug( string, bool ) shows the Debug for the MessageBox.
 * if donav is true, the [help] navigation bar will also be displayed
 */
MessageBox.ShowDebug = function(type, donav) {
  try {
	if (!MessageBox._C) return;
    var msg = '';
    if (typeof donav!='undefined' && donav==true) {
      msg += "<a href=\"#\" onclick=\"MessageBox.ShowHelp()\" title=\"Help\">Help</a>\n";
      //msg += MessageBox._CLANG['help_NAV'] || MessageBox._DLANG['help_NAV'] || '';
    }
	if (MessageBox._C.debugMessageRegistry) {
	    msg += "<b>debug</b>: <a href=\"#\" onclick=\"MessageBox.ShowDebug('REGISTER',true)\" title=\"Registry Debug\">Registry Debug</a>";
	}
	msg += "\n\n";
	switch (type) {
		case 'REGISTER':
		default: 
			msg += 'Message Registry Debugging is '+(MessageBox._C.debugMessageRegistry?"enabled\n\n"+MessageBox._C._regDebug:'disabled by Setup()');
			break;
	}
	var icon = MessageBox._C.debugMessageRegistry?MessageBoxIcon.Information:MessageBoxIcon.Warning;
    MessageBox.ShowAt(200,200,msg, 'MessageBox Debug: '+(type || '#'), null, icon, MessageBoxEvents.None, 400);
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.ShowAt( string, string, MessageBoxButtons, MessageBoxIcon, MessageBoxEvents) hides the MessageBox
 */
MessageBox.ShowAt = function(x, y, message, caption, buttons, icon, events, width) {
  try {
    if (!MessageBox._C) {
      var box = new MessageBox();
	  box.create();
    }
	else {
      var box = MessageBox._C;
	}
	box._init(message, caption, buttons, icon, events, width);
	box.showAt(x,y);
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.Hide() hides the MessageBox
 */
MessageBox.Hide = function() {
  try {
    if (MessageBox._C) {
      MessageBox._C.hide();
	}
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * inner static Hiding function. Do not use directly; use DelayHide instead
 */
MessageBox._DelayHide = function(seconds) {
  try {
    if (typeof seconds!='number') return;
    if (!MessageBox._C.timed) return;
    if (MessageBox._C.element == null) return;
    if (MessageBox._C.hidden) return;
    seconds = Math.abs(seconds);
    if (seconds==0) { MessageBox.Hide(); }
    else { 
      var str = MessageBox._C._ibox.innerHTML.replace(/This message disappears in ./ig, "");
	  var str2 = "This message disappears in "+seconds;
	  MessageBox._C._ibox.innerHTML = str.substr(0,str.length) + str2;
	  setTimeout('MessageBox._DelayHide('+(--seconds)+')', 1000);
	}
  }
  catch (e) {}
}

/**
 * Delays hiding the active MessageBox by n seconds.
 */
MessageBox.DelayHide = function(seconds) {
  try {
    if (typeof seconds!='number') return;
	MessageBox._C.timed = true;
	MessageBox._DelayHide(seconds);
  }
  catch (e) {}
}

/**
 * MessageBox.Close() closes the MessageBox
 * Depending on the MessageBox.cache setting, the inner DOM object is destoryed or retained
 */
MessageBox.Close = function() {
  try {
    if (MessageBox._C) {
      MessageBox._C.close();
	}
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.Register( array ) registers an array of messages.
 * the array is expected to have objects with the folloiwing attributes:
 * id : element id
 * text : message
 * EventMode: event handling modus for the message
 */
MessageBox.Register = function(register) {
  try {
    //create box with defaults if needed
    if (!MessageBox._C) {
      var box = new MessageBox();
      box.create();
    }
    MessageBox._C.registerMessages(register);
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**
 * MessageBox.Setup( array ) is a setup utility function for the MessageBox,
 * creating an instance if needed.
 * 
 */
MessageBox.Setup = function(setup) {
  if (!(typeof setup =='object')) {
    alert("Setup is not in a correct format");
    return;
  }

  function set_default(param, value) { if (typeof setup[param]=='undefined') { setup[param]=value; } }
  set_default('icon', MessageBoxIcon.Information);
  set_default('DialogButtons', null);
  set_default('EventMode', MessageBoxEvents.All);
  set_default('DialogResult', ModalResult.None);
  set_default('canClose', false);
  set_default('caption', null);
  set_default('forceCaption', true);
  set_default('className', '');
  set_default('cache', true);
  set_default('debugMessageRegistry', true);
  set_default('canDrag', true);

  try {
    //create box with defaults if needed
    if (!MessageBox._C) {
      var box = new MessageBox();
      box.create();
    } else {
      var box = MessageBox._C;
    }
    box.debugMessageRegistry = setup.debugMessageRegistry;
    box.icon = setup.icon;
    box.DialogButtons = setup.dialogButtons;
    box.EventMode = setup.EventMode;
    box.DialogResult = setup.DialogResult;
    box.canClose = setup.canClose;
    box.caption = setup.caption;
    box.forceCaption = setup.forceCaption;
    box.className = setup.className;
    box.cache = setup.cache;
    box.canDrag = setup.canDrag;
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/** EVENT HANDLERS **/
/**
 * MessageBox._showTarget( event ) shows the MessageBox based on the configuration for the current specific element
 */
MessageBox._showTarget = function(ev) {
  try {
    if (window.event) { var d = window.event.srcElement; }
    else { var d = ev.currentTarget; }
	if (!d.id) { return; }
    if (MessageBox._C) {
      //prevent when dragging
      if (MessageBox._C.dragging) { return Object.stopEvent(ev); }
      var p = Object.getAbsolutePos(d);
	  var dim = Object.getElementDimensions(d);
      MessageBox.ShowAt(p.x + dim.x + 5, p.y, MessageBox._C._msgRegister[d.id].text);
    }
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}
/**
 * MessageBox._hideTarget( event ) hides the MessageBox
 */
MessageBox._hideTarget = function(ev) {
  try {
    MessageBox.Hide();
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}
/**
 * MessageBox._closeTarget( event ) closes the MessageBox
 * Depending on the MessageBox.cache setting, the inner DOM object is destoryed or retained
 */
MessageBox._closeTarget = function(ev) {
  try {
    MessageBox.Close();
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}
/**
 * MessageBox._showHelp( event ) shows the Help
 */
MessageBox._showHelp = function(ev) {
  try {
    MessageBox.ShowHelp();
  } catch (e) { if (MessageBox._DEBUG) alert(e); }
}

/**************/
MessageBox.onStartDrag = function (ev) {
	var box = MessageBox._C;
	if (!box) {
		return false;
	}
	var posX;
	var posY;
	if (window.event) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posX = ev.pageX;
		posY = ev.pageY;
	}
	var style = box.element.style;
	style.left = (posX - box.xOffs) + "px";
	style.top = (posY - box.yOffs) + "px";
	//window.status = style.left+":"+style.top;
	return Object.stopEvent(ev);
}

MessageBox.stopDrag = function (ev) {
	var box = MessageBox._C;
	if (!box) {
		return false;
	}
	box.dragging = false;
	Object.removeEvent(document, "mousemove", MessageBox.onStartDrag);
	Object.removeEvent(document, "mouseup", MessageBox.stopDrag);
	//do any other events that need to be done here...
	return Object.stopEvent(ev);
}

MessageBox.tableMouseDown = function (ev) {
	var box = MessageBox._C;
	if (!box) {
		return false;
	}
	box._startDrag(ev);
	//do any other events that need to be done here...
	return Object.stopEvent(ev);
}

MessageBox.prototype._startDrag = function (ev) {
	if (this.dragging) {
		return;
	}
	this.dragging = true;
	var posX;
	var posY;
	if (window.event) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posY = ev.clientY + window.scrollY;
		posX = ev.clientX + window.scrollX;
	}

	if (!this.element.style.left) { this.xOffs = posX; }
	else { this.xOffs = posX - parseInt(this.element.style.left); }
	
	if (!this.element.style.left) { this.yOffs = posY; }
	else { this.yOffs = posY - parseInt(this.element.style.top); }
	
	Object.addEvent(document, "mousemove", MessageBox.onStartDrag);
	Object.addEvent(document, "mouseup", MessageBox.stopDrag);
}


