var brushState = "block";

function $(controlId){ return document.getElementById(controlId); }
function addLoadEvent(loadFunc)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = loadFunc;
	} else {
		window.onload = function(){
		oldonload();
		loadFunc();
		}
	}
}
function CancelEvent()
{
    window.event.returnValue = false;
    return false;
}
// I can never remember the casing for this function, so this makes it not matter.
function cancelEvent()
{
    return CancelEvent();
}
// given any object within a form, this function will find the containing form and submit it
function submitForm(object)
{
	if (object && object != null)
		form = findAncestor(object, "FORM");
	else
		form = window.template;

	if (form != null)
		form.submit();
}
//
// Perform the specified event on the specifed control.  Also sets the
// requested argument into the __EVENTARGUMENT hidden input element.
// If eventName is not specified 'click' will be used by default.
//
function InitiateControlEventWithArgument(controlUniqueID, argument, eventName)
{
    if (eventName == null)
        eventName = 'click';

    if (argument != null && argument != '') 
        $('__EVENTARGUMENT').value = argument;
        
    var ajaxifiedControl = $(controlUniqueID);
    eval('ajaxifiedControl.' + eventName + '()');
}

// Given an object and a type of ancestor to find, locates the first ancestor of the given object that is of the specified type.
// If none is found, null is returned
function findAncestor(object, type)
{
	oParent = object.parentElement;
	while (oParent != null)
	{
		if (oParent.tagName == type)
			return oParent;
		oParent = oParent.parentElement;
	}
	return null;
}

function ltrim(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}
function rtrim(sString) 
{
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}
function trim(sString) 
{
	return ltrim(rtrim(sString));
}

var existingClassNames = new Array();
function showHideBrush()
{
	var links = document.getElementsByName("editlink");
	for (i=0;i<links.length;i++)
	{
		links[i].style.display = brushState;
		links[i].className = "";
		if (brushState == "block")
		{
			existingClassNames[i] = links[i].parentElement.className;
			
			links[i].parentElement.className = "PanelEditLink";
			var title = links[i].getAttribute("panelName");
			links[i].parentElement.title = title;
		}
		else
		{
			links[i].parentElement.className = existingClassNames[i];
			links[i].parentElement.title = "";
		}
	}
	if (brushState == "none")
		brushState = "block";
	else
		brushState = "none";
}

function Rollover(obj, image)
{
	obj.src = image;
}

function printWindow()
{
	var bV = parseInt(navigator.appVersion)
	if (bV >= 4) window.print()
}

function emailWindow()
{
	alert('email window');
}

function showInfoCenter()
{
	alert('InfoCenter');
}

/* CDR - 11/29/2006 - window.showHelp is a standard javascript func - commenting out b/c it was killing help links
function showHelp()
{
	alert('Help!');
}*/

function livePageHeight()
{
	if (window.innerHeight != null)
		return window.innerHeight;
		
	if (document.body.clientHeight != null)
		return document.body.clientHeight;
		
	return null;
}

function livePageWidth()
{
	if (window.innerWidth != null)
		return window.innerWidth;
		
	if (document.body.clientWidth != null)
		return document.body.clientWidth;
		
	return null;
}

// given an object, finds its absolute and relative position on the page
function findAbsoluteCoords(obj)
{
   var shape = new Object();
   shape.left = obj.offsetLeft;
   shape.top = obj.offsetTop;
   shape.width = obj.clientWidth;
   shape.height = obj.clientHeight;
   shape.absoluteLeft = 0;
   shape.absoluteTop = 0;
   
   // figre out the absolute x,y coords by going up the ancestory
   var temp = obj;
   while (temp != null && temp.tagName != 'BODY')
   {
      shape.absoluteLeft = shape.absoluteLeft + temp.offsetLeft;
      shape.absoluteTop = shape.absoluteTop + temp.offsetTop;
      temp = temp.offsetParent;
   }
   
   // if the width is 0 (i.e., unspecified) make it as wide as possible
   if (shape.width == 0)
      shape.width = livePageWidth() - shape.absoluteLeft;

   // if the height is 0 (i.e., unspecified) make it as tall as possible
   if (shape.height == 0)
      shape.height = livePageHeight() - shape.absoluteTop;
   return shape;
}


