//
//  misc.js
//
function IsInternetExplorer()
{
	return(/MSIE [56789]/.test(navigator.userAgent) && (navigator.platform == "Win32"))
}

function NoOp()
{
	return true;
}

function StripQueryString(strURL)
{
	var A = strURL.split("?")
	return(A[0]);
}

function NameOnly(strFilename)
//
//  Returns the base filename (no path) of the given filename or URL.
//
{
	var strReturn = new String(strFilename)
	//
	//  Remove leading path info
	//
	var A = strReturn.split("/")
	var n = A.length
	if (n > 0)
		strReturn = A[n-1]

	return(StripQueryString(strReturn));
}

function SetStatus(strMsg)
//
//  Sets the status bar message
//
{
	status = strMsg;
	return true;
}

function ClearStatus()
//
//  Clears the status bar message
//
{
	return(SetStatus(''));
}

function GetWebcatsHeaderFrame()
{
	return(window.top.topheaderFrame);
}

function WebcatsSetModified(bModified)
{
	var objWebcats = GetWebcatsHeaderFrame()
	if (typeof(objWebcats) == "undefined")
		return;
		
	var doc = objWebcats.document;
	if (typeof(doc) == "undefined")
		return;

	doc.m_bWebcatsModified = bModified;
	var objRecentVisits = objWebcats.document.getElementsByName("RecentVisits")[0];	
	objRecentVisits.disabled = bModified;
}
  
function WebcatsIsModified()
{
	return(GetWebcatsHeaderFrame().document.m_bWebcatsModified);
}

var FUNCTION_EDIT = 2

function NewLocation(objLocation, strDescription)
//
//  Notifies the top header frame and lefthand menu frame of changes
//  the URL (location) represented in the main frame.
//
//  (The header and menu frames are only interested in changes to the 
//  occupant of the main frame; in certain circumstances it is tough to
//  ensure that sub-sub-frames aren't reporting in, so we're ignoring them
//  here.)
//
{
	// alert("NewLocation(...,\"" + strDescription + "\")");
	var strURL = typeof(objLocation) == "object" ? objLocation.toString() : objLocation;
	
	if (typeof(window.top.webcatsFrame) != "object") // make sure frame is loaded
		return(false);
		
	WebcatsSetModified(false); // safety
		
	if (typeof(window.top.webcatsFrame.mainFrame) != "object") // make sure frame is loaded
		return(false);
		
	if (window.top.webcatsFrame.mainFrame != self)  // reject subframe notifications
		return(false);
			
	if (NameOnly(window.top.webcatsFrame.leftFrame.location) == "menu.asp")
	{
		if (typeof window.top.webcatsFrame.leftFrame.NewLocation == "function")
			window.top.webcatsFrame.leftFrame.NewLocation(strURL, strDescription);
	}
	if (NameOnly(window.top.topheaderFrame.location) == "webcatsheader.asp")
	{
		if (typeof window.top.topheaderFrame.NewLocation == "function")
			window.top.topheaderFrame.NewLocation(strURL, strDescription);
	}
	
	return(true);
}

function NewLocationEdit(objLocation, strIdField, nID, strDescEdit, strDescNew)
//
//  For use by editable views.  Should only add new location to
//  recent visits if this is an edit of an existing record, not
//  if starting a new record (user should be selecting appropriate
//  menu option to start new record)
//
//  [stant, 12/10/01] Changed my mind -- don't want Editable views in the
//  history at all (they're only one click away from a read-only view that's
//  most certainly going to get into the history).
//
{
	var strURL = typeof(objLocation) == "object" ? objLocation.toString() : objLocation;
	
	var strLocation, strDescription
	if (nID > 0)  // existing record
	{
		strLocation = StripQueryString(strURL) + "?Function=" + FUNCTION_EDIT + "&" +
			strIdField + "=" + nID;
		strDescription = "-- Editing " + strDescEdit + " --"; // don't add to recent visits
	}
	else // new record
	{
		strLocation = strURL;
		strDescription = "-- New " + strDescNew + " --"; // don't add to recent visits
	}
	return(NewLocation(strLocation, strDescription));
}

