/// <reference path="../Scripts/jquery-1.3.2-vsdoc.js" />

// enumeration functions for messages
function MessageTypes(value)
{
	this._value = value;
}
MessageTypes.prototype.toString = function() { return this._value; };
MessageTypes.Info = new MessageTypes(0);
MessageTypes.Warning = new MessageTypes(1);
MessageTypes.Critical = new MessageTypes(2);
MessageTypes.Confirmation = new MessageTypes(3);
MessageTypes.None = new MessageTypes(4);
MessageTypes.Waiting = new MessageTypes(5);

function MessageButtons(value)
{
	this._value = value;
}
MessageButtons.prototype.toString = function() { return this._value; };
MessageButtons.None = new MessageButtons(0);
MessageButtons.Ok = new MessageButtons(1);
MessageButtons.Cancel = new MessageButtons(2);
MessageButtons.Yes = new MessageButtons(4);
MessageButtons.No = new MessageButtons(8)
MessageButtons.Retry = new MessageButtons(16);
MessageButtons.GoBack = new MessageButtons(32);
MessageButtons.OkCancel = new MessageButtons(3);
MessageButtons.YesNo = new MessageButtons(12)
MessageButtons.RetryCancel = new MessageButtons(18);
MessageButtons.RetryGoBack = new MessageButtons(48);

function MessageReturnTypes(value)
{
	this._value = value;
}
MessageReturnTypes.prototype.toString = function() { return this._value; };
MessageReturnTypes.None = new MessageReturnTypes(0);
MessageReturnTypes.Ok = new MessageReturnTypes(1);
MessageReturnTypes.Cancel = new MessageReturnTypes(2);
MessageReturnTypes.URL = new MessageReturnTypes(3);
 
// display message function
function DisplayMessage(MsgTitle, MsgName, MsgText, MsgType, RetryURL, GoBackURL, Buttons, ScriptCallBack, AddMsg, ModifyConfigParams, HidePage)
{
	// hide any visible message if one exists
    HideMessage();


	// set common display
	ResizeShieldFrame();
		
	// hide all combo boxes
	ToggleComboVisibility(false);
	
	var msgFrame = document.getElementById('MessageFrameValue');
	
	if (typeof(ScriptCallBack) == 'undefined')
		ScriptCallBack = '';
		
	msgFrame.src = BuildMessagePageURL(MsgTitle, MsgName, MsgText, MsgType, RetryURL, GoBackURL, Buttons, ScriptCallBack, AddMsg, ModifyConfigParams, HidePage);
	
	// setup event handlers
	RegisterShieldFrameEventHandlers(true);
	RegisterMessageFrameEventHandlers(true);	
	
	// unregister hide on load for waiting page. this prevents another message that has been displayed
	// after calling ShowWaiting(msgtitle, msgtext, true) from being hidden on page load...
	window.detachEvent('onload', HideMessage);
	
}

function DisplayConfirmation(MsgName, MsgText, ScriptCallBack)
{
    DisplayMessage('', MsgName, MsgText, MessageTypes.Confirmation, '', '', MessageButtons.YesNo, ScriptCallBack);
}

function DisplayInformation(MsgName, MsgText, ScriptCallBack,AddMsg)
{
    DisplayMessage('', MsgName, MsgText, MessageTypes.Info, '', '', MessageButtons.Ok, ScriptCallBack,AddMsg);	
}

function DisplayWarning(MsgName, MsgText, ScriptCallBack)
{
    DisplayMessage('', MsgName, MsgText, MessageTypes.Warning, '', '', MessageButtons.Ok, ScriptCallBack);
}

function DisplayError(MsgName, MsgText, ScriptCallBack, AddMsg)
{
    DisplayMessage('', MsgName, MsgText, MessageTypes.Critical, '', '', MessageButtons.Ok, ScriptCallBack, AddMsg);	
}

