// Globals
var maxBarWidth = 0;  // to be set later
var maxBarHeight = 15;  // to be set later

///////////////////////////////////////////////////////////////////////
// OnLoadHandler for entire client site.
///////////////////////////////////////////////////////////////////////
function onLoadHandler(){
    //if there is a function on a page called pageOnLoad, it'll fire here
    if ( typeof pageOnLoad == 'function' )
    {
        pageOnLoad();
    }
    
    // rotate banner
    if (typeof showRotateBanner != 'undefined')
    {
        if (showRotateBanner)
        {
            rotateBanner(bannerRotationDelay);
        }
    }
    
    // display current server time
    if ((typeof timeFormatString != 'undefined') && (typeof currentTimeIntervalId != 'undefined'))
    {
        displayCurrentTime();  // display it now
        if (currentTimeIntervalId)
        {
            window.clearInterval(currentTimeIntervalId);
        }
        currentTimeIntervalId = window.setInterval('displayCurrentTime();', 60000);  // and then once a minute
    }
    
    //start page timout
    if (typeof enableCountdown != 'undefined')
    {
        if (enableCountdown)
	    {
	        InitializeAlertingForm(document.forms[0]);
            DecTimer();  //start timeout countdown
        }
    }
}

///////////////////////////////////////////////////////////////////////
// OnLoadHandler for entire administration site.
///////////////////////////////////////////////////////////////////////
function onLoadHandlerAdministration(){
    var path = window.location.pathname;
    var page = path.substring(path.lastIndexOf('/') + 1);
    
    if(page.toLowerCase().indexOf('login')!=-1 || page.toLowerCase().indexOf('logout')!=-1){
        //on login/logout page
    }else{
        var minutesBeforeTimeout = 15; //must be greater than 2
        var millisecondsToOneMinuteWarning = minutesBeforeTimeout*60000-60000;
        var timeout = setTimeout("onMinuteWarningThenLogout();",millisecondsToOneMinuteWarning);
    }
}

function onMinuteWarningThenLogout(){
    window.status='Your session is about to expire.';
    setTimeout("location.href='logout.aspx?timeout=1';",60000);
}

function onUnloadHandler()
{
    if ((typeof currentTimeIntervalId != 'undefined') && currentTimeIntervalId)
    {
        window.clearInterval(currentTimeIntervalId);
        currentTimeIntervalId = null;
    }
}

function validateTextFields()
{
    inputCollection = document.getElementsByTagName("input");
    if (inputCollection)
    {
        if (!validateTextCollection(inputCollection))
        {
            return false;
        }
    }
    textareaCollection = document.getElementsByTagName("textarea");
    if (textareaCollection)
    {
        if (!validateTextCollection(textareaCollection))
        {
            return false;
        }
    }

    return true;
}