// returns an array of the url parameters, with each element in the form of "param=value"
function GetURLParameters()
{
	var url = window.document.URL.toString();
	
	if (url.indexOf("?") > 0)
	{
		var parts = url.split("?");
		var paramsArray = parts[1].split("&");
		return paramsArray;
	}
	return null;
}

function FindURLParameter(paramName)
{
	paramName = paramName.toUpperCase();
	var paramsArray = GetURLParameters();
	if (paramsArray != null)
		return FindParameterInArray(paramName,paramsArray);
	return null;
}

// given an array of parm=value strings, splits the parm name from the value, looks for the paramName in the array of names
// and if found returns the param value
function FindParameterInArray(paramName, paramsArray)
{
	paramName = paramName.toUpperCase();
	for (i=0;i<paramsArray.length;i++)
	{
		var sParam =  paramsArray[i].split("=");
		if (sParam[0].toUpperCase() == paramName)
			return sParam[1];
	}	
	return null;
}

// opens a modal dialog given the url, paramaters to pass and a size
function ShowDialog(url, args, width, height) 
{
	var cursor = document.body.style.cursor;
	document.body.style.cursor = "wait";
	var result = window.showModalDialog(url, args, "status:no; center:yes; help:no; minimize:no; maximize:no; scroll:yes; border:thin; statusbar:no; dialogWidth:" + width + "px; dialogHeight:" + height + "px");
	document.body.style.cursor = cursor;
	return result;
}

// opens a dialog window
// Parameters:
//	contentCode - the ContentCode of the content to show in the dialog.  Required.
//	modal - if true the dialog is modal, if false it is pseudo modal, meaning it can postback etc.  If not supplied, false (pseudo) is assumed
//  urlParamString - any url params to pass to the window (e.g., the server).  Should be a string like param1=value1&param2=value2 etc.
//  args - any arguments passed to the client as dialogArguments (for modal), or accessible in opener.dialogWin.args if pseudo
//	width - the width of the dialog.  If not supplied, 600 is assumed
//	height - the width of the dialog.  If not supplied, 400 is assumed
//  returnFunc -- reference to the function (on this caller) to be called when the dialog is done
//  navigationCode - If specified, this value is put into the query string.  This is to allow the IQD to
//    utilize this function.
function CMOpenDialog (contentCode, modal, width, height, urlParamString, args, returnFunc, navigationCode)
{
	// contentCode is required
	if (contentCode != null)
	{
		// initialize any parameters not sent
		if (modal == null || modal != true)
			modal = false;
		if (urlParamString == null)
			urlParamString = "";
		else if (urlParamString.substr(0, 1) != "&")
			urlParamString = "&" + urlParamString;
		if (width == null)
			width = 600;
		if (height == null)
			height = 400;

		var url = gWebRoot + "/iMIS/ContentManagement/Template.aspx?ContentCode=" + contentCode + urlParamString;
        if (url.indexOf('&TemplateType=') < 0)
            url += '&TemplateType=D';
        if (typeof gWebsiteKey != 'undefined' && gWebsiteKey != 'null' && url.indexOf('&WebsiteKey=') < 0)
            url += '&WebsiteKey=' + gWebsiteKey;

		if (navigationCode != null)
    		url = url + "&NavigationCode=" + navigationCode;
   		else if(urlParamString.indexOf("&hkey=") < 0)
   		{
    	    if (gHKey != '')
    	    {
    	        url += "&hkey=" + gHKey;
    	    }
    	    else
    	    {
		        var hkey = FindURLParameter("hkey");
        		
	            if (hkey != null)
		            url = url + "&hkey=" + hkey;
	            else
	            {
		            var hierarchyCode = FindURLParameter("HierarchyCode");
		            if (hierarchyCode != null)
    		            url = url + "&HierarchyCode=" + hierarchyCode;
	            }    		
		    }
	    }
		var session = FindURLParameter("iSession");
		if (session != null)
			url = url + "&iSession=" + session;
		if (modal)
			return ShowDialog(url,args,width,height);
		else
			ShowPseudoDialog(url, args, width, height, returnFunc)
	}
	else
		alert('contentCode is required!');
}

// One object tracks the current modal dialog opened from this window.
var dialogWin = new Object()

