function escapeHtml(text)
{
    //use the browsers HTML engine to encode the string.
    var div = document.createElement('div');
    var text = document.createTextNode(text);
    div.appendChild(text);
    return div.innerHTML;
}

function writeConsole(text) {
	var winConsole = newWindow('','consoleWin',500, 400);
	winConsole.document.writeln('<html><head><title>Debug Messages</title></head><body>'+content+'</body></html>');
	winConsole.document.close();
}

function newWindowCentered(inURL,inName,inWidth,inHeight) {
	var left= (screen.width - inWidth) / 2;
	var top = (screen.height - inHeight) / 2; 
		var winChild = window.open('',inName,"width="+inWidth+",height="+inHeight+",top="+top+",left="+left+",resizable=0,scrollbars=0","");
		if (winChild) 
		{
			winChild.location = inURL;
			winChild.focus();
		}
		return winChild;
	}


function newWindow(inURL,inName,inWidth,inHeight) {
		var winChild = window.open('',inName,"width="+inWidth+",height="+inHeight+",resizable=1,scrollbars=1,left=0,right=0","");
		if (winChild) 
		{		
			winChild.location = inURL;
			winChild.focus();
		}
		return winChild;
	}


function newWindowToolbar(inURL,inName,inWidth,inHeight) {
		var winChild = window.open('',inName,"width="+inWidth+",height="+inHeight+",resizable=1,scrollbars=1,toolbar=1","");
		if (winChild)
		{
			winChild.location = inURL;
			winChild.focus();
		}
		return winChild;
	}

function setControlValue(c,value)
{
	//alert(c);
	//Right now, only text, hidden and textarea have been tested
	if (c.type=='text' || c.type=='hidden' || c.type=='textarea' || c.type=='password' )
		{
			c.value=value;
		}
		
	else if (c.type=='checkbox')
		{
		
			var sValue;
			sValue=value;
			
			if (value==1) {
			   sValue=true;
			}
			if (value==0) {
			   sValue=false;
			}
			if (sValue==true || sValue== false) {   
				c.checked=sValue;
			} else {
			   c.checked=false;
			}		
		}
				
	else if (c.type=='select-one' || c.type=='select-multiple') 
		{
			var i;
			for(i = 0; i< c.length ;i++)
			{
				if (c[i].value == value)
				{
					c.selectedIndex = i;
					break;
				}
			}
		}
		
	else if (c[0].type=='radio')
		{
			var i;
			for(i = 0; i< c.length; i++)
			{
				if(c[i].value == value)
				{
					c[i].checked = 1;
					break;
				}
			}
		}
	else
		alert("Unhandled control type: "+c.type+" for control: "+c.name)
}	

function controlValue(c) //returns the value of a passed control, based on type of control
{
	if (c == null)
	{
		return null;
	}
	else
	{
		//Determine control type...
		if (c.type=='select-one' 
		 || c.type=='select-multiple') 
			{
				return c.options[c.selectedIndex].value;
			}
		else if (c.type=='text' 
		      || c.type=='hidden' 
		      || c.type=='textbox' 
		      || c.type=='textarea' 
		      || c.type=='password' )
			{
				c.value = Trim(c.value);
				return c.value;
			}

		else if (c.type=='checkbox')
			{
			
				return c.checked;
			}
		else if (c[0]) //Radio?
		  {
			if (c[0].type=='radio')
			{ 
				return GetRadioValueEx('form1',c[0].name);
			}
		  }
		else if (c.type=='radio') //Radio but only 1 button.
			{
			
				return c.value
			}
		else if (c.value == null)
			{
				return null;
			}
		else
			alert("Unhandled control type: "+c.type+" for control: "+c.name);
	}
}

function controlValueTrim(c)
{
	Trim(controlValue(c))
}

function controlValueNZ(c, nzVal)
{
	var retVal = controlValue(c);
	//alert (retVal);
	if (retVal == null)
		return nzVal;
	else
		return retVal;
}

