//Common functions for the entire site
/*----------------------------------------------+
 | Parts of this page are from the old ION      |
 | parts are new and some are collected from    |
 | other talented developers that we have tried |
 | to give credit where credit was due.         |
 +---------------------------------------------*/
//General variable init area
var strUserAgent = navigator.userAgent.toLowerCase(); 
var isIE = strUserAgent.indexOf("msie") > -1; 
var isNS6 = strUserAgent.indexOf("netscape6") > -1; 
var isNS4 = !isIE && !isNS6  && parseFloat(navigator.appVersion) < 5; 
var reValidChars = /\d/;

var w3c=(document.getElementById)? true: false;
var ie5;
ie5 = (w3c && document.all)? true : false;
var ns6=(w3c && (navigator.appName=="Netscape"))? true: false;
var mx=0; //Mouse x location
var my=0; //Mouse y location
var currIDb=null;

///This selects a rad tab control tab by the index of the tab.
//  pTabStrip can be passed in using: window["<%= <yourtabstripobjectid>.ClientID %>"];
function SelectTabByIndex(pTabStrip, pIdx)
{
  try
  {    
    if (pTabStrip.AllTabs[pIdx].Enabled) pTabStrip.AllTabs[pIdx].Select();
  }
  catch (e)
  {
    alert("An error occured selecting the tab (" + pIdx + "): " + e.message);
  }
  return false;      
}
///This selects a rad tab control tab by the text of the tab.
//  pTabStrip can be passed in using: window["<%= <yourtabstripobjectid>.ClientID %>"];
function SelectTabByText(pTabStrip, pTabText)
{
  try
  {
    var tabstrip = pTabStrip;
    for(i=0;i<tabstrip.AllTabs.length;i++)
    {
      //alert(tabstrip.AllTabs[i].Text);
      if (tabstrip.AllTabs[i].Text == pTabText)
      {
        if (tabstrip.AllTabs[pIdx].Enabled) tabstrip.AllTabs[i].Select();
        break;
      }
    }
  }
  catch (e)
  {
    alert("An error occured selecting the tab ('" + pTabText + "'):" + e.message);
  }
  return false;      
}

/*
Purpose: To control the pop-up window.
Parameters: H,W, FeatureList
Note: FeatureList will contain a string of control parameters separated by comma with
	  no space in between. The first parameter is used to control the location of 
	  the window and can be one of the followings:
			center	: center of the screen
			uleft	: upper left of the screen
			uright	: upper right of the screen
			lleft	: lower left of the screen
			lright	: lower right of the screen
			max		: maximize the window.
	  The rest of the parameters is for window control and optional. By default, all the 
	  window features are turned off. If they are passed to this function, the specific 
	  features will be turned on. They can be a combination of the followings:
			dir		: directories bar
			loc		: location (address bar)
			menu	: menu bar (contains the file control tab)
			scroll	: scrollbar
			status	: status bar
			tool	: tool bar
	  Ex. SetFeature(500,600,"center,loc,menu,scroll")	
*/
function SetFeatureList(h,w,slist){
	/*	by default, everything feature is off
	height,width,menubar,toolbar,resizable,top,left,location,scrollbars,status,directories
	H,W,(center, uleft, uright, lleft, lright, max),menu,tool,loc,scroll,status,dir
	*/
	var sCompare;
	var sWinFea = "";
	var iTop = "";
	var iLeft = "";
	if (slist){
		var sAryFea = slist.split(",")
		var spostype = sAryFea[0];
		var iFea = sAryFea.length;
		//-----set the pop-up window location-----
		switch (spostype){	
			case "center":	//Center position
				iTop = eval(screen.availHeight/2 - h/2) + ""; 
				iLeft = eval(screen.availWidth/2 - w/2) + "";
				break;
			case "uleft":	//upper left position
				iTop = "0"; 
				iLeft = "0";				
				break;
			case "uright":	//upper right position
				iTop = "0"; 
				iLeft = eval(screen.availWidth  - w) + "";				
				break;
			case "lleft":	//lower left position
				iTop = eval(screen.availHeight - h) + ""; 
				iLeft = "0";				
				break;
			case "lright":	//lower right position
				iTop = eval(screen.availHeight - h) + ""; 
				iLeft = eval(screen.availWidth - w) + "";				
				break;
			case "max":	//maximize openning window
				iTop = "0"; 
				iLeft = "0";
				h = screen.availHeight;
				w = screen.availWidth;
				break;	
		}//end switch
			
		//-----set the other window feature-----
		if 	(iFea>1){	
			for (var i=1; i<iFea; i++){
				sCompare = sAryFea[i];
				switch (sCompare){
					case "dir":
						sWinFea = sWinFea +"directories=1,";
						break;
					case "menu":
						sWinFea = sWinFea +"menubar=1,";
						break;
					case "loc":
						sWinFea = sWinFea +"location=1,";
						break;
					case "resize":
						sWinFea = sWinFea +"resizable=1,";
						break;
					case "scroll":
						sWinFea = sWinFea +"scrollbars=1,";
						break;
					case "status":
						sWinFea = sWinFea +"status=1,";
						break;
					case "tool":
						sWinFea = sWinFea +"toolbar=1,";
						break;		
				}//end switch
			}//end for
		}//end if
	}//end if
		
var sFeature = 'height=' + h + ',width=' + w + ',left=' + iLeft + ',top=' + iTop + ',' + sWinFea;
return sFeature;
}//end SetFeatureList