// Generate a pseudo modal dialog that can do postback etc. i.e., it is a real window that acts modal
// Parameters:
//    url -- URL of the page/frameset to be loaded into dialog
//    width -- pixel width of the dialog window
//    height -- pixel height of the dialog window
//    returnFunc -- reference to the function (on this page)
//                  that is to act on the data returned from the dialog
//    args -- [optional] any data you need to pass to the dialog
function ShowPseudoDialog(url, args, width, height, returnFunc) {
    // set the window events on the parent so that trying to go back there set focus back to the dialog
	window.attachEvent('onclick',checkModal);
	window.attachEvent('onfocus',checkModal);
	
	// SAT - 11/9/2006 - DT18027
	// Added the following try/catch to handle the exception which occurs when the parent of the 
	// dialog is hosted in c/s.
	var newDialog = false;
	try {
	    if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed))
	        newDialog = true;
	}
	catch(e) {
	    if(e.message == 'The remote server machine does not exist or is unavailable')
	        newDialog = true;
	}
	
	if (newDialog) {
		// Initialize properties of the modal dialog object.
		dialogWin.returnFunc = returnFunc
		dialogWin.returnedValue = ""
		dialogWin.args = args
		if (typeof(returnFunc) == "string" && returnFunc != "")
		{
			if (url.indexOf("?") < 0)
				url += "?" + "iCallbackFunction=" + returnFunc;
			else
				url += "&" + "iCallbackFunction=" + returnFunc;
		}
		dialogWin.url = url
		dialogWin.width = width
		dialogWin.height = height
		// Keep name unique so Navigator doesn't overwrite an existing dialog.
		dialogWin.name = (new Date()).getSeconds().toString()
		// Assemble window attributes and center on the screen
		dialogWin.left = (screen.width - dialogWin.width) / 2
		dialogWin.top = (screen.height - dialogWin.height) / 2
		var attr = "left=" + dialogWin.left + ",top=" + 
			dialogWin.top + ",scrollbars=yes,resizable=yes,width=" + dialogWin.width + 
			",height=" + dialogWin.height
		
		// Generate the dialog and make sure it has focus.
		dialogWin.win=window.open(dialogWin.url, dialogWin.name, attr)
		dialogWin.win.focus()
	} else {
		dialogWin.win.focus()
	}
}

function OpenFinderAdder(returnFunc, singleSelect, queryKey, documentPath, filterColumn, filterValue)
{
    var url = gWebRoot + '/AsiCommon/Controls/Shared/FinderAdder/FinderAdder.aspx?TemplateType=D&ShowExport=false&hkey=' + gHKey;
    
    if (queryKey != null)
        url += "&QueryKey=" + queryKey;
    else if (documentPath != null)
        url += "&DocumentPath=" + documentPath;
        
    if (filterColumn != null && filterValue != null)
        url += "&FilterColumn=" + filterColumn + "&FilterValue=" + filterValue;
    
    ShowPseudoDialog(url, '', 400, 400, returnFunc);
}

// Invoked by onFocus event handler of EVERY frame,
// return focus to dialog window if it's open.
function checkModal() {
	setTimeout("finishChecking()", 50)
	return true;
}

function finishChecking() {
    // try-catch required to handle exception when dialog's parent is hosted in omnis.
    try {
	    if (dialogWin.win && !dialogWin.win.closed) {
		    dialogWin.win.focus() 
	    }
    }
    catch(e) {
        if(e.message == 'The remote server machine does not exist or is unavailable')
            return;
    }	 
}

function wait()
{
    if (document.getElementById("waitDiv") != null)
    {
        var waitDiv = document.getElementById("waitDiv");
        waitDiv.style.display = "block";
        var divWidth = 277;
        var divHeight = 24;
        waitDiv.style.left = (document.body.offsetWidth - divWidth) / 2;
		waitDiv.style.top = (document.body.offsetHeight - divHeight) / 2;
    }
    
	window.document.body.style.cursor = "wait";
	
	//disable all input type=submit,img,button objects so user doesn't
	//inadvertantly click a button while page is posting
	var inputs = document.getElementsByTagName("input");
	for (var i=0;i<inputs.length;i++)
	{
		var type = inputs[i].getAttribute("type").toLowerCase();
		if ((type == "submit" || type == "image" || type == "button") && (window.event == null || window.event.srcElement != inputs[i]))
			inputs[i].disabled = true;
	}
}
function waitStop()
{
    if (document.getElementById("waitDiv") != null)
    {
        waitDiv.style.display = "none";
    }
    
	window.document.body.style.cursor = "default";
	
	//disable all input type=submit,img,button objects so user doesn't
	//inadvertantly click a button while page is posting
	var inputs = document.getElementsByTagName("input");
	for (var i=0;i<inputs.length;i++)
	{
		var type = inputs[i].getAttribute("type").toLowerCase();
		if ((type == "submit" || type == "image" || type == "button") && window.event.srcElement != inputs[i])
			inputs[i].disabled = false;
	}
}