function DisplayWaiting(MsgName, MsgText, ScriptCallBack, HideOnLoad, HidePage)
{
    DisplayMessage('', MsgName, MsgText, MessageTypes.Waiting, '', '', MessageButtons.None, ScriptCallBack, null,null, HidePage);
    
    if (HideOnLoad == true)
		window.attachEvent('onload', HideMessage);
}

function DisplaySlidedownMessage(MessageToDisplay) {

    HideSlidedownMessage();
    var message = $("<div id='slidedown_message'>" + MessageToDisplay + "</div>");
    var body = $("body");
    var leftMargin = (body.width() / 2) - 200;
    message.css("margin-left", leftMargin);
    message.appendTo(body);
    message.click(function() { message.slideUp("fast") });
    message.slideDown("slow");
    setTimeout(function() {
        message.slideUp("slow");
    }, 5000);
}

function HideSlidedownMessage() {
    // remove if a message already exists
    var existingMessage = $('#slidedown_message');
    if (existingMessage.length > 0) {
        existingMessage.remove();
    }
}

function ShowShield()
{
	// hide any visible shield if one exists
	HideShield();

	// set properties to display
	ResizeShieldFrame();
	RegisterShieldFrameEventHandlers();
	
	// hide all combo boxes
	ToggleComboVisibility(false);	
}

function HideShield()
{
	HideMessage();
}

var _HideMessageLatched = false; //Provides a latch that prevents us from hiding a message that is displayed during the load

function DisableHide()
{
    _HideMessageLatched = true;
}

function EnableHide()
{
    _HideMessageLatched = false;
}

function HideMessage()
{
    //We are latched, we are displaying a message and we know someone will try to hide it.
    //Typically this is used to disable hide before displaying message then use the script
    //callback to enable the hide once the ok buttong is finished.
    if (_HideMessageLatched)
    {
        return;
    }
	// set properties to display
	var msgFrame = document.getElementById('MessageFrameValue');
	var shieldFrame = document.getElementById('MessageFrameFrame');
	shieldFrame.style.display = 'none';
	msgFrame.style.display = 'none';
	msgFrame.src = "";

	// setup event handlers
	RegisterShieldFrameEventHandlers(false);
	RegisterMessageFrameEventHandlers(false);

	// hide all combo boxes
	ToggleComboVisibility(true);
}

// build message page url querystring
function BuildMessagePageURL(MsgTitle, MsgName, MsgText, MsgType, RetryURL, GoBackURL, Buttons, ScriptCallBack, AddMsg, ModifyConfigParams, HidePage)
{
	var url;
	if ( typeof(MsgPageURL) == 'undefined' || MsgPageURL == null || MsgPageURL.length < 1)
		url = '../Controls/MessagePage.aspx';
	else
		url = MsgPageURL;
	
	url = url + '?__MsgButtons=' + escape(Buttons);
	url = url + '&__GoBackURL=' + escape(GoBackURL);
	url = url + '&__RetryURL=' + escape(RetryURL);
	url = url + '&__MsgType=' + escape(MsgType);
	url = url + '&__MsgText=' + encodeURIComponent(MsgText);
	url = url + '&__MsgTitle=' + encodeURIComponent(MsgTitle);
	url = url + '&__MsgName=' + encodeURIComponent(MsgName);
	url = url + '&__ScriptCallback=' + escape(ScriptCallBack);
	

    if(AddMsg !='' && AddMsg !=null)
	{
	    url = url + '&__AddMsg=' + encodeURIComponent(AddMsg);			
    }

    if(ModifyConfigParams !='' && ModifyConfigParams !=null)
	{
	    url = url + '&__ModifyCallBackParams=' + escape(ModifyConfigParams);
	}
	if (HidePage != null && HidePage != '') {
	    url = url + '&__HidePage=' + HidePage;
	}
	
	return url;
		
}