function NewLocationView(objLocation, strIdField, nID, strDescView)
//
//  For use by read-only detail view.  Should only new location but
//  only with FUNCTION_VIEW specified.  We don't want to bookmark
//  a FUNCTION_UPDATE or something else that hit this page.
//
{
	//alert("NewLocationView(...,\"" + strIdField + "\"," + nID + ",\"" + strDescView + "\")");
	var strURL = (typeof(objLocation) == "object") ? objLocation.toString() : objLocation;
	var strLocation = StripQueryString(strURL) + "?" + strIdField + "=" + nID;
	var strDescription = strDescView;
	return(NewLocation(strLocation, strDescription));
}

function ChangingLocation()
{
	NewLocation("--", "-- (loading new page) --")
}

function ClearLocations()
{
	if (typeof(window.top.topheaderFrame) == "undefined")
		return;
		
	if (window.top.topheaderFrame.location.pathname != "/webcatsheader.asp")
		return;
	
	if (typeof(window.top.topheaderFrame.ClearLocations) != "function")
		return;
		
	return(window.top.topheaderFrame.ClearLocations());
}

function SetLinks(strPrefix, strHref, arrAttrs)
//
//  Sets the "static" links of a page upon download, in order to save space
//  in the download.
//
//  strPrefix (I) -- ID prefix to apply changes to
//
//  strHref (I) -- if non-blank, the href to assign to the anchors; the href will
//  have the ID data following the prefix appended to it.
//
//  strClassName (I) -- if non-blank, the class to assign to the anchors
//
//  strTitle (I) -- if non-blank, the title to assign to the anchors
//
//  NOTE: Should be called from document.onload().
{
	var objAnchors = document.getElementsByTagName("a");
	var nAnchors = objAnchors.length;
	
	var nAttrs = arrAttrs.length;
	var cbPrefix = strPrefix.length;
	var cbHref = strHref.length;

	var funcOnMouseOver = null;
	var funcOnMouseOut = null;
	for(var i = 0; i < nAttrs; i++)
	{
		if (arrAttrs[i][0] == "HelpText")
		{
			funcOnMouseOver = new Function("status='" + arrAttrs[i][1] + "'; return true;");
			funcOnMouseOut  = new Function("status=''; return true;");
			break;
		}
	}
	
	for(i = 0; i < nAnchors; i++)
	{
		var Fld = objAnchors[i];
		with(Fld)
		{
			if (id.substr(0, cbPrefix) != strPrefix)
				continue; // don't apply changes
				
			if (cbHref > 0)
				href = strHref + id.substr(cbPrefix);
				
			for(var j = 0; j < nAttrs; j++)
			{
				switch(arrAttrs[j][0])
				{
				case "HelpText":
					title = arrAttrs[j][1];
					onmouseover = funcOnMouseOver;
					onmouseout = funcOnMouseOut;
					break;
				case "className":
					className = arrAttrs[j][1];
					break;
				case "target":
					target = arrAttrs[j][1];
					break;
				case "title":
					title = arrAttrs[j][1];
					break;
				case "onclick":
					onclick = arrAttrs[j][1];
					break;
				case "onmouseover":
					onmouseover = arrAttrs[j][1];
					break;
				case "onmouseout":
					onmouseover = arrAttrs[j][1];
					break;
				}
			}
		}
	}
}