//Purpose: To open a new help window.
//Author: Kelphen Kuok
function popuphelp()
 {	
	//added by Russell Corona 7/24/00
	var currentPage = location.pathname;
	var currentHost = location.hostname;

	var sFeature = SetFeatureList("350","500","uleft,noresize,noscroll");
	window.open ('../resources/help.aspx?ref=' + currentPage + '&pth=' + currentHost  ,'help',sFeature);
 }


//Purpose: To destroy a window object if it already exists.
//Author: Kelphen Kuok
function CheckWinObj(oWin){
	if (oWin != null){	//check if window object still exists
		if (!oWin.closed){	//checked if window is not still open
			oWin.close();
			oWin = null;
		}//end if
	}//end if 
}//end CheckWinObj

function IsEmptyStr(StrIn){
//	alert("Inside IsEmptyStr-" + StrIn + "|");
	var blnOK = true;
	var strChar;
	var strTemp = "" + StrIn;
		
	for (var c=0;((c<strTemp.length)&&(blnOK));c++){
		strChar = strTemp.charAt(c);
		//if (strTemp.charCodeAt(c) != 160)	//check for space
		//	blnOK = false;
	//	if ((strChar != " ") || (strTemp.charCodeAt(c) != 160))	//check for space
		
		if ((strChar == " ") || (strTemp.charCodeAt(c) == 160))	//check for space
			var t = 3; //do nothing
		else{
			blnOK = false;
			break;
		}
	}//end for
	return blnOK;
}//end IsEmptyStr	

//Replaces the actual with newvalue in entry
function replaceChars(entry,actual,newvalue) 
{
  out = actual; // replace this
  add = newvalue; // with this
  temp = "" + entry; // temporary holder

  while (temp.indexOf(out)>-1) 
  {
    pos= temp.indexOf(out);
    temp = "" + (temp.substring(0, pos) + add + 
    temp.substring((pos + out.length), temp.length));
  }
  return temp;
}

//Format a number in the form of percent
function formatPercent(myValue){
	if (isFinite(myValue))
		retValue = Format2DecPlace(myValue * 100)  + "%";
	else
		retValue = "0.00%";
	
	return retValue;
}//End function

//Formats the value in a text box in the required formats eg. Currency
function numFormat(elem, lead, sep)
{
  if(elem.value)
  {
	  if (elem.value == '') return true;
  	
	  var value = parseInt(cleanNumber(elem.value), 10);
	  //if (0 > value) value = 0;
	  if (isNaN(value)) 
	  {
		  alert('You may have entered an incorrect character or exceeded the range for some information on this tab. \nPlease check your information and try again.');
		  elem.value = '';
		  return false;
	  }
	  elem.value = format(value, lead, sep);
  }
	return true;
}

function RemoveFormat(e)
{
  document.getElementById(e.id).value = cleanNumber(document.getElementById(e.id).value);
  e.select();
}

function IsInteger(nNum) {
	var NewRegPattern = new RegExp("[0-9]");
	var nTemp;
	var bRet;
	bRet = true;
	if (nNum.length < 1) {
		bRet = false;
	}
	for (i=0;i<nNum.length; i++) {
		nTemp = nNum.charAt(i);
		if (NewRegPattern.exec(nTemp) == null) {
			bRet = false;
			break;
		}	
	}	
	if (bRet == true ) {
		return true;
	 } else {
		return false;
	}
}

// Replaces the Special characters in a number if any.
function cleanNumber(strNum)
{
	if (!strNum) return strNum;
	strNum = Replace(strNum, '$', '', 0);
	strNum = Replace(strNum, ',', '', 0);
	strNum = Replace(strNum, '%', '', 0);	
	strNum = Replace(strNum, ' ', '', 0);
	return strNum;
}

//Function for replacing the strings
function Replace(szBuf, szFind, szReplace, lStart)
{
	var lFind = 0;
	if (!lStart) lStart = 0;
	
	while (lFind != -1) {
		lFind = szBuf.indexOf(szFind, lStart);

			if (lFind != 0 &&(lFind == '' || lFind == null)) lFind = -1;

		if (lFind != -1) {
			szBuf = szBuf.substring(0,lFind) + szReplace + szBuf.substring(lFind + szFind.length);
			lStart = lFind + szReplace.length;
		}
	}
	return szBuf;
}

//Format a percentage into a decimal
function unformatPercent(myValue) {
	var retValue = cleanNumber(myValue)/100;	
	return retValue;	
}