// called by message page when a button on message has been clicked
function MessageAcknowledged(MessageName, ReturnValue, ReturnURL, ScriptCallBack, ModifyCallBackParams)
{
	// hide message 
    HideMessage();
	if (ReturnURL == null)
    {
        ReturnURL = "";
    }
	// if a client script callback is specified, call that passing the return values,
	if (ScriptCallBack.length > 0)
	{
	    if (ModifyCallBackParams == "True")
	    {
		    eval(CreateCallBack(MessageName, ReturnValue, ReturnURL, ScriptCallBack));		
		}
		else
		{	
		    //This is temporary code in order to avoid this messagebox changes the original function by
		    //adding parameters in front of  original params.
		    //To make this right, it needs to add params at the end, so that it can become optional params. 	    
		    //if canceld, then close, this is one another thing needed to be changed, because this function
		    //only accepts one callback that doesn't accept more that one script to accomodate more than
		    //one button event. So, right now, the return value cancel will hide message
		    // IIF ModifyConfigParams = false, and return value = 2, cancel.
		    if (ReturnValue == 2)
		    {		       
		         HideMessage();
		    }
		    else
		    {
		       eval(ScriptCallBack);
		    }
		}
	}
}

function CreateCallBack(MessageName, ReturnValue, ReturnURL, ScriptCallBack)
{
    if (ReturnURL == "")
    {
        ReturnURL = null;
    }
	var myArgs = "'" + MessageName + "', " + ReturnValue + ", '" + ReturnURL + "'";
	var newCallback = ScriptCallBack;
	var startIdx;
	var lastIdx;
	
	if (newCallback != null && newCallback.length > 0)
	{
		// look for if this callback has parameters already specified
		startIdx = newCallback.indexOf("(");
		lastIdx = newCallback.lastIndexOf(")");
		
		// oooh... someone is being fancy and trying to use arguments
		if (startIdx > -1 && lastIdx > -1)
		{
			// extract their arguments
			var userArgs = "";
			if ((lastIdx - startIdx) > 1) // are there any arguments?
				userArgs = newCallback.substring(startIdx+1, lastIdx);
						
			// create our own arguments			
			if (userArgs.length > 0) 
				myArgs = myArgs + ",";
			
			// and insert our own arguments before theirs
			newCallback = newCallback.substring(0, startIdx+1) + myArgs + userArgs + ")";
		}
		else
			newCallback = newCallback + "(" + myArgs + ")"
	}
	
	return newCallback;
}

function GetScrollX()
{
	var scrollX;
	
	if (document.all)
	{
		if (!document.documentElement.scrollLeft)
			scrollX = document.body.scrollLeft;
		else
			scrollX = document.documentElement.scrollLeft;
	}
	else
	{
		scrollX = window.pageXOffset;
	}
	
	return scrollX;
}

function GetScrollY()
{
	var scrollY;
	
	if (document.all)
	{
		if (!document.documentElement.scrollTop)
			scrollY = document.body.scrollTop;
		else
			scrollY = document.documentElement.scrollTop;
	}
	else
	{
		scrollY = window.pageYOffset;
	}
	
	return scrollY;
}

// toggle combo visibilty
function ToggleComboVisibility(Visible)
{
	var sVisibility;
	var combos = document.body.getElementsByTagName("SELECT");
	
	if (combos != null) 
	{
		if (Visible)
			sVisibility = "visible";
		else
			sVisibility = "hidden";
	
		// loop through all combos on page and set visibility
		for (var i=0; i<combos.length; i++)
		{
			if (sVisibility == "visible")
			{
				// if the previous visibility state could not be determined, don't change the state
				// this will prevent cases where the control did not exist during the loading from becoming visble
				// it was not previously invisible so make it visible
				if (typeof(combos[i].PreviouslyInvisible) != 'undefined' && combos[i].PreviouslyInvisible != true) 
				{
					combos[i].style.visibility = sVisibility;
					combos[i].PreviouslyInvisible = false;
				}
			}
			else if (sVisibility == "hidden")
			{
				if (combos[i].style.visibility == "hidden")
					combos[i].PreviouslyInvisible = true;
				else
					combos[i].PreviouslyInvisible = false;
								
				combos[i].style.visibility = sVisibility;						
			}
		}	
	}
}