function SetAllLinks()
//
//  Makes a single pass through the document anchors, setting additional properties.
//
{
	//alert("SetAllLinks()");
	var arrAttrSets = [
		["CF_", ["href", "conferencedetail.asp?ID="],       ["HelpText", "Open Conference"],         ["target", "mainFrame"], ["className", ""]],
		["CS_", ["href", "sessiondetail.asp?ID="],          ["HelpText", "Open Counseling Session"], ["target", "mainFrame"], ["className", ""]],
		["AW_", ["href", "awarddetail.asp?ID="],            ["HelpText", "Open Award"],              ["target", "mainFrame"], ["className", ""]],
		["IN_", ["href", "investmentdetail.asp?ID="],       ["HelpText", "Open Investment"],         ["target", "mainFrame"], ["className", ""]], 
		["MI_", ["href", "milestonedetail.asp?ID="],        ["HelpText", "Open Milestone"],          ["target", "mainFrame"], ["className", ""]],
		["CL_", ["href", "clientframes.asp?CLIENT_ID="],    ["HelpText", "Open Client"],             ["target", "mainFrame"], ["className", ""]],
		["CT_", ["href", "centerdetail.asp?CENTER_ID="],    ["HelpText", "Open Center"],             ["target", "mainFrame"], ["className", ""]],
		["CN_", ["href", "counselorframes.asp?COUNSEL_ID="],["HelpText", "Open Counselor"],          ["target", "mainFrame"], ["className", ""]],
		["LI_", ["href", "listdetail.asp?LIST_ID="],        ["HelpText", "Open List"],               ["target", "mainFrame"], ["className", ""]],
		["IL_", ["href", "individualframes.asp?INDIV_ID="], ["HelpText", "Open Contact"],			 ["target", "mainFrame"], ["className", ""]],
		["IQ_", ["href", "inquirydetail.asp?ID="],          ["HelpText", "Open Inquiry"],            ["target", "mainFrame"], ["className", ""]],
		["CO_", ["href", "clientframes.asp?COMPANY_ID="],   ["HelpText", "Open Company"],            ["target", "mainFrame"], ["className", ""]],
		["NR_", ["href", "narrativedetail.asp?ID="],        ["HelpText", "Open Narrative"],          ["target", "mainFrame"], ["className", ""]],
		["SR_", ["href", "SurveyFrames.asp?ID="],        ["HelpText", "Open Survey Response"],          ["target", "mainFrame"], ["className", ""]],
		["CR_", ["href", "CounselingRequestDetail.asp?COUNSREQ_ID="],["HelpText", "Open Counseling Request"], ["target", "mainFrame"], ["className", ""]],
		["OR_", ["href", "ConferenceRequestDetail.asp?CONFREQ_ID="], ["HelpText", "Open Conference Request"], ["target", "mainFrame"], ["className", ""]],
		["AT_", ["href", "clientdetail_getattachment.asp?DOC_ID="], ["HelpText", "Open Client File Attachment"], ["target", "_blank"], ["className", ""]]
		
	];
	var objAnchors = document.getElementsByTagName("a");
	var nAnchors = objAnchors.length;
	var nAttrSets = arrAttrSets.length;

	var funcOnMouseOver = [ null, null, null, null, null, null, null, null]; 
	var funcOnMouseOut = [ null, null, null, null, null, null, null, null];
	for(var i = 0; i < nAttrSets; i++)
	{
		var arrAttrs = arrAttrSets[i];
		for(var j = 0; j < arrAttrs.length; j++)
		{
			if (arrAttrs[j][0] == "HelpText")
			{
				funcOnMouseOver[i] = new Function("status='" + arrAttrs[j][1] + "'; return true;");
				funcOnMouseOut[i]  = new Function("status=''; return true;");
				break;
			}
		}
	}

	for(i = 0; i < nAnchors; i++)
	{
		var Fld = objAnchors[i];
		with(Fld)
		{
			var strPrefix = id.substr(0, 3);
			for(nSet = 0; nSet < nAttrSets; nSet++)
			{
				if  (strPrefix == arrAttrSets[nSet][0])
				{
					var arrAttrs = arrAttrSets[nSet];
					var nAttrs = arrAttrs.length;
						
					for(var j = 1; j < nAttrs; j++)
					{
						switch(arrAttrs[j][0])
						{
						case "href":
							//alert("ID=" + id + ", href=" + arrAttrs[j][1] + id.substr(3));
							href = arrAttrs[j][1] + id.substr(3);
							break;
						case "HelpText":
							title = arrAttrs[j][1];
							onmouseover = funcOnMouseOver[nSet];
							onmouseout = funcOnMouseOut[nSet];
							break;
						case "target":
							target = arrAttrs[j][1];
							break;
						case "className":
							className = arrAttrs[j][1];
							break;
						case "title":
							title = arrAttrs[j][1];
							break;
						case "onclick":
							onclick = arrAttrs[j][1];
							break;
						case "onmouseover":
							onmouseover = arrAttrs[j][1];
							break;
						case "onmouseout":
							onmouseover = arrAttrs[j][1];
							break;
						}
					}
				}
			}
		}
	}
}