// Formats a given value with a leading character and a separator. 
function format(value, lead, sep)
{
	var strValue = new String(value);
	var len = strValue.length;
	var n;
	var strRet = '';
	var ctChar = 3 - (len%3);
	if (ctChar == 3) ctChar =0;
	for (n=0; len > n; n++) {
		if (ctChar == 3) {
			strRet += sep;
			ctChar = 0;
		}
		ctChar++;
		strRet += strValue.substring(n,n+1)		
	}
	if (lead == '%') {
		return strRet + lead;
	}
	else {
		return lead + strRet;
	}
}

//Format number n to 2 decimal places and return it as a string.
function Format2DecPlace(n)
{
   var work,dp,sl,dl;
   
   work = ""+ floor(n); // force only 2 decimals
   sl=work.length;
   
   if(-1 == (dp = work.indexOf(".")))work=work+".00";
   else if(3 > sl-dp)work = work+".00".substring(sl-dp,3);
   
   return work;
}//end Format2DecPlace

//Purpose: Round number to 2nd digit.
function round2d(n){
	return(.01* Math.round(100*n));
}

//Purpose: Return the smallest number in the 2nd  decimal digit.
function ceil2d(n){
	return(.01* Math.ceil(100*n));
}

//Purpose: Return the largest number in the 2nd  decimal digit.
function floor(number){
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);	//floor(number *100)/100
}//end floor


//Adds an event handler to dynamically created html controls
function addEventHandler(obj, evType, fn){
 if (obj.addEventListener){
   obj.addEventListener(evType, fn, true);
   return true;
 } else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
 } else {
   return false;
 }
}

/*-----------------------------------+
| The functions hidebox, showbox,    |
| minimize and restore all control   |
| the window type 'popup' boxes that |
| are created on the page.           |
| They only work with W3C standard   |
| browsers.                          |
+-----------------------------------*/
function DestroyBox(id)
{
  if(w3c && document.getElementById(id))
  {
    document.body.removeChild(document.getElementById(id));
  }
}

function HideBox(id)
{
  if(w3c && document.getElementById(id))
  {
    document.getElementById(id).style.display='none';
  }
}

function showbox(id)
{
  if(w3c)
  {
    var bx=document.getElementById(id).style;
    var sh=document.getElementById(id).style;
    bx.display='block';
    sh.display='block';
    sh.zIndex=++zdx;
    bx.zIndex=++zdx;
  }
}

function minimize()
{
  if(w3c)
  {
    this.IDS[0].style.height=(ie5)? '28px':'24px';
    this.IDS[3].style.height='28px';
    this.IDS[2].style.display='none';
    this.IDS[4].style.display='none';
    setTimeout('ns6bugfix()',100);
  }
}

function restore()
{
  if(w3c)
  {
    var h=this.IDS[10];
    this.IDS[0].style.height=h+'px'; //box
    this.IDS[3].style.height=(ie5)? h+'px':h+5+'px'; //shd
    this.IDS[2].style.display='block';
    this.IDS[4].style.display='block'; 
    setTimeout('ns6bugfix()',100);
  }
}

//Purpose as the name emplies, fixes a 'bug' with NS 6
function ns6bugfix()
{
  self.resizeBy(0,1);
  self.resizeBy(0,-1);
}

function trackmouse(evt)
{
  mx=(ie5)?event.clientX+truebody().scrollLeft:evt.pageX;
  my=(ie5)?event.clientY+truebody().scrollTop:evt.pageY;
  if(!ns6)movepopup();
  if((currIDb!=null)||(currRS!=null))return false;
}

function movepopup()
{
  if((currIDb!=null)&&w3c)
  {
    var x=mx+xoff;
    var y=my+yoff;
    currIDb.style.left=x+'px';
    currIDs.style.left=x+8+'px';
    currIDb.style.top=y+'px';
    currIDs.style.top=y+8+'px';
  }
  if((currRS!=null)&&w3c)
  {
    var rx=mx+rsxoff;
    var ry=my+rsyoff;
    var c=currRS;
    c.style.left=Math.max(rx,((ie5)?88:92))+'px';
    c.style.top=Math.max(ry,((ie5)?68:72))+'px';
    c.IDS[0].style.width=Math.max(rx+((ie5)?12:8),100)+'px';
    c.IDS[0].style.height=Math.max(ry+((ie5)?12:8),80)+'px';
    c.IDS[1].style.width=Math.max(rx+((ie5)?4:3),((ns6)?95:92))+'px';
    c.IDS[5].style.left=parseInt(c.IDS[1].style.width)-48+'px';
    c.IDS[3].style.width=Math.max(rx+12,((ie5)?100:104))+'px';
    c.IDS[3].style.height=Math.max(ry+((ie5)?12:13),((ie5)?80:86))+'px';
    c.IDS[2].style.width=Math.max(rx-((ie5)?-5:5),((ie5)?92:87))+'px';
    c.IDS[2].style.height=Math.max(ry-((ie5)?24:28),44)+'px';
    c.IDS[10]=parseInt(c.IDS[0].style.height);
  }
}