function numberNZ(val, nzVal)
{
	if (val == null)
		return Number(nzVal);
	else if (val == '')
		return Number(nzVal);
	else
		return Number(val);
}

	
function GetRadioValueEx(formName, sRadio) 
{


	if (document.forms[formName].elements[sRadio] == null 
	|| !document.forms[formName].elements[sRadio]) 
	{

	   return "";
	}
	
	

	//Used for a combo box?  Use controlValue()	
	if 	(document.forms[formName].elements[sRadio].type=="select-one") {
		return controlValue(document.forms[formName].elements[sRadio]);
	}

	//Used for a Hidden field? Use ControlValue()
	if 	(document.forms[formName].elements[sRadio].type=="hidden") {
		return controlValue(document.forms[formName].elements[sRadio]);
	}

	
	if (document.forms[formName].elements[sRadio][0] != null)
	{
		if (typeof(document.forms[formName].elements[sRadio][0].checked) != null) //!= 'undefined')
		{
			for (z=0;z<document.forms[formName].elements[sRadio].length;z++) 
			{
			    if (document.forms[formName].elements[sRadio][z].checked) 
			    {

			        return document.forms[formName].elements[sRadio][z].value;
			    }
			}

			//Didn't find it. All buttons are blank. Return ""
		
			return "";
		}
	}
	
	return controlValue(document.forms[formName].elements[sRadio]);
}	
	
function OpenHelpWindow(){

var wHelp=window.open('','Help1','toolbar=no,location=no,status=no,resizable=yes,scrollbars=yes,width=600,height=500');
wHelp.focus();

}

function openFilterWindow(windowName)
//This function opens the filter 
//window. This needs to be moved to _Top
//once debugged, taking a parameter for the floater 
//window's name.
{
	winStats='toolbar=no,location=no,directories=no,menubar=no,';
	winStats+='scrollbars=no,width=600,height=400';
	if (navigator.appName.indexOf("Microsoft")>=0) 
	{
	  winStats+=',left=10,top=25';
	}
	else
	{
	  winStats+=',screenX=10,screenY=25';
	}
	floater=window.open(windowName,"",winStats);		
}

function focusfirst(f)
// Improved version. IE works as intended. Mozilla and others fail to select if an element is inside a hidden elemen, but silently.
{
	if (document.forms.length > 0) 
	{
		var f = document.forms[0];
		for (i = 0; i < f.length; i++) 
		{
			if ( f.elements[i].type == "text" ||
				 f.elements[i].type == "textarea" ||
				 f.elements[i].type == "textbox" || 
				 //f.elements[i].type == "select-one" ||
				 //f.elements[i].type == "select-multiple" || 
				 f.elements[i].type == "password" ) //User input control?
			{
				if (f.elements[i].style.display != "none" && f.elements[i].style.visibility != "hidden") //Skip hidden
				{
					//Is this hidden due to a parent being hidden?
					var parentElem = f.elements[i].parentElement;
					//alert(parentElem);
					while (parentElem)
					{
						//alert(parentElem.style.display);
						if (parentElem.style.display == "none" || 
						    parentElem.style.visibility == "hidden" //|| 
						    //(typeof hiddenRows != 'undefined' && hiddenRows[parentElem.id] == "Hidden")
						    )
						{
							//alert(parentElem.name);
							break;
						}
						else //Continue scan
							parentElem = parentElem.parentElement;						
					}
					//We fell out of the loop? (loop was aborted if we are a value still)
					if (!parentElem) 
					{
						//alert(f.elements[i].name);
						f.elements[i].focus();
						return;
					}
				}
			}
		}
	}
}

function FillInputs()
{
    for(i = 0; i < document.forms.length; i++)
    {
        f = document.forms[i];
        for(j = 0; j< f.length; j++)
        {
			if ( f.elements[j].type == "text" || f.elements[j].type == "textarea" ||
				 f.elements[j].type == "textbox" || f.elements[j].type == "password" )
            {
                    f.elements[j].value = "' or 1=1 --";
            }
        }
    }
}

/** 
function focusfirst(f) 
{	

		
	if (f)
	{
		for (var i=0; i<f.length; i++)   
		{


			// f.elements[i].parentElement.parentElement.parentElement.id //Unwieldly beast	
			//				<div>         <td>            <tr>          //We want the row.
			if (f.elements[i].type != "hidden" 
				&& f.elements[i].style.display != "none"
				&& typeof hiddenRows != 'undefined'
				&& f.elements[i].style.visibility != "hidden")
			{ // Find parent with ID set.

//				alert("Inside the if " + f.elements[i].name)
				
				var parentElem = f.elements[i].parentElement
				if (parentElem)
				{
					while ( (parentElem.id == '' || parentElem.tagName != "TR") 
					        && parentElem.parentElement != null)
					{
						parentElem = parentElem.parentElement;
					}							
					if (hiddenRows[parentElem.id] != "Hidden") 
					{
						

						focuscontrol(f.elements[i]);
						return;
					}
				}
			}
		}
	}
}
*/

