﻿var g_ActivePopup = null;
var g_DefaultButton = null;
var g_CancelButton = null;

function IsLivePopupOpen()
{
	return (g_ActivePopup != null);
}
function showLivePopup(popupName, defaultButtonId, cancelButtonId)
{
	// Make sure we only display 1 popup at a time
	if (g_ActivePopup != null)
		hideLivePopup();

	// Save the default button	
	g_CancelButton = document.getElementById(cancelButtonId);
	g_DefaultButton = document.getElementById(defaultButtonId);

	// Display the Popup
	DisplayPopup(popupName);	
}

function hideLivePopup()
{
	if(g_ActivePopup != null)
	{
		g_ActivePopup.className = "popupHidden";
		document.getElementById("popupDisable").className = "popupHidden";

		// Hide any Select boxes (that show through in IE6)
		HideSelects(false, g_ActivePopup);
		
		// Detach our Tab trap
		document.detachEvent("onkeydown", onPopupKeyDown);

		g_ActivePopup = null;
		g_DefaultButton = null;
		g_CancelButton = null;
	}
}

function defaultLivePopupAsyncCallback(status, responseText, context )
{
	if (status != "UpdateWithError" && status != "Error")
	{
		hideLivePopup();
	}
	else
	{
		// Re-enable the buttons to try again
		g_CancelButton.disabled = false;
		g_DefaultButton.disabled = false;
	}
}

function DisplayPopup(popupName)
{
	// Find the Popup Window
	g_ActivePopup = document.getElementById(popupName);
	if(g_ActivePopup)
	{
		// Get the dimensions of the client area of the browser
		var zoomPercent = GetZoomPercent();
		var windowHeight = getWindowHeight() / zoomPercent;
		var windowWidth = getWindowWidth() / zoomPercent;

		// We need to take into account the current scroll position of the window
		var vScrollPos = getScrollTop() / zoomPercent;
		var hScrollPos = getScrollLeft() / zoomPercent;

		// Display the popup
		g_ActivePopup.className = "popupVisible";

		// Position the Active Popup in the middle of the client area of the browser		
		g_ActivePopup.style.top = (vScrollPos + ((windowHeight - g_ActivePopup.offsetHeight) / 2)) + "px";
		g_ActivePopup.style.left =  (hScrollPos + ((windowWidth - g_ActivePopup.offsetWidth) / 2)) + "px";

		// Display the disabling DIV
		document.getElementById("popupDisable").className = "popupDisable";
	
		// Position the Disable Div
		PositionOverlays();
		
		// Hide any Select boxes (that show through in IE6)
		HideSelects(true, g_ActivePopup);
	
		// Attach our Tab trap
		document.attachEvent("onkeydown", onPopupKeyDown);
		
		// Set the focus to the first element in the popup
		focusFirstElement();
	}
}

function focusFirstElement()
{
	// Sets the focus to the first focusable element in the popup (if any)
	var element = getFirstElement();
	if(element)
		element.focus();
}

function focusLastElement()
{
	// Sets the focus to the last focusable element in the popup (if any)
	var element = getLastElement();
	if(element)
		element.focus();
}

function getFirstElement()
{
	// Returns the first focusable element in the popup
	if(g_ActivePopup)
	{	
		// Get the Popup's Content DIV
		var content = document.getElementById(g_ActivePopup.id + "Content");
		
		// Find the first focussable element within the Popup's content
		if(content)
		{
			var element = content.firstChild;
			while(element != null)
			{
				if(isFocusable(element))
				{
					return element;
				}
				else if (element.hasChildNodes())
			    {
			        element = element.firstChild;
			    }
			    else if (element.nextSibling != null)
			    {
				    element = element.nextSibling;
				}
				else if (element.parentNode != content)
				{
				    element = element.parentNode;
				    while(element.nextSibling == null)
				    {
				        element = element.parentNode;
				    }
				    element = element.nextSibling;
				}
				else
				{
				    element = content;
				}
			}
		}
	}
}

function getLastElement()
{
	// Returns the last focusable element in the active popup
	if(g_ActivePopup)
	{
		// Get the Popup's Content DIV
		var content = document.getElementById(g_ActivePopup.id + "Content");
		// Find the last focussable element within the Popup's content
		if(content)
		{
			var element = content.lastChild;
			while(element != null && element != content)
			{
				if(isFocusable(element))
				{
					return element;
				}
				else if (element.hasChildNodes())
			    {
			        element = element.lastChild;
			    }
			    else if (element.previousSibling != null)
			    {
				    element = element.previousSibling;
				}
				else if (element.parentNode != content)
				{
				    element = element.parentNode;
				    while(element.previousSibling == null)
				    {
				        element = element.parentNode;
				    }
				    element = element.previousSibling;
				}
				else
				{
				    element = content;
				}
			}
		}	
	}
	
	return null;
}

function isFocusable(element)
{
	// Returns TRUE if we can set focus to the element type
	switch(element.tagName)
	{
		case "BUTTON":
		case "A":
		case "TEXTAREA":
		case "SELECT":
			return (!element.disabled);
		case "INPUT":
			if(element.type == "hidden")
				return false;
			return true;
		default:
			return false;
	}
}