/*------------------------------------------------------------+
|  This creates a div box to be used for popups their         |
|  corresponding shadow box and a title bar if the developer  |           
|  wants. This is a slightly modified version of code from    |
|  Brian Gosselin w/ changes by Dynamicdrive.com              |
|  Parameters:                                                |
|  x =  Top where box will appear                             |
|  y =  Left where box will appear                            |
|  id = Id of the div so that the style sheet can do most of  |
|       the formating.                                        |
|  h =  Height of box, if this is a zero the style sheet will |
|       handle the height                                     |
|  w =  Same as height except for width                       |
|  ClassName = the style sheet class name                     |
+------------------------------------------------------------*/
function createSubBox(x, y, id, h, w, ClassName)
{
  var v=document.createElement('div');
  v.setAttribute('id',id); 
  v.style.position='absolute';
  v.style.left=x+'px';
  v.style.top=y+'px';
  if(w>0)
    v.style.width=w+'px';
  if(h>0)
    v.style.height=h+'px';
  if(ClassName != "")
    v.className = ClassName;
    
  v.style.visibility='visible';
  return v  
}

var mouseX;
var mouseY;

/* Remote iframe call related */
var IFrameObj; 

function buildQueryString(theFormName) {
  theForm = document.forms[theFormName];
  var qs = ''
  for (e=0;e<theForm.elements.length;e++) {
    if (theForm.elements[e].name!='') {
      qs+=(qs=='')?'?':'&'
      qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value)
      }
    }
  return qs
}


  function callToServer(URL) {
    if (!document.createElement) {return true};
    var IFrameDoc;
    if (!IFrameObj && document.createElement) {
      // create the IFrame and assign a reference to the
      // object to our global variable IFrameObj.
      // this will only happen the first time 
      // callToServer() is called
    try {
        var tempIFrame=document.createElement('iframe');
        tempIFrame.setAttribute('id','RSIFrame');
        tempIFrame.style.border='0px';
        tempIFrame.style.width='0px';
        tempIFrame.style.height='0px';
        IFrameObj = document.body.appendChild(tempIFrame);

        
        if (document.frames) {
          // this is for IE5 Mac, because it will only
          // allow access to the document object
          // of the IFrame if we access it through
          // the document.frames array
          IFrameObj = document.frames['RSIFrame'];
        }
      } catch(exception) {
        // This is for IE5 PC, which does not allow dynamic creation
        // and manipulation of an iframe object. Instead, we'll fake
        // it up by creating our own objects.
        iframeHTML='\<iframe id="RSIFrame" style="';
        iframeHTML+='border:0px;';
        iframeHTML+='width:0px;';
        iframeHTML+='height:0px;';
        iframeHTML+='"><\/iframe>';
        document.body.innerHTML+=iframeHTML;
        IFrameObj = new Object();
        IFrameObj.document = new Object();
        IFrameObj.document.location = new Object();
        IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
        IFrameObj.document.location.replace = function(location) {
          this.iframe.src = location;
        }
      }
    }
    
    if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
      // we have to give NS6 a fraction of a second
      // to recognize the new IFrame
      setTimeout('callToServer()',10);
      return false;
    }
    
    if (IFrameObj.contentDocument) {
      // For NS6
      IFrameDoc = IFrameObj.contentDocument; 
    } else if (IFrameObj.contentWindow) {
      // For IE5.5 and IE6
      IFrameDoc = IFrameObj.contentWindow.document;
    } else if (IFrameObj.document) {
      // For IE5
      IFrameDoc = IFrameObj.document;
    } else {
      return true;
    }
    IFrameDoc.location.replace(URL);
    return false;     
  }

  function handleResponse(text, term)
  {
    ShowAnswer(text, term);
  }

  function ShowAnswer(def, term)
  {
    var wid = 0;
    var len = def.length;
    if(len <= 300)
      wid = 100;
    if(len >= 301 && len <= 450)
      wid = 150;
    if(len >= 451 && len <= 650)
      wid = 250;
    if(len >= 651)
      wid = 300;
    
    var t;
      
    t = "<a href='javascript:void(0)' onclick='HideAnswer()'>Close</a><p></p>";
    t += "<b>" + term + "</b><p></p>";
    t += def;
    t += "<p><a href='javascript:void(0)' onclick='HideAnswer()'>Close</a></p>";
    DestroyBox('AnswerBox');
    DestroyBox('AnswerBoxShadow');
    
    
    var ansBox = createSubBox((mousePos.x+25), mousePos.y, 'AnswerBox', 0, wid, '');
    ansBox.innerHTML = t;
    
    var ansShadow = createSubBox((mousePos.x+30), (mousePos.y+5), 'AnswerBoxShadow', 0, wid, '');
    ansShadow.innerHTML = t;
    if(ie5)
      ansShadow.style.filter='alpha(opacity=50)';
    else 
      ansShadow.style.MozOpacity=.5;

    document.body.appendChild(ansShadow);
    document.body.appendChild(ansBox);
  }

  function HideAnswer()
  {
    DestroyBox('AnswerBox');
    DestroyBox('AnswerBoxShadow');
  }        

  //This is the same as the one below but it will allow you to pass in the offset
  //and the width and height
  function ShowAnswerBox(t, xo, yo, h, w)
  {
  
    t = "<a href='javascript:void(0)' onclick='HideAnswer()'>Close</a><p></p>" + t;
    t += "<p><a href='javascript:void(0)' onclick='HideAnswer()'>Close</a></p>";
    DestroyBox('AnswerBox');
    DestroyBox('AnswerBoxShadow');

    var ansBox = createSubBox((mousePos.x+xo), (mousePos.y+yo), 'AnswerBox', h, w, '');
    ansBox.innerHTML = t;
    
    var ansShadow = createSubBox((mousePos.x+xo+5), (mousePos.y+yo+5), 'AnswerBoxShadow', h, w, '');
    ansShadow.innerHTML = t;
    if(ie5)
      ansShadow.style.filter='alpha(opacity=50)';
    else 
      ansShadow.style.MozOpacity=.5;

    document.body.appendChild(ansShadow);
    document.body.appendChild(ansBox);  
  }

  /*
  This allows for a JS Div box with shadow to be placed on the page
  the parameters are: t = text to show; x = x position; y = y position;
  h = height; w = width;
  */
  function ShowDivBox(t, x, y, h, w)
  {
    t += "<p><a href='javascript:void(0)' onclick='HideDivBox()'>Close</a></p>";

    var wid = 0;
    var len = t.length;
    if(len <= 300)
      wid = 100;
    if(len >= 301 && len <= 450)
      wid = 150;
    if(len >= 451 && len <= 650)
      wid = 250;
    if(len >= 651)
      wid = 300;

    var ansBox = createSubBox(x, y, 'GeneralBox', h, wid, 'QuestionBox');
    ansBox.innerHTML = t;
    
    var ansShadow = createSubBox((x+5), (y+5), 'GeneralBoxShadow', h, wid, 'QuestionBoxShadow');
    ansShadow.innerHTML = t;
    if(ie5)
      ansShadow.style.filter='alpha(opacity=50)';
    else 
      ansShadow.style.MozOpacity=.5;

    document.body.appendChild(ansShadow);
    document.body.appendChild(ansBox);    
  }
  
  function HideDivBox()
  {
    DestroyBox('GeneralBox');
    DestroyBox('GeneralBoxShadow');
  }        
  
  /*
    This function and the following one are for the questions 
    for the loan declarations  
  */
  //a is the hidden control the answer is put in
  //t is the question from the array
  function ShowQuestion(t, a, b)
  {
    var hidValue = document.getElementById(a).value;
    var ts = t; //this is for the shadow box  <textarea id=answer rows=3 cols=20></textarea>
    t += "<p><textarea  id='answer' rows=3 cols=15>" + hidValue + "</textarea>"; //this is for the question box
    t += "<p><center><a href='javascript:void(0)' onclick=\"SaveAnswer('" + a + "')\">Save</a></center>";
    //these are here so the shadow is the same size as the question box
    ts += "<p><textarea  rows=3 cols=15 id='answershadow' wrap=false style='background:#000000'></textarea>"; 
    ts += "<p><center><a href='javascript:void(0)' onclick=\"SaveAnswer('" + a + "')\">Save</a></center>";
    
    DestroyBox('QuestionBox');
    DestroyBox('QuestionBoxShadow');

    //This is here to move the question box up a bit when called from the save button and to 
    //negate the effect of the 105 for the x when the box is called from the "Saved Answer" button.
    switch(b)
    {
      case 1: //Save button was clicked
        mousePos.y = mousePos.y-250;
        mousePos.x = mousePos.x-70;
        break;
      case 2: //the button for an existing reason was clicked
        mousePos.x = mousePos.x - 105;
        break;
    }

    var questBox = createSubBox((mousePos.x+105), (mousePos.y-50), 'QuestionBox', 0, 0, 'QuestionBox');
    questBox.innerHTML = t;

    var questShadow = createSubBox((mousePos.x+108), (mousePos.y-47), 'QuestionBoxShadow', 0, 0, 'QuestionBoxShadow');
    questShadow.innerHTML = ts;
    
    if(ie5)
      questShadow.style.filter='alpha(opacity=50)';
    else 
      questShadow.style.MozOpacity=.5;

    document.body.appendChild(questShadow);
    document.body.appendChild(questBox);
  }

  function SaveAnswer(a)
  {
    document.getElementById(a).value = document.getElementById("answer").innerText;
    DestroyBox('QuestionBox');
    DestroyBox('QuestionBoxShadow');
  }

  function ClearAnswer(a)
  {
    document.getElementById(a).value = '';
    DestroyBox('QuestionBox');
    DestroyBox('QuestionBoxShadow');
  }        

  // Detect if the browser is IE or not.
  var IE = document.all?true:false

  // If !IE -- then set up for mouse capture
  if (!IE) document.captureEvents(Event.MOUSEMOVE)


