//*******************************************************************************
// Copyright © 2001-2004 Witt Biomedical Corporation
//
// Filename:		/js/_functions.js
// Author:			Jason Rosensweig
// Description:		javascript functions
// Created:			10/07/04
//
//	Date		Author			Description
//	7/8/05		JR				fixed date function to allow 2 or 4 digit year
//	02/07/06	JR				added password restrictions (DVR-32)
//
//
//*******************************************************************************

//*************************************************************
//				ARRAY FUNCTIONS START
//*************************************************************
function arrayInsert(arrayObj,insertVal,i){
	var tempArray = arrayObj;
	var newArray = new Array();

	if(arrayObj.length == undefined || arrayObj.length < 0){
		alert("Invalid array object.")
		return false;
	}
	
	if(!isNumeric(i) || isDecimal(i)){
		alert("Index " + i + " is not an integer.");
		return false;
	}
	
	if(i < 0){
		alert("An index that is 0 or greater is required.");
		return false;
	}
	
	if(i > arrayObj.length){
		alert("Your array has " + arrayObj.length + " elements.\r\nPlease enter a positive, zero-based index that is no greater than " + eval(arrayObj.length));
		return false;
	}
	
	tempArrayIndex = 0;
	for(j=0;j<=tempArray.length;j++){
		if(j==i){
			newArray[j] = insertVal;
		}
		else{
			newArray[j] = tempArray[tempArrayIndex];
			tempArrayIndex++;
		}
	}
	return newArray;
}

function arrayAppend(arrayObj,insertVal){
	var tempArray = arrayObj;
	var newArray = new Array();

	if(arrayObj.length == undefined || arrayObj.length < 0){
		alert("Invalid array object.")
		return false;
	}
	
	var i = arrayObj.length;
	tempArrayIndex = 0;
	for(j=0;j<=tempArray.length;j++){
		if(j==i){
			newArray[j] = insertVal;
		}
		else{
			newArray[j] = tempArray[tempArrayIndex];
			tempArrayIndex++;
		}
	}
	return newArray;
}

function arrayDelete(arrayObj,i){
	var tempArray = arrayObj;
	var newArray = new Array();

	if(arrayObj.length == undefined || arrayObj.length < 0){
		alert("Invalid array object.")
		return false;
	}
	
	if(!isNumeric(i) || isDecimal(i)){
		alert("Index " + i + " is not an integer.");
		return false;
	}
	
	if(i < 0){
		alert("An index that is 0 or greater is required.");
		return false;
	}
	
	if(i > arrayObj.length - 1){
		alert("Your array has " + arrayObj.length + " elements.\r\nPlease enter a positive, zero-based index that is no greater than " + eval(arrayObj.length - 1));
		return false;
	}

	tempArrayIndex = 0;
	for(j=0;j<tempArray.length;j++){
		if(j==i){
			// do nothing and skip value
		}
		else{
			newArray[tempArrayIndex] = tempArray[j];
			tempArrayIndex++;
		}
	}
	return newArray;
}
//*************************************************************
//				ARRAY FUNCTIONS END
//*************************************************************



//*************************************************************
//				STRING AND NUMBER FUNCTIONS START
//*************************************************************
function replaceAll(str,char1,char2){
	str = str.replace(char1,char2);
	if(str.indexOf(char1) != -1){
		return replaceAll(str,char1,char2);
	}
	else{
		return str;
	}
}

// check value to see if it is numeric
function isNumeric(num){
	var i;
	num = num.toString();
	
	if(num == ""){
		return false;
	}

	if(num.charAt(0) == "-"){
		start = 1;
	}
	else{
		start = 0;
	}

	for(i=start;i<num.length;i++){
		if(num.charAt(i) < "0" && num.charAt(i) != "."){
			return false;
		}
		if(num.charAt(i) > "9" && num.charAt(i) != "."){
			return false;
		}
	}

	return true;
}

function isDecimal(num){
	//convert to a string
	num = num.toString();
	
	if(!isNumeric(num)){
		//not a number
		//alert("Not a number.");
		return false;
	}
	else if(num.indexOf(".") != -1){
		return true;
	}
	else{
		return false;
	}
}