function onPopupKeyDown(ev)
{
    if (g_ActivePopup == null)
        return CancelEvent(ev);
        
    // Enter: if the Cancel button has the focus, run its click handler.
    // Otherwise, run the default button's click handler (if a default 
    // button is defined).
    if (ev.keyCode == 13) 
    {
        var ctrlToClick = null;
    
        if (document.activeElement == g_CancelButton)
        {
            ctrlToClick = g_CancelButton;
        }
        else if (g_DefaultButton != null && !g_DefaultButton.disabled)
        {
            ctrlToClick = g_DefaultButton;
        }
        
        if (ctrlToClick != null)
        {
            ctrlToClick.onclick();
            return CancelEvent(ev);
        }
    }
	
	if (g_CancelButton != null && g_CancelButton.disabled == false && ev.keyCode == 27) // Escape
	{
	    g_CancelButton.onclick();
		return CancelEvent(ev);
	}
	
	if (ev.keyCode == 9)    // Tab
	{
		// Check if we're tabbing forwards or backwards
		// and if we're about to step off the popup
		if(ev.shiftKey)
		{
			// Tabbing backwards
			if( ev.srcElement == getFirstElement() || !containsTag(g_ActivePopup, ev.srcElement) )
			{
				focusLastElement();
				return CancelEvent(ev);
			}
		}
		else
		{
			// Tabbing forwards
			if(ev.srcElement == getLastElement() || !containsTag(g_ActivePopup, ev.srcElement) )
			{
				focusFirstElement();
				return CancelEvent(ev);
			}
		}
	}
}

function PositionOverlays()
{
	if (g_ActivePopup != null)
	{
		// Get the dimensions of the client area of the browser
		var zoomPercent = GetZoomPercent();
		var windowHeight = getWindowHeight() / zoomPercent;
		var windowWidth = getWindowWidth() / zoomPercent;

		// We need to take into account the current scroll position of the window
		var vScrollPos = getScrollTop() / zoomPercent;
		var hScrollPos = getScrollLeft() / zoomPercent;

		if (g_ActivePopup != null)
		{
			// Position the disabling DIV so that it exactly covers
			// the current client area of the browser
			var disableDiv = document.getElementById("popupDisable");
			disableDiv.style.top = vScrollPos + "px";
			disableDiv.style.left = hScrollPos + "px";
			disableDiv.style.height = windowHeight + "px";
			disableDiv.style.width = windowWidth + "px";
		}	
	}
}

function HideSelects(value, exceptElement)
{
	if (document.all)
	{
		var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])
		if (version < 7.0)
		{
			var hiddenSelects = document.getElementsByTagName("SELECT");
			for (var i=0; i < hiddenSelects.length; i++)
				hiddenSelects[i].style.visibility = (value ? 'hidden' : 'visible');
				
			var visibleSelects = exceptElement.getElementsByTagName("SELECT");
			for (var i=0; i < visibleSelects.length; i++)
				visibleSelects[i].style.visibility = 'visible';
		}
	}
}

// Add the resize event
if (window.attachEvent)
{
	// IE
	window.attachEvent("onresize", PositionOverlays);
	window.attachEvent("onscroll", PositionOverlays);	
}
else if (window.addEventListener)
{
	// Firefox etc
	window.addEventListener("resize", PositionOverlays, false);
	window.addEventListener("scroll", PositionOverlays, false);	
}

function getScrollTop()
{
	var pos = 0;
	if(document.body && document.body.scrollTop)
		pos = parseInt(document.body.scrollTop, 10);
	if(pos == 0 && document.documentElement && document.documentElement.scrollTop)
		pos = parseInt(document.documentElement.scrollTop, 10);
	return pos;
}

function getScrollLeft()
{
	var pos = 0;
	if(document.body && document.body.scrollLeft)
		pos = parseInt(document.body.scrollLeft, 10);
	if(pos == 0 && document.documentElement && document.documentElement.scrollLeft)
		pos = parseInt(document.documentElement.scrollLeft, 10);
	return pos;
}

function getWindowHeight()
{
	if (window.innerHeight != window.undefined)
		return window.innerHeight;
		
	if (document.compatMode == 'CSS1Compat')
		return document.documentElement.clientHeight;
		
	if (document.body)
		return document.body.clientHeight;
		
	return window.undefined; 
}
function getWindowWidth()
{
	if (window.innerWidth != window.undefined)
		return window.innerWidth; 
		
	if (document.compatMode == 'CSS1Compat')
		return document.documentElement.clientWidth; 
		
	if (document.body)
		return document.body.clientWidth; 
		
	return window.undefined; 
}

function GetZoomPercent()
{
	if (document.body.getBoundingClientRect)
	{
		var rect = document.body.getBoundingClientRect();
		return Math.round( (rect.right-rect.left)/getWindowWidth() * 100)/100.0; 
	}
	return 1.0;
}

function validateInput(controlName, errControlName, errorMsg, shouldMatch)
{
    getElementByGid(errControlName).style.display = "none";
    var regex = new RegExp("[\"<'>&)(;#]", "g");
    
    var nameInput = document.getElementById(controlName);
    if (nameInput != null)
    {
        var match = regex.test(nameInput.value);
        if ((shouldMatch && !match) || (!shouldMatch && match))
        {
            getElementByGid(errControlName).style.display = "block";
            document.getElementById(errControlName + "_ErrorMessage").innerText = errorMsg;
            return false;
        }
    }
    return true;
}