var htmlRegEx = /((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)/m;
function validateTextCollection(textCollection)
{
    for (var i = 0; i < textCollection.length; i++)
    {
        textElement = textCollection[i];
        if (textElement.type == "text" || textElement.type == "textarea")
        {
            var matchArray = textElement.value.toLowerCase().match(htmlRegEx);
            if (matchArray)
            {
                return false;
            }
        }
    }

    return true;
}

function displayCurrentTime()
{
    var elCurrentTime = document.getElementById("divCurrentTime");
    if (elCurrentTime)
    {
        var currentDateTime = new Date();
        var currentTimeString = "";
        
        if (timeFormatString == "hh:mm tt")
        {
            var hourAdjustment = 0;
            var amPm = "";
            
            if (currentDateTime.getHours() < 12)
            {
                amPm = "AM";
            }
            else
            {
                amPm = "PM";
                if (currentDateTime.getHours() > 12)
                {
                    hourAdjustment = 12;
                }
            }
            currentTimeString = toTwoDigitString(currentDateTime.getHours() - hourAdjustment) + ':' +
                toTwoDigitString(currentDateTime.getMinutes()) + ' ' + amPm;
        }
        else // assume HH:mm
        {
            currentTimeString = toTwoDigitString(currentDateTime.getHours()) + ':' + toTwoDigitString(currentDateTime.getMinutes());
        }
        
        elCurrentTime.innerHTML = currentTimeString;
        
        delete currentDateTime;
    }
}

function toTwoDigitString(hourOrMinute)
{
    var digits = hourOrMinute.toString();

    return digits.length == 1 ? '0' + digits : digits;
}

function rewriteQuerystring(url, item, value){
    
    var updatedUrl;
    if (url.indexOf('?') > 0)
    {
        updatedUrl = url.substring(0,url.indexOf('?'));
    }else{
        updatedUrl = url;
    }

    updatedUrl = updatedUrl + '?' + item + '=' + value
    return updatedUrl;   
}

function appendToQuerystring(url, item, value){
    //decide to append to querystring, or add one.
    var updatedUrl;
    if (url.indexOf('?') > 0)
    {
        updatedUrl = url + '&';
    }else{
        updatedUrl = url + '?';
    }
    updatedUrl = updatedUrl + item + '=' + value
    return updatedUrl;
}

function deleteEmail(emailId)
{
    if (confirm(emailDeleteWarning))
    {
        var txtElement = getElementByPartialName("txtDeleteEmailId");
        if (txtElement)
        {
            txtElement.value = emailId;
            document.forms[0].submit();
            return false;
        }
    }
    return false;
}

///////////////////////////////////////////////////////////////////////
// Open a New Window
///////////////////////////////////////////////////////////////////////
function fnNewWindow(newURL,scrWidth,scrHeight,scrTop,scrLeft,menubar,windowname) {
	var systemtime=new Date();
	var systemmilliseconds=systemtime.getTime() + 1;
	if (!windowname){
		windowname=systemmilliseconds;
	}
	windowparams = "width=" + scrWidth + ",height=" + scrHeight + ",top=" + scrTop + ",left=" + scrLeft + "," + menubar ;
	return window.open(newURL, systemmilliseconds, windowparams);
}
///////////////////////////////////////////////////////////////////////

function printIt() {
    if (this.window){
    	this.window.print();
    }
}

///////////////////////////////////////////////////////////////////////
// Timeout
///////////////////////////////////////////////////////////////////////

var timer = 0;
var alertingForm;
var countInSeconds = false;
var displayTimer = true;

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
//code below should be implemented by page that needs to keep track of timeout

function InitializeAlertingForm(form)
{
	alertingForm = form;	
}

function countdown()
{
  if(timer > 0 && countInSeconds == false)
  {
	
	if (timer == 1)
	{
		countInSeconds = true;
		timer = 60;	//timer now stores seconds			
		status = TimeoutOneMinute;        
		setTimeout("countdown()",1000);    			
	}
	else
	{
		status = TimeOutMessagePrefix + " "  + timer + " " + TimeOutMessageSuffix;        
		setTimeout("countdown()",60000);    			
	}
	timer -= 1;
  }
  else
  {	
	if (timer ==0){
	    timer = 60;
	    displayTimer = true;
	    countInSeconds = true;
	}
	status = TimeOutMessagePrefix + " " + timer + " " + secondPlural + ".";	
	window.status = status;

	if (timer >= 59)
	{
		/////////////////////////////////////////////////////////////
		//centering the screen
		
		//scroll to the top to get attention of inactive user
		self.scrollTo(0,0);
				
		var AlertingDiv = document.getElementById("timeoutPopUp");
		var popupHeight = AlertingDiv.clientHeight;
		var popupWidth = AlertingDiv.clientWidth;
		var midScreenHeight = parent.document.body.offsetHeight / 2;
		var midScreenWidth = parent.document.body.offsetWidth /2;

		AlertingDiv.style.left = midScreenWidth - (popupWidth/2);
		AlertingDiv.style.top = 200;
		AlertingDiv.style.zIndex = 1000;
		AlertingDiv.focus();

	
		AlertingDiv.style.visibility = "visible";
		/////////////////////////////////////////////////////////////
	}	 	
	else if (timer == 0)
	{
		status = TimeOutMessage;				
		displayTimer = false;	
		displayUserTimeoutAlert();			
		//clearTimeout();

		var timeoutFlag = document.getElementById("Timedout");
		timeoutFlag.value = "1";
	}
	//send to logout page
	if (displayTimer)
	{
	    displayUserTimeoutAlert();	
		setTimeout("countdown()",1000);	
		timer -= 1;	
	}		
  }
}

var lMinutesLeft;
if (window.lSessionTimeout)
{
    lMinutesLeft = lSessionTimeout;
}
var timerId; // holds the timerid so we can stop it later if we need
var TimeOutURL = "../WebPages/Logout.aspx?message=timeout";

function ResetSession()
{
    window.location.reload( true );
}

function DecTimer() {
	if (lMinutesLeft<1) {
	    AutoLogout();
	} else {
	    timerId = window.setTimeout('DecTimer();', 60000);
	}
	if (lMinutesLeft == lSessionTimeout){
	    window.status = TimeOutMessagePrefix + ' ' + lMinutesLeft + ' ' + TimeOutMessageSuffix;
	}else if(lMinutesLeft == 1){
	    window.focus();
	    window.status = TimeoutOneMinute;
	    countdown();
	    window.blur();
	    window.focus();
	    displayUserTimeoutAlert();
	    document.getElementById("TimeoutLink").focus();
	}else{
	    window.status = TimeOutMessagePrefix + ' ' + lMinutesLeft + ' ' + TimeOutMessageSuffix;
	}
	lMinutesLeft-=1;
}

//code should be implemented by page that will control display to user dialog
//when it's about to timeout
function displayUserTimeoutAlert()
{
	var innerHTML;
	var message = TimeOutMessagePrefix + " " + timer + " " + secondPlural.toLowerCase() + ".";
	window.status = message;
	innerHTML = "<table bgcolor='#eeeeee' style='color:Black; border-style:outset' class='Timeout'>";
	innerHTML += "<tr><td><div name='timeoutMessage' id='timeoutMessage'>" + message + "</div></td></tr>";
	innerHTML += "<tr><td align='center'><br><a id='TimeoutLink' name='TimeoutLink' href='javascript:ResetSession();'>" + resetLabel + "</a><br></td></tr></table>";

	document.getElementById("timeoutPopUp").innerHTML = innerHTML;
	setTimeout("updateMessage()",1000);    
}

function updateMessage()
{
    var message = TimeOutMessagePrefix + " " + timer + " " + secondPlural.toLowerCase() + ".";
	window.status = message;
    document.getElementById("timeoutMessage").innerHTML = message;
    setTimeout("updateMessage()",1000); 
}   

function AutoLogout() {
	window.status=TimeOutMessage;
	location.href=(TimeOutURL);
}

function toggleElement(element) 
{ 
	//This will hide/show an element.
	if(document.getElementById)
	{
		if(getElementByPartialName(element).style.display=='none' )
		{
			getElementByPartialName(element).style.display = '';
		}
		else
		{
			getElementByPartialName(element).style.display = 'none';
		}
	}
 }

var previousDisplayType = new String();

function showElementTimed(elementId, timeInSeconds)
{
    showElement(elementId);
    window.setTimeout('hideElement("' + elementId + '")', timeInSeconds * 1000);
} 
 
function showElement(elementId)
{
    if (document.getElementById)
    {
        var element = getElementByPartialName(elementId);
        if (element != null)
        {
            element.style.display = previousDisplayType;
        }
    }
}
 
function hideElement(elementId)
{
    if (document.getElementById)
    {
        var element = getElementByPartialName(elementId);
        if (element != null)
        {
            previousDisplayType = element.style.display;
            element.style.display = 'none';
        }
    }
}
 
function changeGraphic(element, graphicLocation) 
{ 	
	//Change the current image to the new image based on the new location
	if(document.getElementById)
	{
	    var imgElement = getElementByPartialName(element);
	    if (imgElement)
	    {
		    imgElement.src = graphicLocation;
		}
	}    
}

///////////////////////////////////////////////////////////////////////
// Client Side Add/Remove Session
// RJI 10/17/05
// Calls the server-side page to add/remove session, returns graphic
// to indicate success or failure
///////////////////////////////////////////////////////////////////////
function toggleSession(sessionId, bAddSession, userId, encryptedUserId, eventCode) 
{
    var oImage = new Image;
    oImage.src = "../WebPages/ToggleSession.aspx?EventSessionId=" + sessionId + "&add=" + bAddSession + "&U=" + userId + "&EUI=" + encryptedUserId + "&eventCode=" + eventCode;

    return true;
}

///////////////////////////////////////////////////////////////////////
// Handle Enter Key click within a Form
///////////////////////////////////////////////////////////////////////
function handleEnterKeyClickOnForm(submitButtonName)
{
    if (event)
    {
        if (event.keyCode==13)
        {
            if (document.getElementById)
            {
                getElementByPartialName(submitButtonName).click();
                return false;
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////
// Toggle Row and Image
///////////////////////////////////////////////////////////////////////
function toggleRowAndImage(rowId,imageId,textId,graphicLocation,graphicLocationToggled,hideText,viewText)
{			
	//This will hide/show the row, and change the image and the text
	if(document.getElementById)
	{ 
		toggleElement(rowId);
		
		if(getElementByPartialName(imageId).toggled == "0")
		{						
			getElementByPartialName(imageId).toggled = "1";
			changeGraphic(imageId, graphicLocation);
			getElementByPartialName(textId).innerHTML = viewText;					
		}
		else
		{
			getElementByPartialName(imageId).toggled = "0";
			changeGraphic(imageId, graphicLocationToggled);	
			getElementByPartialName(textId).innerHTML = hideText;				
		}
	}	       
}


///////////////////////////////////////////////////////////////////////
// setCheckboxes
///////////////////////////////////////////////////////////////////////
function setCheckboxes(checkBoxId,checkBoxHeaderId)
{
    var counter;		
	var isHeader;
	if(document.getElementById)
	{ 
		
		if(checkBoxId == checkBoxHeaderId)	//This is the header checkBox
		{
			isHeader = true;
		}
		
		if(isHeader)	//If this is the Header CheckBox, set all of the CehBoxes in that column to that value.
		{
			counter = 1;
			while(true)
			{
				if(getElementByPartialName(checkBoxHeaderId + counter.toString()))
				{
					getElementByPartialName(checkBoxHeaderId + counter.toString()).checked = getElementByPartialName(checkBoxHeaderId).checked;
					counter++;
				}
				else
				{
					break;
				}
			}
		}
		else
		{
			counter = 1;
			var isChecked = false;
			while(true)	//If ALL CheckBoxes in this column are checked, check the Header CheckBox
			{
			    isChecked = true;
				if(getElementByPartialName(checkBoxHeaderId + counter.toString()))
				{
					if(getElementByPartialName(checkBoxHeaderId + counter.toString()).checked == false)
					{
						isChecked = false;
						break;
					}
					counter++;
				}
				else
				{
					break;
				}
			}
			getElementByPartialName(checkBoxHeaderId).checked = isChecked;
		}
		
	}
}

///////////////////////////////////////////////////////////////////////
// clearAllSettings
///////////////////////////////////////////////////////////////////////
function clearAllSettings(){
	//clear all visible items on form
	//solves Netscape Issues with the reset button.
	for(var x=0; x < document.frm.length ; x++){
		if (document.frm.elements[x].type != 'hidden'){
			if (document.frm.elements[x].type == 'radio' || document.frm.elements[x].type == 'checkbox'){
				document.frm.elements[x].checked = false;
			}else{
				document.frm.elements[x].value = '';
			}
		}
	document.frm.Dates[0].checked = true;	
	}
}

///////////////////////////////////////////////////////////////////////
// loadComposePage
///////////////////////////////////////////////////////////////////////
function loadComposePage(){
    window.opener.location.href = 'compose.aspx?haslist=1';
    window.close();
}

function onsiteLogout(){
	if(window.external && this.location.host != 'localhost'){
		window.external.InitScriptInterface();  
		SiteKiosk.Logout();
	}
}

///////////////////////////////////////////////////////////////////////
// rotateBanner: Randomly rotates banners, with a Timeout parameter (AG 12/16/2005)
///////////////////////////////////////////////////////////////////////
function rotateBanner(seconds)
{
	var browser;
	var placeHolder = "bannerPlace";
	
	if (document.all) browser = document.all[placeHolder]; //IE4+
	if (document.layers) browser = document.layers[placeHolder]; //NS4
	if (document.getElementById) browser = document.getElementById(placeHolder); // IE5+ OR NS6+/Firefox
	
	if (browser){
	    if (typeof(bannerArray)!='undefined'){
	        if (bannerArray.length > 0)
	        {
		        index = Math.floor(Math.random() * bannerArray.length);
		        browser.innerHTML = bannerArray[index];
		        setTimeout("rotateBanner(" + seconds + ")", (seconds * 1000));
	        }
	    }
	}
}

///////////////////////////////////////////////////////////////////////
// getElementByPartialName
//
// since .net assigns the form element  name dynamically prefix with the control names
// we do not know the exact names, that's why we need to loop through and find a match
///////////////////////////////////////////////////////////////////////
function getElementByPartialName(partialName)
{
  	var element = null;
	var allElements = document.getElementsByTagName("*");
	
    for (var i = 0; i < allElements.length; i++)
    {
        if (allElements[i].id.indexOf(partialName) >= 0)
        {
            element = allElements[i];
            break;
        }
    }

	return element;
}

///////////////////////////////////////////////////////////////////////
// isQuickTimeInstalled
//
// Determine if QuickTime is installed or not.
///////////////////////////////////////////////////////////////////////
function isQuickTimeInstalled()
{
    var hasQuickTime = false;
    var isIe = (navigator.userAgent.indexOf("MSIE") != -1);
    var isWindows = (navigator.userAgent.indexOf("Windows") != -1);
    
    if (isIe && isWindows)
    {
        try
        {
            var qtObject = new ActiveXObject("QuickTimeCheckObject.QuickTimeCheck.1");
            if (qtObject != null)
            {
                hasQuickTime = true;
            }
        }
        catch (e)
        {
        }
    }
    else
    {
        if (navigator.plugins)
        {
            for (var i = 0; i < navigator.plugins.length; i++)
            {
                if (navigator.plugins[i].name.indexOf("QuickTime") >= 0)
                {
                    hasQuickTime = true;
                    break;
                }
            }
        }
    }
    
    return hasQuickTime;
}

// Slide dialog into view.
var currentDialogHeight = 0;
var maxDialogHeight = 1200;  // default only--will try to get actual height of current page
var maxDialogWidth = 1000;  // default only--will try to get actual width of current page
var topPadding = 100;
var dialogBoxHeight = 300;
var dialogBoxWidth = 300;
var dialogElement = null;
var intervalId = 0;

function slideDialogIntoView(topPaddingInPixels, heightInPixels, widthInPixels)
{
    // Save settings into global variables.
    topPadding = topPaddingInPixels;
    dialogBoxHeight = heightInPixels;
    dialogBoxWidth = widthInPixels;
    
    // Determine page height, if possible.
    var wrapperElement = document.getElementById("wrapper");
    if (wrapperElement && wrapperElement.clientHeight && wrapperElement.clientHeight > maxDialogHeight)
    {
        maxDialogHeight = wrapperElement.clientHeight;
    }
    
    // Start sliding.
    dialogElement = document.getElementById("divDialog");
    if (dialogElement)
    {    
        dialogElement.style.display = "";
            
        intervalId = window.setInterval("slideDialog()", 1);
    }
}

// Helper function for slideDialogIntoView.
function slideDialog()
{
    if (currentDialogHeight < maxDialogHeight)
    {
        // Continue sliding.
        currentDialogHeight += 4;
        dialogElement.style.height = currentDialogHeight + "px";
    }
    else
    {
        // Finish sliding and display dialog box.
        window.clearInterval(intervalId);
        
        dialogElement.style.height = (maxDialogHeight - topPadding - 2).toString() + "px";
        dialogElement.style.paddingTop = topPadding.toString() + "px";

        var dialogBoxElement = document.getElementById("divDialogBox");
        if (dialogBoxElement)
        {
            dialogBoxElement.style.display = "";
            dialogBoxElement.style.height = dialogBoxHeight.toString() + "px";
            dialogBoxElement.style.width = dialogBoxWidth.toString() + "px";
        }
    }
}

function hideDialog(dialogName)
{
    var ddlViews = getElementByPartialName("divViews");
    if (ddlViews)
    {  
          ddlViews.style.display = "";
    }
    var dialogBackground = document.getElementById("divDialogBackground");
    if (dialogBackground)
    {    
        dialogBackground.style.display = "none";

        var dialogBox = document.getElementById("divDialogBox");
        if (dialogBox)
        {
            var dialogNameDiv = document.getElementById(dialogName);
            if(dialogNameDiv)
            {
                
                dialogBox.style.display = "none";
                dialogNameDiv.style.display = "none";
            }
        }
    }
}

// Display a horizontally centered modal dialog with a translucent gray background.
function displayDialog(widthInPixels, heightInPixels, topMarginInPixels, dialogName)
{
    // Determine wrapper height and width, if possible.
    var wrapperElement = getElementByPartialName("wrapper");
    var dialogHeightInPixels = maxDialogHeight;
    var wrapperHeight = getElementHeight(wrapperElement);
    if (wrapperHeight > 0)
    {
        dialogHeightInPixels = wrapperHeight; // - 4;  // -4 until wrapper border is removed
    }
    var dialogWidthInPixels = maxDialogWidth;
    var wrapperWidth = getElementWidth(wrapperElement);
    if (wrapperWidth > 0)
    {
        dialogWidthInPixels = wrapperWidth; // - 4;  // - 4 until wrapper border is removed
    }
    
    // Display dialog.
    dialogBackground = document.getElementById("divDialogBackground");
    if (dialogBackground)
    {   
        var ddlViews = getElementByPartialName("divViews");
        if (ddlViews)
        {  
              ddlViews.style.display = "none";
        } 
        dialogBackground.style.display = "";
        dialogBackground.style.height = dialogHeightInPixels.toString() + "px";
        dialogBackground.style.width = dialogWidthInPixels.toString() + "px";

        var dialogBox = document.getElementById("divDialogBox");
        if (dialogBox)
        {
            var dialogNameDiv = document.getElementById(dialogName);
            if (dialogNameDiv)
            {
                var leftPosition = (dialogWidthInPixels - widthInPixels) > 0 ? Math.round((dialogWidthInPixels - widthInPixels) / 2) : 0;
                dialogBox.style.display = "";
                dialogBox.style.position = "absolute";
                dialogBox.style.left = leftPosition.toString() + "px";
                dialogBox.style.top = topMarginInPixels.toString() + "px";
                dialogBox.style.width = widthInPixels.toString() + "px";
                dialogBox.style.height = heightInPixels.toString() + "px";
                dialogNameDiv.style.display = "block";
            }
        }
    }
}

// Popup window functions.
var popupWindow = null;

function CreatePopupFromDiv(divContentId)
{
    popupWindow = new PopupWindow(divContentId);
}

function ShowPopupAtOffset(divAnchorId, xOffsetInPixels, yOffsetInPixels)
{
    if (popupWindow)
    {
        popupWindow.offsetX = xOffsetInPixels;
        popupWindow.offsetY = yOffsetInPixels;
        popupWindow.showPopup(divAnchorId);
    }
}

function HidePopup()
{
    if (popupWindow)
    {
        popupWindow.hidePopup();
    }
}

function DeletePopup()
{
    popupWindow = null;
}

function CopyTextFieldToHiddenField(txtInput, hidOutput)
{
    var elInput = getElementByPartialName(txtInput);
    var elOutput = getElementByPartialName(hidOutput);
    if (elInput && elOutput)
    {
        elOutput.value = elInput.value;
    }
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function getElementWidth(element)
{
    var elementWidth = 0;
    
    if (element && element.offsetWidth)
    {
        elementWidth = element.offsetWidth;
    }
    else if (element && element.clientWidth)
    {
        elementWidth = element.clientWidth;
    }

    return elementWidth;
}

function getElementHeight(element)
{
    var elementHeight = 0;
    
    if (element && element.offsetHeight)
    {
        elementHeight = element.offsetHeight;
    }
    else if (element && element.clientHeight)
    {
        elementHeight = element.clientHeight;
    }

    return elementHeight;
}


