/*
 * UIMessage by Michael P. Schmidt 12/18/2007
 * 
	UIMessage.displayMessage(message,Timeout)
	UIMessage.loadingMessage()
	UIMessage.doneLoading()
	UIMessage.errorMessage(error, detail)
	
	
	TODO: I am going to add the ability for a UIMessage to take up the whole screen.
	
	This will provide the system to stop people from doing stuff if processing is occuring
	
	Steps would be to create a background div that takes the full screen
	and to then ahve a div inside of this div place the entire information.
	
	fullScreenMessage(strMessage)
	fullScreenMessageDone(strMessage)
*/
var UIMessages =  Class.create();

UIMessages.loadingMessageTxt = "Please wait loading...";
UIMessages.customMessage= "";
UIMessages.defaultMessageTime= 5000; /* in MS */
UIMessages.messageElm= undefined;
UIMessages.errorMessageText= "Error has occured...";
UIMessages.detailButtonText= "Detail &gt; &gt;";
UIMessages.simpleButtonText= "Simple &lt; &lt;";
UIMessages.dismissButtonText= "Dismiss"; 
UIMessages.loadingUIMessage= undefined;
UIMessages.initialized = false;
UIMessages.overlayElement = undefined;
UIMessages.debug = false;
UIMessages.handleError = false;
UIMessages.initialize = function()
{
	var elms = $$(".UIMessage");
	if ( elms.length > 0)
		this.messageElm = elms[0];
	this.debug = this.detectDebug();
	
	if (this.handleError) {
		Ajax.Responders.register({
			onComplete: this.onComplete.bindAsEventListener(this)
		}, {
			onException: this.ajxFailure.bindAsEventListener(this)
		});
		//Event.observe(window, "error",this.jsError.bindAsEventListener(this) );
		window.onerror = function(message, uri, line){
			var fullMessage = message + "<br> at " + uri + ": " + line
			UIMessages.errorMessage("", fullMessage);
			return true;
		}
	}
}
UIMessages.handleException = function(exception)
{
	 /* In FF exception can be a string if it happens
     when opening the xmlHttpRequest.  Gah! */
  if (typeof exception == 'string')
    exception = new Error(exception)
  
  /* If a xmlhttp request is happening in Mozilla and
     the user navigates to another page, then when
     the first request returns a NS_ERROR_NOT_AVAILABLE
     error will be thrown.  So just ignore it. */ 
  if (exception.name == 'NS_ERROR_NOT_AVAILABLE') return
      
  var fullMessage = ''
  var uri = ''
  var stack = ''
  var line = ''
      
  try
  {                    
    /* Don't use exception.toString since the JS spec
       does not require it to provide the error name or message
       (haven't tested to see if it matters though across browsers) */
    fullMessage = exception.name + ': ' + exception.message
    
    uri = exception.fileName
    stack = exception.stack
    
    // Firefox sometimes blows up here
    line = exception.lineNumber
  }
  catch (e)
  {
  }                  

  fullMessage += "\n at " + uri + ": " + line
  tmpMessage = (fullMessage + "\n\n\nStack Trace\n\n" + stack);
  tmpMessage = tmpMessage.replace(/\n/g, "<br>");
  this.errorMessage("", tmpMessage);   
}

UIMessages.detectDebug = function()
{
	if ( window.COOKIES )
		if ( window.COOKIES.Get("DEBUGON") == "1" )
			return true;
		else 
			return false;
			
	return false;
}

UIMessages.setDebug = function(bValue)
{
	this.debug = bValue;
	if ( window.COOKIES )
		if ( bValue)
			window.COOKIES.Set("DEBUGON", "1");
		else
			window.COOKIES.Set("DEBUGON", "0");
}

UIMessages.causeError = function()
{
	try {
	i.d.f = 1;
	i = 5/ 0;
	test = i / 0;
	document.frankenstein.method();
	} catch (e) {
		this.handleException(e);
		
	}
}
UIMessages.jsError = function(obj)
{
	this.errorMessage("", obj);
}

UIMessages.onComplete = function(obj)
{
	if (obj.transport.status == 500)
	{
	this.ajxFailure(obj.transport);
	}
	

}
		
UIMessages.ajxFailure = function(obj)
{
	var resp = obj.responseText;	
	//resp = eval("("+resp + ")");
	
	//errTxt = "Error has occured please refresh the browser and try again.\n";
	/*if ( resp)
	{
		errTxt += resp["message"] + "\n";
		
		errTxt += resp["detail"] + "\n";
		errTxt += resp["sql"] + "\n";
		errTxt += resp["where"] + "\n";
	}
	customLoadingMessage(errTxt);*/
	this.errorMessage("", resp);
	
}