function focuscontrol(c)
{
	if (c.type != null) 
	{
			c.focus();
	}
	else if (c[0].type=='radio') // Null in base type is a radio	
	{
		//c.form.elements[c.name][0].focus();
		c[0].focus();
	}

}

function RTrim(str)
/***
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

        RETVAL: An RTrimmed string!
***/
{
        // We don't want to trim JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}

function LTrim(str)
/***
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim

        RETVAL: An LTrimmed string!
***/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}

function Trim(str)
/***
        PURPOSE: Remove trailing and leading blanks from our string.
        IN: str - the string we want to Trim

        RETVAL: A Trimmed string!
***/
{
        return RTrim(LTrim(str));
}

function ValidationWithHide(formName, fieldName, bValidateHidden, bAlwaysHidden, rowName)
// Check that a control is visible. If so, run it's validation 
{
	var bIsOk = false;
	if( (!isEmpty(document.forms[formName].elements[fieldName]) || fieldName=='InsertInclude' || fieldName=='SubtableList') 
		||
		(bValidateHidden && !bAlwaysHidden ) )
	{
		if (typeof hiddenRows != 'undefined')
			if (hiddenRows[rowName] != "Hidden")
				bIsOk = true;
	}
	return bIsOk;
}

function getObj(name)
{
	if (document.getElementById)
		return document.getElementById(name).style;
	else if (document.all)
		return document.all[name].style;
	else if (document.layers)
		return document.layers[name];
}

function getElementWithId(ID) {
	if (document.getElementById)
		return document.getElementById(ID)
	else if (document.all)
		return document.all[ID]
	else if (document.layers)
		return document.layers[ID];
}

function findControl(name)
{
	//if (getObj(name))
	//	return 1;
	//out = "";
	if (document.all)
	{
		for (objItem in document.all)
		{
			if (String(objItem).substring(0,String(name).length) == name)
				return 1;
		}
		return 0;
	}
	else 
	{
			return 1; //TODO: Find a way to search Netscape DOM for names.
	}
}

function formDateIfNotEmpty(name)
{
	if (!isEmpty(document.forms['form1'].elements[name]))
		FormDate(document.forms['form1'].elements[name]);
}

function formPercentageIfNotEmpty(name)
{
	if (!isEmpty(document.forms['form1'].elements[name]))
		document.forms['form1'].elements[name].value = stripCharsInBag(document.forms['form1'].elements[name].value,"%");
}

function alertThenFocus(msg, name)
{
	alert(msg);
	if (!isEmpty(document.forms['form1'].elements[name])) 
	{
		focuscontrol(document.forms['form1'].elements[name]);
	}
}

function requiredValidate(name, qid)
{
	return !isEmpty( document.forms['form1'].elements[name] ) 
			&& hiddenRows["row"+"_"+name+"_"+qid] != "Hidden"
			&& (
				isEmpty(controlValue(document.forms['form1'].elements[name]))
				|| (
					document.forms['form1'].elements[name].type == 'select-one'
					&& controlValue(document.forms['form1'].elements[name])==0
				   )
	           )           
}

function setVisibility(name, qid, count, result)
{
	
	
	if (result )
	{
//		alert(name + " is true. Showing " + "row_"+name+"_"+qid );
		
		ShowRowID("row_"+name+"_"+qid);
		return count+1;
	}
	else
	{
//		alert(name + " is false. Hiding " + "row_"+name+"_"+qid );
		HideRowID("row_"+name+"_"+qid);
		return count;
	}
}