function dropDownListNavigate(ddl) 
{
  var loc = ddl.options[ddl.selectedIndex].value;
  if(loc != "") {
    if(loc.substr(0, 1) == '~') {
      loc = gWebRoot + loc.substr(1);
    }
    location.href=loc;
  }
}

// opens the BSA object browser as a pop-up allowing the user to select one or more documents or folders for return to the caller
// Parameters:
//  urlParamString - any url params to pass to the browser (see list of available arguments in object browser documentation.  
//     Should be a string like param1=value1&param2=value2 etc.
//  returnFunc -- reference to the function (on the caller) to be called when the dialog is done.  This function will receive
//     the following parameters from the browser:
//        count - the number of keys selected by the user
//        keys - a comma delimited list of the keys selected: HierarchyKeys for folders or DocumentKeys for anything else
//		  type - the DocumentTypeCode of the document selected if there is only one.  Null if more than one
//		  name - the DocumentName of the document selected if there is only one.  Null if more than one
function OpenObjectBrowser(urlParamString, returnFunc)
{
    var paramsArray = urlParamString.split("&");
    
	// we have a few defaults for the pop-up browser that differ from the browser's normal defaults. 
	// Set them unless they are already in the urlParamString
	if (FindParameterInArray("iShowToolbar",paramsArray) == null)
		urlParamString = urlParamString + "&iShowToolbar=0";
	if (FindParameterInArray("iShowSummary",paramsArray) == null)
		urlParamString = urlParamString + "&iShowSummary=0";
	if (FindParameterInArray("iAllowMultiSelect",paramsArray) == null)
		urlParamString = urlParamString + "&iAllowMultiSelect=0";
	if (FindParameterInArray("iDoubleClickAction",paramsArray) == null)
		urlParamString = urlParamString + "&iDoubleClickAction=SelectAndReturnValue";
	if (FindParameterInArray("iOpenMode",paramsArray) == null)
		urlParamString = urlParamString + "&iOpenMode=dialog";
	if (FindParameterInArray("iHeight",paramsArray) == null)
		urlParamString = urlParamString + "&iHeight=490";
	
	CMOpenDialog ('BSA.ObjectBrowser', false, 760, 550, urlParamString, null, returnFunc);
}

// opens the BSA object browser in Save mode
// Parameters:
//  urlParamString - any url params to pass to the browser (see list of available arguments in object browser documentation.  
//     Should be a string like param1=value1&param2=value2 etc.
//  returnFunc -- reference to the function (on the caller) to be called when the dialog is done.  This function will receive
//     the following parameters from the browser:
//        hierarchyKey - the hierarchy key of the folder selected by the user
//        filename - the name of the file to be saved
function OpenObjectSaver(urlParamString, returnFunc)
{
    var paramsArray = urlParamString.split("&");
    
	// we have one default for the saver that differs from the pop-up browser
	// Set it unless it is already in the urlParamString
	if (FindParameterInArray("iShowFilename",paramsArray) == null)
		urlParamString = urlParamString + "&iShowFilename=1";
	
	OpenObjectBrowser(urlParamString, returnFunc);
}

var dirty = true;
//window.onunload = finish;
function finish(buttonId)
{
	if (dirty && window.opener)
	{
//		tryU
		{
		    if(buttonId){
		        var button = window.opener.document.getElementById(buttonId);

		        if (button == null && window.opener.dialogWin.args != null)
		        {
			        button = window.opener.document.getElementById(window.opener.dialogWin.args);
		        }
		    	if (button != null)
			        button.click();
		    }

	        if (button == null && window.opener.RefreshBySubmit)
	            window.opener.RefreshBySubmit();
	        
	        if (window.opener.dialogWin.returnFunc != null)
		        window.opener.dialogWin.returnFunc();

	    }
//	    catch(e)
//	    {
//	        // exception will happen when dialog opened from within Client/Server b/c of 
//	        // security.  this will be a problem.
//	    }
	}
}