UIMessages.displayMessage = function(sMessage, iTimeout)
	{		
			if ( iTimeout == undefined)
			{
				iTimeout = this.defaultMessageTime;
			}
			new UIMessages(sMessage, {timeout:iTimeout});
	};
	
UIMessages.displayDebug = function(sMessage)
{
	if ( this.debug)
	{
		this.displayMessage(sMessage);
	}
}
UIMessages.loadingMessage= function()
	{
		
		if ( ! this.messageElm )
		{
			return;
		}
		if ( this.loadingUIMessage == undefined)
		{
			this.loadingUIMessage = new UIMessages(this.loadingMessageTxt);
		} else {
			this.loadingMessage.destroy();
		this.loadingUIMessage = new UIMessages(this.loadingMessageTxt);
	}
	};
UIMessages.doneLoading = function()
{
	if (this.loadingUIMessage != undefined) {
		this.loadingUIMessage.destroy();
		this.loadingUIMessage = undefined;
	}
}

UIMessages.errorMessage= function(sMessage,sDetail)
	{
		if ( sMessage == "" || sMessage == undefined)
		{
			sMessage = this.errorMessageText;
		}
		if (this.overlayElement)
			Element.hide(this.overlayElement);
		new UIMessages(sMessage, {type:"errorMessage",detail:sDetail});
	};
UIMessages.prototype = {
		elm: undefined,
		timeout: undefined,
		type: "notification",
		detail: "",
		detailBtn : undefined,
		detailElm : undefined,
		fullScreen: false,
		onDestroy: undefined,
		initialize: function(msg, options)
		{
			if (options) {
				for (var idx in options) {
					this[idx] = options[idx];
					
				}
			}
			this.elm = document.createElement("div");
			this.elm.innerHTML = msg;
			if (this.fullScreen) {
				this.displayFullScreen();
				this.elm = UIMessages.overlayElement.appendChild(this.elm);
				this.elm.style.backgroundColor = "white";
				this.elm.style.color = "black";
				this.elm.style.left = "200";
				this.elm.style.width="400px";
				this.elm.style.height="300px";
				this.elm.style.top = "200px";
				this.elm.style.position="relative";
				this.elm.style.textAlign = "center";
				this.elm.style.verticalAlign = "middle";
			}else {
				this.elm = UIMessages.messageElm.appendChild(this.elm);
			}
			if (this.type == "errorMessage") {
				this.elm.innerHTML += "<br />";
				var tmpBtn = document.createElement("button");
				tmpBtn.innerHTML = UIMessages.detailButtonText;
				this.detailBtn = this.elm.appendChild(tmpBtn);
				Event.observe(this.detailBtn, "click", this.toggleDetail.bindAsEventListener(this));
				tmpBtn = document.createElement("button");
				tmpBtn.innerHTML = UIMessages.dismissButtonText;
				tmpBtn = this.elm.appendChild(tmpBtn);
				Event.observe(tmpBtn, "click", this.destroy.bindAsEventListener(this));
				var tmpDetail = document.createElement("div");
				tmpDetail.innerHTML = this.detail;
				this.detailElm = this.elm.appendChild(tmpDetail);
				Element.hide(this.detailElm);			
			} 
			if ( this.timeout != undefined )
				window.setTimeout(this.destroy.bindAsEventListener(this), this.timeout);
		},
		displayFullScreen: function()
		{
			if (UIMessages.overlayElement == undefined) {
				var bod = document.getElementsByTagName('body')[0];
				
				var overlay = document.createElement('div');
				UIMessages.overlayElement = bod.appendChild(overlay);
				$(UIMessages.overlayElement).addClassName("transparentOverlay")
			
		
			} else {
				
			} 
			Element.show(UIMessages.overlayElement);
		},
		destroy: function()
		{
			if ( this.fullScreen )
				Element.hide(UIMessages.overlayElement);
			this.elm.parentNode.removeChild(this.elm);
			if ( this.onDestroy != undefined)
				this.onDestroy(this.elm);
	
		},
		toggleDetail: function()
		{
			if ( Element.visible(this.detailElm))
			{
				Element.hide(this.detailElm);
				this.detailBtn.innerHTML = UIMessages.detailButtonText;				
			} else {
				
				Element.show(this.detailElm);
				this.detailBtn.innerHTML = UIMessages.simpleButtonText;
				
			}
		},
		update: function(msg)
		{
			this.elm.innerHTML = msg;			
		}
	};



Event.observe(window, "load", UIMessages.initialize.bindAsEventListener(UIMessages));