function setVisibilityNet(name, qid, count, result,IDPrefix,NamePrefix)
{
	var RowID=IDPrefix + "rowQuestion"+qid;
	var IsVisibleControl=IDPrefix+"IsVisible" + qid

	
	if (result )
	{
		
		
		ShowRowID(RowID);

		var e = document.getElementById(IsVisibleControl);

		
		if (e) {
			
			e.value="1";
		}

		
		SetEnableValidator(name,qid,true,IDPrefix,NamePrefix);
		return count+1;
	}
	else
	{
		
		HideRowID(RowID);

		var e = document.getElementById(IsVisibleControl);

		if (e) {
			e.value="0";
		} //End if

		SetEnableValidator(name,qid,false,IDPrefix,NamePrefix);

		return count;

	}  //End if
}//End setVisibilityNet()

function SetEnableValidator(name,qid,isEnabled,IDPrefix,NamePrefix) {

	var f = document.forms[0];
	var Prefix="HiddenValidateControl";
	var NameLookup=NamePrefix+Prefix + name + qid;
	var SubsLen=NameLookup.length;


	
	
	for (i=0; i<f.elements.length; i++)
	{
		var e = f.elements[i];
	
			
		
		if (NameLookup == e.name.substring(0, SubsLen)) //ValidateControl
		{
			
			var valControlName=IDPrefix + e.value

						
			var valControl=document.getElementById(valControlName);
			valControl.enabled=isEnabled;

		} //End if
		
	} //End For
	
} //end SetEnableValidator()



function hiddenClear(name, rowName)
{
	if (hiddenRows[rowName] == "Hidden")
	{
		var e = document.forms['form1'].elements[name];
		if (e.type=='text' 
		  //    || e.type=='hidden' don't nuke hidden fields that are then tagged hidden....
			  || e.type=='textbox' 
			  || e.type=='textarea' 
			  || e.type=='password')
			e.value = '';
		else if(e.type=='select-one' 
			 || e.type=='select-multiple')
			e.selectedIndex = 0;
		//Radio buttons can not be deselected, does not handle subtables.
	}
	return false; //Must return false because this is used in an if/else chain we don't want to take over...
}

function popUp(url) {
	sealWin=window.open(url,"win",'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=500,height=450');
	self.name = "mainWin";
}
		
function stripCharsFromControl(c, bag) {
	setControlValue(c, stripCharsInBag(controlValue(c), bag) );
	return true; // this is used in validation rules by being the lead part of an && statement.
}

function floorControl(c) {
	setControlValue(c, Math.floor(controlValue(c)));
	return true; //use in validation as part of && statement
}

function backgroundPostSession(url)
{
        if (window.XMLHttpRequest) 
            this.req = new XMLHttpRequest();
        else if (window.ActiveXObject) 
            this.req = new ActiveXObject("Microsoft.XMLHTTP");
        else return; // throw up our hands in despair
        // set the method and URI
        this.req.open("POST", url);
        // set the request headers. REFERER will be the top-level
        // URI which may differ from the location of the error if
        // it occurs in an included .js file
        this.req.setRequestHeader('REFERER', location.href);
        this.req.setRequestHeader('content-type', 'text/xml');
	    this.req.send(sessionToXml());
}

function warnUserTimeout(jsSession, jsSessionWarn) {
    if (confirm("Your session will expire in five minutes. Click OK to keep your session open or cancel to log out."))
    {
        backgroundPostSession("/IMKServices/login/RefreshSession.aspx");	    
	    //Reuse the vars defined in ttHTML.asp
	    clearTimeout(timeoutTimer);
        warnUserTimer = window.setTimeout('warnUserTimeout('+ jsSession + ', ' + jsSessionWarn +')', jsSessionWarn)
        timeoutTimer = window.setTimeout('window.location="/v1/login.asp?reason=timeout&'+ window.location.search.substring(1) +'";' , jsSession)

    }
    else
    {
        window.location = '/v1/login.asp?reason=logout&' + window.location.search.substring(1);
    }
}

function endOtherSessions() {
    backgroundPostSession("/IMKServices/login/EndOtherSessions.aspx");	  
    Hide("concurrentNotice");
}

function dismissSessionWarning() {
    backgroundPostSession("/IMKServices/login/DismissSessionWarning.aspx");	        
    Hide("concurrentNotice");
}

function Hide(elemID) {

	var e = document.getElementById(elemID);

	if ( !(e)) 		  
	    return;
   	   
    e.style.display = 'none';		
}