//round numbers to specified dec places
function round (n, d) {
  n = n - 0; // force number
  if (d == null) d = 2;
  var f = Math.pow(10, d);
  n += Math.pow(10, - (d + 1)); // round first
  n = Math.round(n * f) / f;
  n += Math.pow(10, - (d + 1)); // and again
  n += ''; // force string
  return d == 0 ? n.substring(0, n.indexOf('.')) :
      n.substring(0, n.indexOf('.') + d + 1);
}


// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.
// call function example as follows: isDate(this.value, 1) 
// The function returns true if a valid date, false if not.
// ******************************************************************

function isDate(dateStr,showAlert) {
	//fixed date function to allow 2 or 4 digit year - JR 7/8/05
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{2,4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	
	if (matchArray == null) {
		if(showAlert){
			alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
		}
		return false;
	}
	
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[5];
	
	if (month < 1 || month > 12) { // check month range
		if(showAlert){
			alert("Month must be between 1 and 12.");
		}
		return false;
	}
	
	if (day < 1 || day > 31) {
		if(showAlert){
			alert("Day must be between 1 and 31.");
		}
		return false;
	}
	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		if(showAlert){
			alert("Month "+month+" doesn't have 31 days!")
		}
		return false;
	}
	
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			if(showAlert){
				alert("February " + year + " doesn't have " + day + " days!");
			}
			return false;
		}
	}
	return true; // date is valid
}
//*************************************************************
//				STRING AND NUMBER FUNCTIONS END
//*************************************************************


//*************************************************************
//				FORM AND DOCUMENT FUNCTIONS START
//*************************************************************
selectElementArray = document.getElementsByTagName('select');
selectState = 1; // visible

function hideSelect(bool) {
	/*alert(val);*/
	if(bool == true){
		for(i=0;i<selectElementArray.length;i++){
			if(selectElementArray[i].doHide == "1"){
				selectElementArray[i].style.visibility = 'hidden';
			}
		}
	}
	else if(bool == false){
		for(i=0;i<selectElementArray.length;i++){
			if(selectElementArray[i].doHide == "1"){
				selectElementArray[i].style.visibility = 'visible';
			}
		}
	}
}

function showDiv(div){
	if(div.style.visibility == "hidden"){
		div.style.visibility = "visible";
	}
	else{
		div.style.visibility = "hidden";
	}
}