document.onmousemove = mouseMove;
var mousePos;

function mouseMove(ev){
	ev           = ev || window.event;
	mousePos = mouseCoords(ev);

}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
		y:ev.clientY + document.documentElement.scrollTop  - document.documentElement.clientTop
	};
}

//  // Set-up to use getMouseXY function onMouseMove
//  document.onmousemove = getMouseXY;

//  // Temporary variables to hold mouse x-y pos.s
//  var tempX = 0
//  var mousePos.y = 0

//  // Main function to retrieve mouse x-y pos.s

//  function getMouseXY(e) {
//    if (IE) { // grab the x-y pos.s if browser is IE
//      tempX = event.clientX + document.body.scrollLeft
//      tempY = event.clientY + document.body.scrollTop  - document.documentElement.clientTop
//    } else {  // grab the x-y pos.s if browser is NS
//      tempX = e.pageX
//      tempY = e.pageY
//    }  
//    // catch possible negative values in NS4
//    if (tempX < 0){tempX = 0}
//    if (tempY < 0){tempY = 0}  
//    return true
//  }

/*
  function ShowDefinition(t)
  {
    DestroyBox('AnswerBox');
    DestroyBox('AnswerBoxShadow');

    var adj = 0;
    var s = new String;
    s = t;
    //Adjust for long answers
    if(s.length > 400)
      adj = 58;
    //Adjust for short answers
    if(s.length < 100)
      adj = - 58;

    //Force definitions to always be on the side
    tempX = 750;
    var newHeight = Math.round((s.length) - adj);

    var ansBox = createSubBox((tempX+25), tempY, 'AnswerBox', newHeight, 0, '');
    
    ansBox.innerHTML = t + "<p><a href='javascript:void(0)' onclick='CloseAnswer()'>Close</a>";
    
    var ansShadow = createSubBox((tempX+30), (tempY+5), 'AnswerBoxShadow', newHeight, 0, '');
    if(ie5)
      ansShadow.style.filter='alpha(opacity=50)';
    else 
      ansShadow.style.MozOpacity=.5;

    document.body.appendChild(ansShadow);
    document.body.appendChild(ansBox);
  }

  function CloseAnswer()
  {
    DestroyBox('AnswerBox');
    DestroyBox('AnswerBoxShadow');
  }
*/  
  //Can be used anywhere, used on the input/results tabs right now
  //To use on other items change the text passed in and add to the
  //switch statement. eg onmouseover="SetStatus('Input');return true"
  //The return true mus tbe there for it to work.
  function SetStatus(t)
  {
    switch (t)
    {
      case "Input":
        window.status = "Show Input";
        break;
      case "Results":
        window.status = "Show Results";
        break;
      default:
        window.status = "";
        break;
    }
    return true;
  }
  
  function MaskDate(objEvent)
  {
    /*
      This formats the text as a short date "mm/dd/yyyy"
 	    The call to this function must occur in the tag's onKeyPress event.
    */
    var iKeyCode, strKey;
    var oEle = eventTrigger(objEvent);
    var sTemp = oEle.value.toString();

    if (isIE) {
      iKeyCode = objEvent.keyCode;
    } else {
      iKeyCode = objEvent.which; 
    }
    
    if(iKeyCode == 8 || iKeyCode==0)
      return true;
            
    if(sTemp.length == 10)
      return false;

    if (iKeyCode==47)
      return true;

//    if (iKeyCode==47)
//    {
//      alert(oEle.value);
//      switch (sTemp.length)
//      {
//        case 4:
//	        oEle.value = "0" + oEle.value;
//	        break;
//        case 1:
//	        oEle.value = "0" + oEle.value;
//	        break;												
//      }
//    }

    if((IsNumeric(iKeyCode) && sTemp.length <= 9) || iKeyCode == 47)
    {
      
 	      switch (sTemp.length)
 	      {
 	        case 5:
 	          if(Right(oEle.value, 1) != "/")
 	            oEle.value += "/";
 	          else
 	            oEle.value = InsertString(oEle.value, "0", 4);
 	  	      break;
 	        case 2:
 	          if(Right(oEle.value, 1) != "/")
 	  	        oEle.value += "/";
 	  	      else
 	            oEle.value = InsertString(oEle.value, "0", 0);
 	  	      break;												
 	      }
    }
    else
    {
      oEle.value = "";
 	    window.status = "Dates can only contain numbers and must be 10 characters long (including slashes).";	
 	    window.status += "(keycode: " + iKeyCode + ")";
 	    iKeyCode=0;	
    }
    //cancel the event because we have explicitly added the character
    objEvent.cancel=true;						
  }

  function eventTrigger (e)
  {
    if (! e)
    e = event;
    return e.target || e.srcElement;
  }

  //This will allow numbers, a negative sign, and a period
  //use where the user can input a money amount
  //it will prevent dollar symbol from being input
  function IsNumericOrPeriod(objEvent)
  {
    var iKeyCode, strKey;
    var oEle = eventTrigger(objEvent);
    var sTemp = oEle.value.toString();
     
    if (isIE) {
      iKeyCode = objEvent.keyCode;
    } else {
      iKeyCode = objEvent.which; 
    }
    
    if(IsNumeric(iKeyCode) || iKeyCode==46 || iKeyCode==45 || iKeyCode==0)
    { return true; }
    else
    { return false; }
  }
  
  //This will allow numbers only is a wrapper
  //areound the IsNumeric funtion below so an
  //event can be passed in.
  function IsNumericOnly(objEvent)
  {
    var iKeyCode, strKey;
    var oEle = eventTrigger(objEvent);
    var sTemp = oEle.value.toString();
     
    if (isIE) {
      iKeyCode = objEvent.keyCode;
    } else {
      iKeyCode = objEvent.which; 
    }
    
    if(IsNumeric(iKeyCode))
    { return true; }
    else
    { return false; }
  }

  function IsNumeric(key)
  {
    if((key>=48) && (key<=57))
    { return true; }
    else
    { return false; }
  }
  
  function MaskSSN(objEvent)
  {
	  /*
		  Formats an input's text to the standard SSN format("###-##-####") as the user enters data.  
		  It also prohibits the entry of invalid characters (like alphabetic chars).
  	
		  The call to this function must occure in the tag's onKeyPress event.
	  */
    var iKeyCode, strKey;
    var oEle = eventTrigger(objEvent);
    var sTemp = oEle.value.toString();
     
    if (isIE) {
      iKeyCode = objEvent.keyCode;
    } else {
      iKeyCode = objEvent.which; 
    }
    
    if(iKeyCode == 8 || iKeyCode==0)
      return true;

    if(sTemp.length == 11)
      return false;

    var iNum = new Number(iKeyCode);

    strKey = String.fromCharCode(iKeyCode);
	  if (!IsNumeric(iKeyCode) && iKeyCode!=45)
	  {
		  window.status = "Social Security Numbers can only contain numbers or dashes(\"-\") and must be 11 characters long (including dashes).";	
		  window.status += "(keycode: " + iKeyCode + ")";
		  iKeyCode=0;
  		return false;
	  }
	  else
	  {
	    if (iKeyCode==45) {iKeyCode=0;}
		  if (sTemp.length >=11){
  			
			  iNum = iNum-48;
			  oEle.value=sTemp.substr(0,sTemp.length-1) + (iNum.toString()); //remove the last char before allowing the new char to be added - thus keeping the length to the max allowed.
  			
			  iKeyCode=0;
		  }	else if (sTemp.length==3||sTemp.length==6) 
		  {
			  oEle.value += "-";
		  }
	  }	
	  objEvent.cancel=true;    
  }


  function MaskPhone(objEvent)
  {
	  /*
		  Formats an input's text to the standard US phone format ( "(###)###-####" ) as the user enters data.  
		  It also prohibits the entry of invalid characters (like alphabetic chars).
  	
		  The call to this function must occure in the tag's onKeyPress event.
	  */
    var iKeyCode, strKey;
	  var oEle = eventTrigger(objEvent);
	  var sTemp = oEle.value.toString();
	  var iNum = new Number(iKeyCode);	
  	
    if (isIE) {
      iKeyCode = objEvent.keyCode;
    } else {
      iKeyCode = objEvent.which; 
    }
    
    if(iKeyCode == 8 || iKeyCode==0)
      return true;

    if(sTemp.length == 13)
      return false;

	  if (	( (iKeyCode <48 || iKeyCode > 57)
					  && iKeyCode!=45
					  && iKeyCode!=40
					  && iKeyCode!=41										
				  ) 
  				
			  )
	  {
		  window.status = "Phone Numbers can only contain numbers or dashes(\"-\") and must be 11 characters long (including dashes).";	
		  window.status += " (keycode: " + iKeyCode + ")";
		  iKeyCode=0;
  			
	  }
	  else {

		  if (iKeyCode==40||iKeyCode==41||iKeyCode==45){iKeyCode=0;}

		  if (sTemp.length >=13){
  			
			  iNum = iNum-48;
			  oEle.value=sTemp.substr(0,sTemp.length-1) + (iNum.toString()); //remove the last char before allowing the new char to be added - thus keeping the length to the max allowed.
  			
			  iKeyCode=0;
		  }	else 
		  {
			  switch (sTemp.length){
			  case 5,8:
				  oEle.value += "-";
				  break;
			  case 0:
				  oEle.value += "(";
				  break;							
			  case 4:
				  oEle.value += ")";
				  break;							
			  }
		  }
	  }
	  //cancel the event because we have explicitly added the character
	  objEvent=true;						
  }
  
  //To verify that the date is correct but only if the date has been entered.
  function VerifyDate(e)
  {
    if(document.getElementById(e.id).value != '')
    {    
      if(isValidDate(document.getElementById(e.id).value, "MMDDYYY"))
        checkDate(e);
      else
      {
        alert("Date is not a valid format, please re-enter MMDDYYYY");
        document.getElementById(e.id).value = "";
        e.focus();
      }
    }
  }
  
  function isValidDate(dateStr, format) {
    if (format == null) 
      { format = "MDY"; }
    format = format.toUpperCase();
    if (format.length != 3) 
      { format = "MDY"; }
    if((format.indexOf("M") == -1) || (format.indexOf("D") == -1) || (format.indexOf("Y") == -1)) 
      { format = "MDY"; }
    if (format.substring(0, 1) == "Y") { // If the year is first
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
    } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
    } else { // The year must be third
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
    }
    // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
    if ( reg2.test(dateStr) == false ) 
      { return false; }
    var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
    // Check to see if the 3 parts end up making a valid date
    if (format.substring(0, 1) == "M") 
    { var mm = parts[0]; 
    } else if (
      format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; 
    }
    if (format.substring(0, 1) == "D") { 
      var dd = parts[0]; 
    } else if (
      format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; 
    }
    if (format.substring(0, 1) == "Y") {
      var yy = parts[0]; 
    } else if (format.substring(1, 2) == "Y") { 
      var yy = parts[1]; } else { var yy = parts[2]; 
    }
    if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
    if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
    var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
    if (parseFloat(dd) != dt.getDate()) { return false; }
    if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
    if (parseFloat(yy) < 1850 || parseFloat(yy) > 9999) { return false; }
    return true;
}


  function checkDate(e)
  {
    var intDayArray = new Array(12);
        intDayArray[0] = 31;
        intDayArray[1] = 29;
        intDayArray[2] = 31;
        intDayArray[3] = 30;
        intDayArray[4] = 31;
        intDayArray[5] = 30;
        intDayArray[6] = 31;
        intDayArray[7] = 31;
        intDayArray[8] = 30;
        intDayArray[9] = 31;
        intDayArray[10] = 30;
        intDayArray[11] = 31;

    var strMonthArray = new Array(12);
      strMonthArray[0] = "January";
      strMonthArray[1] = "Febuary";
      strMonthArray[2] = "March";
      strMonthArray[3] = "April";
      strMonthArray[4] = "May";
      strMonthArray[5] = "June";
      strMonthArray[6] = "July";
      strMonthArray[7] = "August";
      strMonthArray[8] = "September";
      strMonthArray[9] = "October";
      strMonthArray[10] = "November";
      strMonthArray[11] = "December";
        
    var el = document.getElementById(e.id);
    var txt = new String;
    txt = el.value;
    if(txt.length > 0)  
    {      
      var ar = txt.split("/");

      var m = ar[0].valueOf();
      var reg = /\/{2}/
      txt = txt.replace(reg, "/");

      el.value = txt;
      
      if(m>12)
      {
        alert('The month cannot be larger then 12');
        el.focus();
        return false;
      }
    
      var d = ar[1].valueOf();
      
      if( d > intDayArray[m-1])
      {
        alert('Invalid days for ' + strMonthArray[m-1]);
        el.focus();
        return false;
      }
    
      var y = ar[2].valueOf();
            
      if(y.length < 4)
      {
        alert('Please input the entire year');
        el.focus();
        return false;
      }
      
    }
  }
  
  function PIPayment(principal, annualRate, termInMonths)
  {
    var rate;
    if(annualRate > 1)
      rate = annualRate * .01;
    else
      rate = annualRate;
    var monthlyRate = 1+(rate/12);
    var PI_payment = ceil2d(principal*(monthlyRate-1)/(1-Math.pow(monthlyRate,-(termInMonths))));
    return PI_payment;
  }
  
  function Left(str, n)
  {
	  if (n <= 0)
	      return "";
	  else if (n > String(str).length)
	      return str;
	  else
	      return String(str).substring(0,n);
  }

  function Right(str, n)
  {
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
  }
  
  function InsertString(str, ch, n)
  {
    var sub1 = new String();
    var sub2 = new String();
    var sub3 = new String();
    
    sub3 = str;
    
    sub1 = sub3.substring(0, n-1);
    sub2 = sub3.substring(n-1);

    sub3 = sub1 + ch + sub2;
    return sub3;
  }
  
  function TESTER(e)
  {
    var e = e.value;
    alert(e);
  }
  
  function ValNumGreaterThenZero(txtVal,sFieldName)
  {
    var OK;
    var Message = "Please enter a value greater than zero for " + sFieldName + ".";
    var Text = txtVal.value;
    
    OK = false;
    
    if(Text == "")
    {
        alert(Message);
        txtVal.focus();
        return OK;
    }
    
    if(Text < 1)
    {
        alert(Message);
        txtVal.focus();
        return OK;
    }
    
    OK = true;
    
    return OK;
  }
  
  function ValSSN2(txtSSNComplete,sFieldName,BlankOK)
{//this is for a SSN all in one textbox
    var OK;
    var Message = "Please enter a valid " + sFieldName + " value.";
    var Text = txtSSNComplete.value;
    var splitSSN = new Array(3);
    
    OK = false;
    
    if(BlankOK == false)
    {
        if(Text.value == "")
        {
            alert(Message);
            txtSSNComplete.focus();
        }
    }
    
    if(Text.value != "")
    {
        splitSSN = Text.split("-",3)
        if(splitSSN[0].length != 3 || splitSSN[1].length != 2 || splitSSN[2].length != 4)
        {
            alert(Message);
            txtSSNComplete.focus();
        }
    }
}
  
  /*  AJAX Related functions */
  
  function GetHttpRequest()
  {
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    else
    {
      return http_request;
    }      
  }
 