function SetMailLinks(strPrefix, arrAttrs)
//
//
//  NOTE: Should be called from document.onload().
{
	var objAnchors = document.getElementsByTagName("a");
	var nAnchors = objAnchors.length;
	
	var nAttrs = (arrAttrs == null) ? 0 : arrAttrs.length;
	var cbPrefix = strPrefix.length;
	
	for(i = 0; i < nAnchors; i++)
	{
		var Fld = objAnchors[i];
		with(Fld)
		{
			if (id.substr(0, cbPrefix) != strPrefix)
				continue; // don't apply changes
			
			var strEmail = id.substr(cbPrefix);
			href = "mailto:" + strEmail;
			innerHTML = (strEmail.length > 30) ? strEmail.substr(0, 27) + "..." : strEmail;
			title = "Send e-mail to " + strEmail;
			onmouseover = new Function("status='" + title.replace(/'/g, "\\'") + "'; return true;");
			onmouseout = new Function("status=''; return true;");	
				
			for(var j = 0; j < nAttrs; j++)
			{
				switch(arrAttrs[j][0])
				{
				case "className":
					className = arrAttrs[j][1];
					break;
				case "title":
					title = arrAttrs[j][1];
					break;					
				case "target":
					target = arrAttrs[j][1];
					break;
				case "onclick":
					onclick = arrAttrs[j][1];
					break;
				case "onmouseover":
					onmouseover = arrAttrs[j][1];
					break;
				case "onmouseout":
					onmouseover = arrAttrs[j][1];
					break;
				}
			}
		}
	}
}

function absoluteTop(objElement)
{
	var objEl = objElement;
	var nTop = parseInt(objEl.offsetTop);
	while(objEl.offsetParent != null)
	{
		objEl = objEl.offsetParent;
		nTop += objEl.offsetTop;
	}
	nTop += objElement.document.parentWindow.screenTop;
	return(nTop);
}

function absoluteLeft(objElement)
{
	var objEl = objElement;
	var nLeft = parseInt(objEl.offsetLeft);
	while(objEl.offsetParent != null)
	{
		objEl = objEl.offsetParent;
		nLeft += objEl.offsetLeft;
	}
	nLeft += objElement.document.parentWindow.screenLeft;
	return(nLeft);
}

function CleanUpTemps(strTemps)
{
	var strURL = "cleanup.asp?" + strTemps;
	window.open(strURL, "tempFrame", "height=1;width=1;left=1;screenX=1;top=1;screenY=1;alwaysLowered=yes");
}

function ConfirmPage(strMsg, strURL)
{
	if (confirm(strMsg))
		window.open(strURL, "mainFrame");
}

function rand(max_num)
{
	//necessary because the Math Objects random method is next to useless.
	var now = new Date();
	var num = (now.getTime()) % (max_num - 1)
	var num = num + 1;
	return num;
}

function ReSort(strColumn, bDesc, strCurSort)
{
	//alert("ReSort(\"" + strColumn + "\", \"" + strBaseURL + "\", " + bDesc + ", \"" + strCurSort + "\")");
	if (strColumn == strCurSort)
		bDesc = !bDesc;
	else
	{
		switch(strColumn)
		{
		case "DATE":
		case "START_DATE":
		case "isNull(START_DATE, DATE)":
		case "HOURS":
		case "AddlField":
		case "NbrMembers":
		case "COUNSREQ_ID":
		case "CONFREQ_ID":
			bDesc = true;
			break;
		default:
			bDesc = false;
		}
	}
	
	document.sortForm.DESC.value = bDesc ? 1 : 0;
	document.sortForm.SortCol.value = strColumn;	
	document.sortForm.submit();
}

function KeepSessionAlive(bKeepAlive)
{
	var wndFrame1 = window.top.frames[1];
	if (typeof(wndFrame1) == "undefined") // called from a subwindow?!
		return;
	
	var FrameSet = wndFrame1.document.getElementById("leftFrameset");
	var objForm = document.KeepSessionAlive;
	var bFormExists = (typeof(objForm) == "undefined") ? false : true;
	
	if (bKeepAlive) // we're in an edit-form
	{
		//
		//  Expand the frame to display time remaining
		//
		FrameSet.rows = "*,60,1";
	}
	else            // we're no longer in an edit-form
	{
		//
		//  Shrink the frame to hide and give the space back to the vertical menu
		//
		FrameSet.rows = "*,1,1";
		//
		//  Change the keep-alive's form target so that content-refreshes cease.
		//
		if (bFormExists)
			objForm.action = "KeepSessionAlive.asp?TimeRemaining=-10000";
	}
	if (bFormExists)
		objForm.submit();
}

function FormattedTag(strMask, nNbr)
{

/*
  JavaScript version of function found in lib.asp 

  Shared by Conferences and Clients for formatting value for CONFERENCE and CLIENT
  fields respectively.

  Example: FormattedTag("CL###AB", 2) should return "CL002AB"

  strMask (I) -- format mask that contains one sequences of #s to be replaced with
  a zero-padded numeric value.

  nNbr (I) -- number to place in the #-sequence in the mask.
*/

	var strPrefix = "";
	var strSuffix = "";
	var nDigits = 0
	var nPos = strMask.indexOf('#');
							
	if (nPos > 0) 
		strPrefix = strMask.substr(0, nPos);
		
	for (var i=0; i < strMask.length; i++)
	{
		if (strMask.substr(nPos, nPos + 1).indexOf('#') > -1)
		{
			nDigits++;
			nPos++;
		}
	}
	
	if (nPos <= strMask.length)
		strSuffix = strMask.substr(nPos, strMask.length)
	
	var strZeroes = "";
	for (i=0; i < nDigits - nNbr.toString().length; i++)
		strZeroes += '0';

	return(strPrefix + strZeroes + nNbr.toString() + strSuffix);
}

function DateDiff( start, end, interval, rounding ) 
{
	var iOut = 0;

	// Create 2 error messages, 1 for each argument. 
	var startMsg = "Check the Start Date and End Date\n"
	startMsg += "must be a valid date format.\n\n"
	startMsg += "Please try again." ;

	var intervalMsg = "Sorry the dateDiff function only accepts\n"
	intervalMsg += "d, h, m OR s intervals.\n\n"
	intervalMsg += "Please try again." ;

	var bufferA = Date.parse( start ) ;
	var bufferB = Date.parse( end ) ;

	// check that the start parameter is a valid Date. 
	if ( isNaN (bufferA) || isNaN (bufferB) ) 
	{
		alert(startMsg) ;
		return null ;
	}

	// check that an interval parameter was not numeric. 
	if ( interval.charAt == 'undefined' ) 
	{
		// the user specified an incorrect interval, handle the error. 
		alert(intervalMsg) ;
		return null ;
	}

	var number = bufferB-bufferA ;

	// what kind of add to do? 
	switch (interval.charAt(0))
	{
		case 'd': case 'D': 
			iOut = parseInt(number / 86400000);
			if(rounding)
				iOut += parseInt((number % 86400000)/43200001);
			break;
		case 'h': case 'H':
			iOut = parseInt(number / 3600000 );
			if(rounding)
				iOut += parseInt((number % 3600000)/1800001);
			break;
		case 'm': case 'M':
			iOut = parseInt(number / 60000 );
			if(rounding)
				iOut += parseInt((number % 60000)/30001);
			break;
		case 's': case 'S':
			iOut = parseInt(number / 1000 );
			if(rounding)
				iOut += parseInt((number % 1000)/501);
			break;
	    default:
		/*
		/ If we get to here then the interval parameter didn't meet the d,h,m,s criteria.  Handle
		/ the error.
		*/
		alert(intervalMsg) ;
		return null;
	}

	return iOut;
}

function OpenDuplicateCheck(strQueryString, strNameArg, strExtraFeatures)
{
	var strName = (arguments.length < 2) ? "DuplicateCheck" : strNameArg;
	
	var strFeatures = "height=400, width=600, scrollbars=yes, resizable=yes";
	if (arguments.length > 2)
		strFeatures += (", " + strExtraFeatures);
		
	var strURL= "DuplicateCheck.asp?" + strQueryString;
	return(window.open(strURL, strName, strFeatures));
}