function ResizeShieldFrame()
{
	var shieldFrame = document.getElementById('MessageFrameFrame');        
            
    if (shieldFrame != null)
    {    
		// do sizing of shield	
		shieldFrame.style.display = 'block';
		shieldFrame.style.width = document.body.scrollWidth;
		shieldFrame.style.height = document.documentElement.clientHeight;
		shieldFrame.style.marginTop = GetScrollY();
    }
}

function ResizeMessageFrame()
{
    var frame = document.getElementById('MessageFrameValue');
            
    if (frame != null && window.MessageFrameValue.setFocus != null)
    {    
        // do sizing
        frame.style.display = "block";
        var newWidth = frame.Document.body.scrollWidth;
        var newHeight = frame.Document.body.scrollHeight;                      
        frame.style.width =  newWidth;           
        frame.style.height = newHeight;
          
        // do positioning        
        RepositionMessageFrame();
        eval(window.MessageFrameValue.setFocus.call())
    }
}     

function RepositionMessageFrame()
{
    var frame = document.getElementById('MessageFrameValue');
            
    if (frame != null && window.MessageFrameValue.setFocus != null)
    {  
        // positioning code
        var leftMargin = -1 * ((frame.style.width.replace("px", "") / 2) - GetScrollX());
		var topMargin = -1 * ((frame.style.height.replace("px", "") / 2) - GetScrollY());        
        frame.style.marginLeft = leftMargin + "px";
        frame.style.marginTop =  topMargin + "px";   
    }
}


function RegisterShieldFrameEventHandlers(bEnable)
{
	var shieldFrame = document.getElementById('MessageFrameFrame');

	// detach all event handlers first to prevent multiple registration
	shieldFrame.detachEvent('onload', ResizeShieldFrame);
	//window.detachEvent('onkeypress', ResizeShieldFrame);
	//window.detachEvent('onscroll', ResizeShieldFrame);
	
	// setup all event handlers for sizing of iframe
	if (bEnable == true)
	{
		shieldFrame.attachEvent('onload', ResizeShieldFrame);		
		//window.attachEvent('onkeypress', ResizeShieldFrame);
		//window.attachEvent('onscroll', ResizeShieldFrame);
	}
}

function RegisterMessageFrameEventHandlers(bEnable)
{
	var msgFrameValue = document.getElementById('MessageFrameValue');

	// detach all event handlers first to prevent multiple registration
	msgFrameValue.detachEvent('onload', ResizeMessageFrame);
	window.detachEvent('onkeypress', RepositionMessageFrame);
	window.detachEvent('onscroll', RepositionMessageFrame);
	
	// setup all event handlers for sizing of iframe
	if (bEnable == true)
	{
		msgFrameValue.attachEvent('onload', ResizeMessageFrame);		
		window.attachEvent('onkeypress', RepositionMessageFrame);
		window.attachEvent('onscroll', RepositionMessageFrame);
	}
}

// insert a waiting message followed by an imperceptible delay before calling
// the specified function. This is to get the repainting of the screen
// needed by the message window out of the main function execution call
// stack so that the screen repaints before the entire stack completes
Function.prototype.waitingMessageBefore = function(MsgName, MsgText, ScriptCallBack, HideOnLoad) 
{
    var __method = this, args = $A(arguments);
	args.splice(0, 4, 1);
    DisplayWaiting(MsgName, MsgText, ScriptCallBack, HideOnLoad, true);
    return __method.delay.apply(__method, args);
}

Function.prototype.showShieldBefore = function(MsgName, MsgText, ScriptCallBack, HideOnLoad) {
    var __method = this, args = $A(arguments);
    args.splice(0, 4, 1);
    ShowShield();
    //DisplayWaiting(MsgName, MsgText, ScriptCallBack, HideOnLoad, true);
    return __method.delay.apply(__method, args);
}
