/*
CareCatalyst's common javascript location
*/

ccInitScripts();

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function safeOpenWindow(url)
{
	window.open(url,"mywindow","menubar=1,resizable=1");
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

 function isInt(x) 
 {
   var y=parseInt(x);
   if (isNaN(y))
   {
    return false;
   }
   return x==y && x.toString()==y.toString();
 } 
 
function getDomain()
{
	var location = document.location.href;
	if (location.indexOf("https://") == 0)
		location = location.substring(8, location.length);
	if (location.indexOf("http://") == 0)
		location = location.substring(7, location.length);

	var locationParts = location.split("/");
	var domain = locationParts[0];
	var domainParts = domain.split(".");
	var retval = "";
	if (domainParts.length == 4)
	{
		if (isInt(domainParts[0]) &&
			isInt(domainParts[1]) &&
			isInt(domainParts[2]) &&
			isInt(domainParts[3]) 
			)
		 {
			//it's an ip address
			return null;
		 }
	}
	
	if (domainParts.length > 1)
	{
		retval = domainParts[domainParts.length-2] + "." + domainParts[domainParts.length-1];
	}
	else
	{
		retval = null;
	}
	return retval;
	
}

function setJsTesterCookie()
{
	createCookie("jsTesterCookie", "true", null, getDomain() );
}

function createCookie(name,value,days,domain)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	var cookie = name+"="+value+expires+"; path=/;"
	if (domain != null)
	{
		cookie += "domain="+domain;
	}
	document.cookie =  cookie;
}
function ccInitScripts()
{
	setJsTesterCookie();
}
// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim( value ) 
{
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim( value ) 
{
	return LTrim(RTrim(value));
}

var countdownTime;
var logoutTime; 
var logoutTimer;
var logoutLink = "Users_Logout.aspx";
function setLogoutTimer(_logoutTime, _countdownTime, _logoutLink)
{
	if (_countdownTime)
	{
		countdownTime = _countdownTime;
	}
	if (_logoutTime)
	{
		logoutTime = _logoutTime;
	}
	if (_logoutLink)
	{
		logoutLink = _logoutLink;
	}
	logoutTimer = setTimeout(setCountdownMessageOn, logoutTime * 1000);
	window.onmousemove = resetLogoutTimer;
	document.onkeyup = resetLogoutTimer;
}
function resetLogoutTimer(e)
{
	if (!e) var e = window.event;
	if (logoutTimer)
	{
		clearTimeout(logoutTimer);
		setLogoutTimer(logoutTime, countdownTime);
	}
}
var transparentBGTargetElem;
function setTransparentBGTargetElem(_transparentBGTargetElem)
{
	transparentBGTargetElem = _transparentBGTargetElem;
}
function setTransparentBGOn()
{		
	if(browser == "Internet Explorer" && version <= 6)
	{
		hideSelectBoxes();
	}
	var madeNewDiv = false;
	if (!transparentBGTargetElem)
	{	
	
		transparentBGTargetElem = document.createElement("div");
		transparentBGTargetElem.id = "transparentBackground";
		madeNewDiv = true;
	}
	
	transparentBGTargetElem.className = "SemiTransparentBg";
	transparentBGTargetElem.style.visibility = 'visible';
	transparentBGTargetElem.style.display = "inline";
	transparentBGTargetElem.style.top = "0";
	transparentBGTargetElem.style.left = "0";
	transparentBGTargetElem.style.position = "absolute";
	Element.setOpacity(transparentBGTargetElem, 0.5);

	if (madeNewDiv)
	{
		document.body.appendChild(transparentBGTargetElem);
	}	
	resizeTransparentBG();
	Event.observe(window, "resize", setTransparentBGAndPopWin, false);
	Event.observe(window, "scroll", setTransparentBGAndPopWin, false);
}
function setTransparentBGAndPopWin()
{
	resizeTransparentBG();
	centerPopWin(); 
}
function resizeTransparentBG()
{
	if (transparentBGTargetElem)
	{
		transparentBGTargetElem.style.width = getScrollWidth() + "px";
		transparentBGTargetElem.style.height = getScrollHeight() + "px";
	}
}
	
function centerPopWin()
{
	var tagList = $("PopupWindow");
	if (tagList)
	{
		var width = tagList.offsetWidth;
		var height = tagList.offsetHeight;
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		var theBody = document.documentElement;
		var scTop = parseInt(theBody.scrollTop,10);
		var scLeft = parseInt(theBody.scrollLeft,10);
		var topPos = (scTop + ((fullHeight - height) / 2));
		if (topPos < 0)
		{
			topPos = 0;
		}
		var leftPos = (scLeft + ((fullWidth - width) / 2));
		if (leftPos < 0)
		{
			leftPos = 0;
		}	
		tagList.style.top = topPos + "px";
		tagList.style.left = leftPos + "px";
	}
}

function setTransparentBGOff()
{
	Event.stopObserving(window, "resize", setTransparentBGAndPopWin);
	Event.stopObserving(window, "scroll", setTransparentBGAndPopWin);
	if (transparentBGTargetElem)
	{
		Effect.Fade(transparentBGTargetElem);
		if(browser == "Internet Explorer" && version <= 6)
		{
			displaySelectBoxes();
		}
	}
}
var countdownInt;
var countdownTimer;
var logoutRedirectTimer;
function setCountdownMessageOn()
{
	setTransparentBGOn();
	var messagebox = document.createElement("div");
	messagebox.id = "countdownTimeBox";
	messagebox.style.width = "250px";
	messagebox.style.height = "150px";
	messagebox.style.border = "2px solid black";
	messagebox.style.background= "white";
	messagebox.style.position = "absolute"
	messagebox.style.left = (getViewportWidth() - 250) /2 + "px";
	messagebox.style.top = (getViewportHeight() - 150) /2 + "px";
	messagebox.style.zIndex= 10000;
	messagebox.style.padding = "5px";
	countdownInt = countdownTime;
	messagebox.innerHTML = "<h2 style=\"text-align:center;\">Security Logout</h2><p style=\"text-align:center;\">For your security, you will be logged out in <span id=\"countdownSeconds\" style=\"color:red\">" + countdownInt + "</span> seconds due to inactivity.<br><br> <button id=\"extendTime\" onclick=\"extendTime(); return false;\">Extend My Time</button></p>";
	clearTimeout(logoutTimer);
	window.onmousemove = null;
	document.onkeyup = null;
	document.body.appendChild(messagebox);
	countdownTimer =setTimeout(decrementCountdownTimer, 1000);
	logoutRedirectTimer = setTimeout(logoutUser, countdownTime * 1000);
}
function logoutUser()
{
	location.href = logoutLink;
}
function decrementCountdownTimer()
{
	clearTimeout(countdownTimer);
	countdownInt = countdownInt - 1;
	var countdownSecs = document.getElementById("countdownSeconds");
	if (countdownSecs)
	{
		if (countdownInt >= 0)
		{
			countdownSecs.innerHTML = countdownInt;
			countdownTimer = setTimeout(decrementCountdownTimer, 1000);	
		}
	}
}
function setCountdownMessageOff()
{
	setTransparentBGOff();
	var thebox = document.getElementById("countdownTimeBox");
	if(thebox)
	{
		document.body.removeChild(thebox);
	}
}

function extendTime()
{
	clearTimeout(logoutRedirectTimer);
	clearTimeout(countdownTimer);
	setCountdownMessageOff();
	setLogoutTimer(logoutTime, countdownTime);
	keepAlive(); // defined in the page
}

function getScrollHeight()
{
	var bdyscrlhgt =  document.body.scrollHeight;
	var docscrlhgt = document.documentElement.scrollHeight;
	var docelmthgt = Element.getHeight(document.documentElement);
	var theHeight = bdyscrlhgt;
	if (docscrlhgt > theHeight)
	{
		theHeight = docscrlhgt;
	}
	if (docelmthgt > theHeight)
	{
		theHeight = docelmthgt;
	}
	return theHeight;
}
function getScrollWidth()
{
	var scrlwdth =  document.documentElement.clientWidth;
	if (!scrlwdth)
	{
		scrlwdth = document.body.clientWidth;
	}
	
	return scrlwdth;
}


/**
* Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function hideSelectBoxes() 
{
	var hiddenBoxCount = 0;
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if (document.forms[i].elements[e].style.display != "none")
			{
				if(document.forms[i].elements[e].tagName == "SELECT") 
				{
					if (document.forms[i].elements[e].style.visibility !="hidden")
					{
						document.forms[i].elements[e].style.visibility="hidden";
						document.forms[i].elements[e].setAttribute('autohidden', 'true');
						hiddenBoxCount++;
					}
				}
			}
		}
	}
	return hiddenBoxCount;
}

/**
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function displaySelectBoxes() {
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if(document.forms[i].elements[e].tagName == "SELECT") 
			{
				if ( document.forms[i].elements[e].style.visibility=="hidden" && 
					document.forms[i].elements[e].getAttribute('autohidden') == 'true')
				{
					document.forms[i].elements[e].style.visibility = "visible";	
				}
			}
		}
	}
}
/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 * Gets the full width/height because it's different for most browsers.
 */
function getViewportHeight() {
	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 getViewportWidth() {
	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; 
}

///Toggles on or off an element... uses cool Scriptaculous effects.
function coolToggle(elem)
{
	if (elem )
	{
		if (elem.style.display == "none")
		{
			Effect.Appear(elem);
		}
		else
		{
			Effect.Fade(elem);
		}		
	}
}

//Ian's own javascript progressbar!
function ProgressBar()
{
	this.min;
	this.max;
	this.currentPos;
	this.numSegments;
	this.startColor = "#999999";
	this.finishColor ="#509DE0";
	this.barWidth;
	this.barHeight;
	this.divProgBar;
	
	
	this.setUp = function (_divProgBar, _width, _height, _min, _max, _currentPos, _startColor, _finishColor)
	{
		this.divProgBar = _divProgBar;
		this.min = _min;
		this.max = _max;
		this.currentPos = _min;
		this.divProgBar = _divProgBar;
		this.barWidth = _width;
		this.barHeight = _height;
		this.divProgBar.style.height = this.barHeight + "px";
		this.divProgBar.style.width = this.barWidth + "px";
		if (_currentPos)
		{
			this.currentPos = _currentPos;
		}
		if (_startColor)
		{
			this.startColor = _startColor;
		}
		if (_finishColor)
		{
			this.finishColor = _finishColor;
		}
		var frontDiv = document.createElement('div');
		
		frontDiv.id = "divprogbarfront";
		frontDiv.style.height = this.barHeight + "px";
		frontDiv.style.width = "0px";
		frontDiv.style.backgroundColor =this.finishColor ;
			
		this.divProgBar.style.backgroundColor = this.startColor;
		this.divProgBar.style.overflow = "hidden";
		this.divProgBar.appendChild(frontDiv);

		this.setPosition(this.currentPos);		
	}
	this.setPosition = function (pos)
	{
		if (pos >= this.max)
		{
			pos = this.max;
		}
		else if (pos <= this.min)
		{
			pos = this.min;
		}			
		appearAmount = (pos - this.min)/(this.max - this.min) * this.barWidth ; 
		
		for (i = 0 ; i < this.divProgBar.childNodes.length; i++)
		{
			var div =this.divProgBar.childNodes[i];
			if (div.id=="divprogbarfront")
			{
				div.style.width = appearAmount + "px";			
			}			
		}
		this.currentPos = pos;
	}
}

function resizeFrameToMatchContentSize(frame)
{
    try
    {
        innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
        frame.height = innerDoc.body.scrollHeight + 30;
        frame.width = innerDoc.body.scrollWidth;
    }
    catch(err)
    {
        window.status = err.message;
    }
}

function printFrame(frameName)
{
    window.frames[frameName].focus();
    window.frames[frameName].print();
}

// PROBLEM: TabContainer switches tabs even when form validators fire.
// HACK: Wire up TabContainer.OnClientActiveTabChanged to ActiveTabChanged and TabPanel.OnClientClick to TabClicked below.
// validation will fire and the tab will revert to the previous tab.
var lastActiveTabIndex = 0;
var nextTabIndex = 0;

function ActiveTabChanged(sender, e) {
    if (!Page_IsValid && (lastActiveTabIndex != nextTabIndex)) {
        nextTabIndex = lastActiveTabIndex;
        sender.set_activeTabIndex(lastActiveTabIndex);
    }
}

function TabClicked(sender, e) {
    nextTabIndex = sender._tabIndex;
    lastActiveTabIndex = sender.get_owner().get_activeTabIndex();
    Page_ClientValidate();
}