function correctSize(width, height, inApp){	
	var isIE = false;

	if (self.innerWidth){
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth){
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body){
		isIE = true;
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	else 
		return;

	var widthOffset = 0;
				
	// the app thinks there's scrollbars there
	if (isIE && inApp)
		widthOffset = -16;

	if (width != frameWidth || height != frameHeight){	
		parent.window.resizeBy((width - frameWidth + widthOffset), (height - frameHeight));
	}
}

function checkAll(chk){
	if(chk[0] != undefined){
		if(chk[0].checked == false){
			for(var i=0;i<chk.length;i++){
				chk[i].checked = true;
			}
		}
		else{
			for(var i=0;i<chk.length;i++){
				chk[i].checked = false;
			}
		}
	}
	else{
		chk.checked = !chk.checked;
	}
}

function clipText(txtField) {
	//var tempval = txtField;
	//tempval.focus();
	//tempval.select();
	if (document.all){
		therange=txtField.createTextRange();
		therange.execCommand("Copy");
	}
}

function pasteText(txtField) {
	//var tempval = txtField;
	//tempval.focus();
	//tempval.select();
	if (document.all){
		therange=txtField.createTextRange();
		therange.execCommand("Paste");
	}
}

function setCheckValue(obj,chk){
	var checkMe = false;
	if(chk.checked == true){
		checkMe = true;
	}
	for(i=0;i<obj.length;i++){
		obj[i].checked = false;
	}
	if(checkMe){
		chk.checked = true;
	}
}

function hiliteBox(txtField,bit){
	if(bit == 1){
		txtField.style.backgroundColor = '#FFEE00';
	}
	else if(bit == 0){
		txtField.style.backgroundColor = 'white';
	}
}

function hiliteTD(td,color){
	td.style.backgroundColor = color;
}

//uncomment 2 lines below to enable no right-click
document.onmousedown = noRightClick;
document.oncontextmenu = noContextMenu;
function noRightClick(e) {
	if (document.layers || document.getElementById && !document.all) {
		if (e.which == 2 || e.which == 3) {
			document.captureEvents(Event.MOUSEDOWN);
			return false;
		}
	} 
	else if (document.all && !document.getElementById) {
		if (event.button == 2)
		return false;
	}
}

function noContextMenu () {
	return false;
}

function disableRightClick(){
	document.onmousedown = noRightClick;
	document.oncontextmenu = noContextMenu;
}

//checks the length of the value of an object and compares it with the maximum length
//use with both onKeyPress and onKeyUp events
function charCounter(obj,maxCount,counterObj){
	if(obj.value.length > maxCount){
		alert("You may only enter up to " + maxCount + " characters in this field.");
		obj.value = obj.value.substr(0,maxCount);
		counterObj.value = maxCount - obj.value.length;
		return false;
	}
	counterObj.value = maxCount - obj.value.length;
}

function noSubmit(){    
	if(event.keyCode == 13){        
		event.cancelBubble = true;
		event.returnValue = false;
	}
} 

var alphaList = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var alphaArray = alphaList.split(",");
var specialCharList = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,!,@,#,$,%,^,&,*,(,)";
var specialCharArray = specialCharList.split(",");

var hasSpecChar = false;
var hasNumeric = false;
var hasAlpha = false;

function checkPwd(str,specCharReq,alphaNumericReq){
	for(i=0;i<str.length;i++){
		currChar = str.substr(i,1)
		for(j=0;j<specialCharArray.length;j++){
			//check for special characters
			if(currChar == specialCharArray[j]){
				hasSpecChar = true;
			}
			//check for numeric
			if(isNumeric(currChar)){
				hasNumeric = true;
			}
		}
		//check for alpha
		for(k=0;k<alphaArray.length;k++){
			if(currChar.toLowerCase() == alphaArray[k].toLowerCase()){
				hasAlpha = true;
			}
		}
	}
	//alert("hasAlpha = " + hasAlpha);
	//alert("hasNumeric = " + hasNumeric);
	//alert("hasSpecChar = " + hasSpecChar);

	if(specCharReq && !hasSpecChar){
		alert("Password does not contain special characters.")
		return false;
	}
	if(alphaNumericReq && (!hasNumeric || !hasAlpha)){
		alert("Password is not alpha-numeric.")
		return false;
	}
	return true;
}

//*************************************************************
//				FORM AND DOCUMENT FUNCTIONS END
//*************************************************************



//*************************************************************
//					POPUP WINDOW FUNCTIONS START 
//*************************************************************
//Modal window  (always on top; retains focus)
function fnOpenModal(url,ht,wt,cntr,scrl,sts){
   ModalWind = window.showModalDialog(url, window, "dialogheight:" + ht + "px;dialogwidth:" + wt + "px;center:" + cntr + ";scroll:" + scrl + ";status:" + sts + ";help:no;edge:raised;")
   return ModalWind;
}

//Modeless window (always on top)
function fnOpenModeless(url,ht,wt,cntr,scrl,sts){
   ModelessWind = window.showModelessDialog(url, window, "dialogheight:" + ht + "px;dialogwidth:" + wt + "px;center:" + cntr + ";scroll:" + scrl + ";status:" + sts + ";help:no;edge:raised;")
   return ModelessWind;
}

var infoWind;
function infoWindow(url,ht,wt,scrl,rsz,cntr){
	if(infoWind == null || infoWind.closed){
		infoWind = window.open(url,"info",'TOOLBAR=0,LOCATION=0,DIRECTORIES=0,STATUS=0,MENUBAR=0,SCROLLBARS=' + scrl + ',RESIZABLE=' + rsz + ',WIDTH=' + wt + ',HEIGHT=' + ht);
		//center popup
		if (cntr == '1'){
			infoWind.moveTo((screen.width/2)-200,(screen.height/2)-75);
		}
		infoWind.focus();
	}
	else{
		infoWind.focus();
	}
}

var patientInfoWind;
function patientInfoWindow(caseID){
	if(patientInfoWind == null || patientInfoWind.closed){
		patientInfoWind = window.open("/webdv/secure/cases/patientInfo.asp","patientInfo",'TOOLBAR=0,LOCATION=0,DIRECTORIES=0,STATUS=0,MENUBAR=0,SCROLLBARS=1,RESIZABLE=1,WIDTH=250,HEIGHT=500');
		//move window
		patientInfoWind.moveTo((screen.width)-260,0);
		patientInfoWind.focus();
	}
	else{
		patientInfoWind.focus();
	}
}

function numberOrderSort(a,b){
	return (a.toString().substring(a.length - 6,a.length - 4) - b.toString().substring(b.length - 6,b.length - 4));
}

var helpWind;
function helpWindow(helpID){
	if(helpWind == null || helpWind.closed){
		helpWind = window.open("/webdv/library/help/help.asp?helpID=" + helpID,"help","TOOLBAR=0,LOCATION=0,DIRECTORIES=0,STATUS=0,MENUBAR=0,SCROLLBARS=0,RESIZABLE=0,WIDTH=300,HEIGHT=300");
		//right side popup
		helpWind.moveTo((screen.width)-325,10);
		helpWind.focus();
	}
	else{
		helpWind.focus();
	}
}

function popup(HTMLContent,Xpos,Ypos,wt,ht) {
	var oPopup = window.createPopup();
    var oPopupBody = oPopup.document.body;
	oPopupBody.style.backgroundColor = "lightyellow";
	oPopupBody.style.border = "solid black 1px";    
    oPopupBody.innerHTML = HTMLContent;
    oPopup.show(Xpos, Ypos, wt, ht, document.body);
	
}
//*************************************************************
//					POPUP WINDOW FUNCTIONS END
//*************************************************************



//*************************************************************
//					IMAGE FUNCTIONS START
//*************************************************************
function swapImage(imgObj,img1,img2){
	if(imgObj.src.indexOf(img1) > 0){
		imgObj.src = img2;
	}
	else{
		imgObj.src = img1;
	}
}
//*************************************************************
//					IMAGE FUNCTIONS END
//*************************************************************





//*************************************************************
//					DISPLAY CLOCK START
//*************************************************************
var inactivityPeriod = 0;
function displayClock(expMin,userID){
	var now = new Date();
	var currHour = now.getHours();
	var currMin = now.getMinutes();
	var currSec = now.getSeconds();
	
	var monthArray = new Array();
	monthArray[0] = "Jan";
	monthArray[1] = "Feb";
	monthArray[2] = "Mar";
	monthArray[3] = "Apr";
	monthArray[4] = "May";
	monthArray[5] = "Jun";
	monthArray[6] = "Jul";
	monthArray[7] = "Aug";
	monthArray[8] = "Sep";
	monthArray[9] = "Oct";
	monthArray[10] = "Nov";
	monthArray[11] = "Dec";
	
	var dayArray = new Array();
	dayArray[0] = "Sun";
	dayArray[1] = "Mon";
	dayArray[2] = "Tue";
	dayArray[3] = "Wed";
	dayArray[4] = "Thu";
	dayArray[5] = "Fri";
	dayArray[6] = "Sat";
	
	var currDateStr = "";
	var currDay = dayArray[now.getDay()];
	var currMonthName = monthArray[now.getMonth()];
	
	currDateStr = currDay + " " + currMonthName + " " + now.getDate() + ", " + now.getYear();
	
	var displayTime = currDateStr + " " + (( currHour > 12) ? currHour - 12 : currHour);
	displayTime += ((currMin < 10) ? ":0" : ":") + currMin;
	displayTime += ((currSec < 10) ? ":0" : ":") + currSec;
	displayTime += ((currHour < 12) ? " AM" : " PM");
	
	clock.innerHTML = displayTime;
	
	inactivityPeriod += 1;
	if (inactivityPeriod >= expMin*60 && userID > 0){
		if(self.name != "main"){
			self.close();
		}
		else{
			window.location.href=webroot + '/default.asp?logout=true&msg=' + escape("Your session has timed out.");
		}
	}
	else if (inactivityPeriod == ((expMin*60) - 300) && userID > 0){
		// added focus and screen resize to timeout warning; increased timeout to 5 min prior - JR 03/16/04
		window.focus();
		//window.resizeTo(screen.availWidth, screen.availHeight)
		//window.moveTo(0,0);
		fnOpenModeless(webroot + '/secure/login/logoutMsg.asp',175,300,1,0,0);
		
	}
	setTimeout("displayClock(" + expMin + "," + userID + ")",1000);
}


// display message if window is closed without saving. To use, put the following line incased in script tags
// after the footer of a page: 
// window.onbeforeunload = closeWarning;
// have a function on the page set the variable below, allowNavigate, to true if you do not want this message 
// to appear. A good place to set this variable is in the form validation function.

var allowNavigate = false;
var navWarning = "";
function closeWarning(){
	if(!allowNavigate){
		event.returnValue = navWarning;
	}
}

//*************************************************************
//					DISPLAY CLOCK END
//*************************************************************




//*************************************************************
//					COOKIES START
//*************************************************************
//
//  Cookie Functions -- "Night of the Living Cookie" Version (25-Jul-96)
//
//  Written by:  Bill Dortch, hIdaho Design <bdortch@hidaho.com>
//  The following functions are released to the public domain.
//
//  This version takes a more aggressive approach to deleting
//  cookies.  Previous versions set the expiration date to one
//  millisecond prior to the current time; however, this method
//  did not work in Netscape 2.02 (though it does in earlier and
//  later versions), resulting in "zombie" cookies that would not
//  die.  DeleteCookie now sets the expiration date to the earliest
//  usable date (one second into 1970), and sets the cookie's value
//  to null for good measure.
//
//  Also, this version adds optional path and domain parameters to
//  the DeleteCookie function.  If you specify a path and/or domain
//  when creating (setting) a cookie**, you must specify the same
//  path/domain when deleting it, or deletion will not occur.
//
//  The FixCookieDate function must now be called explicitly to
//  correct for the 2.x Mac date bug.  This function should be
//  called *once* after a Date object is created and before it
//  is passed (as an expiration date) to SetCookie.  Because the
//  Mac date bug affects all dates, not just those passed to
//  SetCookie, you might want to make it a habit to call
//  FixCookieDate any time you create a new Date object:
//
//    var theDate = new Date();
//    FixCookieDate (theDate);
//
//  Calling FixCookieDate has no effect on platforms other than
//  the Mac, so there is no need to determine the user's platform
//  prior to calling it.
//
//  This version also incorporates several minor coding improvements.
//
//  **Note that it is possible to set multiple cookies with the same
//  name but different (nested) paths.  For example:
//
//    SetCookie ("color","red",null,"/outer");
//    SetCookie ("color","blue",null,"/outer/inner");
//
//  However, GetCookie cannot distinguish between these and will return
//  the first cookie that matches a given name.  It is therefore
//  recommended that you *not* use the same name for cookies with
//  different paths.  (Bear in mind that there is *always* a path
//  associated with a cookie; if you don't explicitly specify one,
//  the path of the setting document is used.)
//  
//  Revision History:
//
//    "Toss Your Cookies" Version (22-Mar-96)
//      - Added FixCookieDate() function to correct for Mac date bug
//
//    "Second Helping" Version (21-Jan-96)
//      - Added path, domain and secure parameters to SetCookie
//      - Replaced home-rolled encode/decode functions with Netscape's
//        new (then) escape and unescape functions
//
//    "Free Cookies" Version (December 95)
//
//
//  For information on the significance of cookie parameters, and
//  and on cookies in general, please refer to the official cookie
//  spec, at:
//
//      http://www.netscape.com/newsref/std/cookie_spec.html    
//
//******************************************************************
//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}
//
//  Function to correct for 2.x Mac date bug.  Call this function to
//  fix a date object prior to passing it to SetCookie.
//  IMPORTANT:  This function should only be called *once* for
//  any given date object!  See example at the end of this document.
//
function fixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of (Unix) time - should be 0
  if (skew > 0)  // Except on the Mac - ahead of its time
    date.setTime (date.getTime() - skew);
}
//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}
//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid. If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function deleteCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}
//*************************************************************
//					COOKIES END
//*************************************************************
