//common.js
//Version 2.0

//Declare global variables
$sPrefix 		= '../library/';
$aURL 			= new Array();

$aURL.Index 	= $sPrefix + 'index_ajax.php';

//************************************************************************************************************
function GetUrlVar($sVarName){

	var $aVars 		= [], $sHash;
	var $sHashes 	= window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

	for(var i = 0; i < $sHashes.length; i++){

		$sHash 				= $sHashes[i].split('=');
		$aVars.push($sHash[0]);
		$aVars[$sHash[0]] 	= $sHash[1];

	}

	return $aVars[$sVarName];

}

//************************************************************************************************************
function Set_Cookie($sName, $sValue, $sExpires, $sPath, $sDomain, $sSecure){

	// set time, it's in milliseconds
	var $oToday = new Date();

	$oToday.setTime( $oToday.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if($sExpires) $sExpires = $sExpires * 1000 * 60 * 60 * 24;

	var expires_date = new Date( $oToday.getTime() + ($sExpires) );

	document.cookie = $sName + "=" + escape($sValue) +
					( ( $sExpires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
					( ( $sPath ) ? ";path=" + $sPath : "" ) +
					( ( $sDomain ) ? ";domain=" + $sDomain : "" ) +
					( ( $sSecure ) ? ";secure" : "" );

}

//************************************************************************************************************
function Get_Cookie($sCheckName){

	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var $aAllCookies 	= document.cookie.split( ';' );
	var $aTempCookie 	= '';
	var $sCookieName 	= '';
	var $sCookieValue 	= '';
	var $bCookieFound 	= false; // set boolean t/f default f
	var $iCount;

	for($iCount = 0; $iCount < $aAllCookies.length; $iCount++){

		// now we'll split apart each name=value pair
		$aTempCookie = $aAllCookies[$iCount].split( '=' );


		// and trim left/right whitespace while we're at it
		$sCookieName = $aTempCookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if($sCookieName == $sCheckName){

			$bCookieFound = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if($aTempCookie.length > 1)
				$sCookieValue = unescape( $aTempCookie[1].replace(/^\s+|\s+$/g, '') );

			// note that in cases where cookie is initialized but no value, null is returned
			return $sCookieValue;
			break;

		}

		$aTempCookie = null;
		$sCookieName = '';

	}

	if(!$bCookieFound) return null;

	return false;

}

//************************************************************************************************************
function MinMaxDiv($sEle){

	var $oEle = $($sEle);

	$oEle.toggle();

	if($oEle.style.display == 'none') Set_Cookie('TicketsAdmin_TicketOptions', '1', 30, '/', '','');
	else Set_Cookie('TicketsAdmin_TicketOptions', '0', 30, '/', '','');

}

//************************************************************************************************************
//By Default binds only to TEXTAREA inputs, but set $sText to true to bind all TEXT inputs
function SpellCheckBind($sForm, $bText){

	var $oSpan;
	var $oDiv;
	var $oText;
	var $sMarkerText;
	var $aInputs = $($sForm).getElements();

	$bText = DefaultArg($bText, false);

	$aInputs.each(function($sEle){

		if($sEle.type == 'textarea' || ($sEle.type == 'text' && $bText))
			Event.observe($sEle, 'keypress', ActivateSpellCheck);

	});

	if (!$('SpellCheckAjaxReturn')) {

	 	$oSpan 		= document.createElement('span');
	 	$oSpan.id 	= 'SpellCheckAjaxReturn';
	 	document.body.appendChild($oSpan);

	 }

	$sMarkerText = ($bText) ? 'SPELLCHECK ALL' : 'SPELLCHECK TEXTAREA';

	$oDiv					= document.createElement('div');
	$oDiv.id				= 'SpellCheckMarker';
	$oText					= document.createTextNode($sMarkerText);
	$oDiv.className			= 'spellcheckmarker';
	$oDiv.appendChild($oText);
	document.body.appendChild($oDiv);

}

//************************************************************************************************************
function ActivateSpellCheck(){

	if(event.keyCode == 19) SpellCheck(this);

}

//************************************************************************************************************
function SpellCheck($sEle){

	var $sText = $F($sEle);

	if($sText.strip()) AjaxUpdater('ajaxCommand=SpellCheckAjax&sEle=' + $($sEle).name + '&sText=' +
		encodeURIComponent($sText), 'SpellCheckAjaxReturn', $aURL.Common);

}

//************************************************************************************************************
function DefaultArg($sArg, $sValue){

	return typeof($sArg) != 'undefined' ? $sArg : $sValue;

}

/**
 * Comma creates a comma-delimited list of an array
 */
//************************************************************************************************************
function Comma($aArray, $sReturn, $sPrefix, $sSuffix){

	$sReturn = DefaultArg($sReturn, '');
	$sPrefix = DefaultArg($sPrefix, '');
	$sSuffix = DefaultArg($sSuffix, '');

	var $sTemp = '';

	if(IsArray($aArray)){

		$aArray.each(function($s, $index){

			if($s.strip() == '') throw $continue;

			$sTemp = $sTemp + $sPrefix + $s + $sSuffix;

			if(typeof($aArray[$index + 1]) != 'undefined') $sTemp = $sTemp + ',';

		}
		);

	}
	else if($sReturn != '') $sTemp = $sPrefix + $sReturn + $sSuffix;

	return $sTemp;

}

//************************************************************************************************************
function DebugPage($sError){

	if(_PRODUCTION) return;

	var $oWin = window.open('', 'Error', 'location=0, toolbar=0, status=1, resizable=1, '
				+ 'width=500, height=500, scrollbars=1, top=50, left=50');
	$oWin.document.write($sError + '<br />');

}


//************************************************************************************************************
function Pointer($sEle){

	$sEle.style.cursor='pointer';

}

//************************************************************************************************************
function StoreValueInSession($sValue, $sVariable, $sFilter, $sUpdateTimeEle){

	var $bReturn;

	$sFilter 		= DefaultArg($sFilter, false);
	$sUpdateTimeEle	= DefaultArg($sUpdateTimeEle, false);
	$sUpdateTimeEle	= $sUpdateTimeEle ? '&sUpdateTime=' + $sUpdateTimeEle : '';

	if($sFilter){

	 	if(!InArray([32, 13, 190, 10, 188, 8], window.event.keyCode)) return false;

	}

	$bReturn = AjaxUpdater('ajaxCommand=StoreValueInSession&sTempVariable=' + encodeURIComponent($sVariable) +
				'&sTempValue=' + encodeURIComponent($sValue) + $sUpdateTimeEle, 'Dirty', $aURL.Common);

	return $bReturn;

}

//************************************************************************************************************
function HideAll(){

	['day1', 'day2', 'day3', 'day4', 'day5'].each(function($sDay){

		$($sDay).hide();

	});

	Form_KeepAlive();

}

//************************************************************************************************************
function CloseRecord($sTable, $iID){

	AjaxUpdater('ajaxCommand=CloseRecord&iID=' + $iID + '&sTable=' + $sTable, 'Dirty', $aURL.Common,
		'false', 'get', 'false');

}

//************************************************************************************************************
function MonitorFormChange($sForm){

	Form.getElements($sForm).each(function($sEle){

		$sEle.observe('change', function(){ $('hdnChanged').value = 1; });

	});

}

//************************************************************************************************************
function DisableFieldsByPrefix($sForm, $sPrefix){

	$aFields = GetFormElementNamesbyPrefix($sForm, $sPrefix);

	$aFields.each(function($s){

		$($s).disable();

	});

}

//************************************************************************************************************
function SignDay($iID, $iDay, $iUserID, $sForm){

	AjaxUpdater('ajaxCommand=SignDayAjax&iID=' + $iID + '&iDay=' + $iDay + '&iUserID=' + $iUserID +
				'&sForm=' + $sForm, 'sig' + $iDay, $aURL.Forms, 'true', 'get');

}

//************************************************************************************************************
function SignDayDelete($iID, $iDay, $iUserID, $sForm){

	AjaxUpdater('ajaxCommand=SignDayAjaxDelete&iID=' + $iID + '&iDay=' + $iDay + '&iUserID=' + $iUserID +
				'&sForm=' + $sForm, 'sig' + $iDay, $aURL.Forms, 'true', 'get');


}

//************************************************************************************************************
function Load_AutoCompleteUser($sFunc){

	$myAjax = new Ajax.Autocompleter("autocomplete_name", "autocomplete_name_choices",
				"/library/common.php?ajaxCommand=UserLookup",
				{afterUpdateElement: $sFunc, minChars: 2});

}

//************************************************************************************************************
function Load_AutoCompletePatientDocuments($sFunc){

	$myAjax = new Ajax.Autocompleter('autocomplete_name', 'autocomplete_name_choices',
				'/library/common.php?ajaxCommand=PatientLookupDocuments',
				{afterUpdateElement: $sFunc});

}

//************************************************************************************************************
function Load_AutoComplete($sFunction, $sLookupFunction, $sCompleteType){

	$sCompleteType 	= typeof($sCompleteType) != 'undefined' ? '_' + $sCompleteType : '';

	$myAjax 		= new Ajax.Autocompleter('autocomplete' + $sCompleteType + '_name',
						'autocomplete' + $sCompleteType + '_name_choices',
						'/library/common.php?ajaxCommand=' + $sLookupFunction + '&sCompleteType=' +
						$sCompleteType,
						{afterUpdateElement: $sFunction,
						paramName: 'autocomplete' + $sCompleteType + '_parameter_name'});

}

//************************************************************************************************************
function Load_AutoCompleteProvider($sFunc){

	$myAjax = new Ajax.Autocompleter("autocomplete_provider_name", "autocomplete_provider_name_choices",
				"/library/common.php?ajaxCommand=ProviderLookup",
				{afterUpdateElement: $sFunc, minChars: 2});

}

//************************************************************************************************************
function Load_AutoCompletePatient($sFunc){


	var $myAjax = new Ajax.Autocompleter("autocomplete_name", "autocomplete_name_choices",
					"/library/common.php?ajaxCommand=PatientLookup",
					{afterUpdateElement: $sFunc, minChars: 2});

	return $myAjax;

}

//************************************************************************************************************
function Load_AutoCompleteTicket($sFunc){

	var $myAjax = new Ajax.Autocompleter("autocomplete_ticket_name", "autocomplete_ticket_name_choices",
				"/library/common.php?ajaxCommand=TicketLookup",
				{callback: function($x, $s){ return $s + '&chkDescription=' +
					$('chkDescription').checked; }, afterUpdateElement: $sFunc, minChars: 2,
					indicator: 'indicator1'});

	return $myAjax;

}

//************************************************************************************************************
function ResetJump($sValue, $obj){

	$($obj).selectedIndex 	= 0;
	window.top.location 	= $sValue;

}

//************************************************************************************************************
function ShowD($s){

	if($('a' + $s).innerHTML == '+') $('a' + $s).innerHTML='-';
	else $('a' + $s).innerHTML='+';

	$('d' + $s).toggle();

}

//************************************************************************************************************
function EmailNotificationAjax($sMessage, $sSubject, $sTo, $sFrom, $sCC){

	if(typeof($sMessage) == 'undefined') return false;

	$sSubject 	= DefaultArg($sSubject, 'Test');
	$sTo 		= DefaultArg($sTo, 'it@pridedallas.com');
	$sFrom 		= DefaultArg($sFrom, 'app01@pridedallas.com');
	$sCC 		= DefaultArg($sCC, '');

	var $sPars	= 'ajaxCommand=EmailNotificationAjax&sMessage=' + $sMessage + '&sSubject=' + $sSubject +
					'&sTo=' + $sTo + '&sFrom=' + $sFrom + '&sCC=' + $sCC;

	AjaxUpdater($sPars, 'MessageResults', $aURL.Common);

	return true;

}

//************************************************************************************************************
function ConfirmAndSubmit($sText, $sName, $sValue, $sFormName){

	$sFormName 	= typeof($sFormName) != 'undefined' ? $sFormName : 'frmMain';

	var $sConfirm = confirm($sText);

	if($sConfirm){

		$('hdncomphere').innerHTML = '<input type="hidden" name="' + $sName + '"' +
								'value="' + $sValue + '">';
		$($sFormName).submit();

	}

}

//************************************************************************************************************
function DelConfirm($sLastName, $sFirstName, $sCase, $sEpisode, $sID){

	var $sConfirm = confirm('Are you sure you want to delete ' + $sLastName + ', ' + $sFirstName +
					' (' + $sCase + ' - ' + $sEpisode + ')');

	if($sConfirm){

		$('hdndelhere' + $sID).innerHTML = '<input type="hidden" name="cmdDelete" value="Delete">';
		window.document.forms('frmUpdate' + $sID).submit('test');

	}
}

//************************************************************************************************************
function MarkOPNOPC($iSkey, $sType){

	if($iSkey == '') return;

	var $sDate = $F('hdnEndDate' + $iSkey);

	if($sDate == ''){

		alert('No End Date entered!');
		return;

	}
	else{

		$sConfirm = confirm('Mark patient ' + $sType + ' and enter discharge date of ' + $sDate + ' ?');

		if($sConfirm){

			AjaxUpdater('ajaxCommand=MarkOPNOPC&iSkey=' + $iSkey + '&sDate=' + $sDate + '&sType=' +
				$sType, 'results', $aURL.OPT, 'false', 'get');

		}

	}

}

//************************************************************************************************************
function MarkORD($iSkey){

	if($iSkey == '') return;

	var $sConfirm = confirm('Mark patient ORD?');

	if($sConfirm){

		AjaxUpdater('ajaxCommand=MarkORD&iSkey=' + $iSkey, 'results', $aURL.OPT, 'true', 'get');

	}

}

//************************************************************************************************************
function LoadGrid($sPage, $s, $iRowOffset){

	AjaxUpdater('sFunction=LoadGrid&s=' + $s + '&iRowOffset=' + $iRowOffset, 'Grid', $aURL[$sPage], 'false',
		'get');

}

//************************************************************************************************************
function ShowGrid($sForm, $sParam1){

	if($sForm + '' == ''){

		alert('Form not specified!');

		return false;

	}

	AjaxUpdater('ShowGrid=Grid&sForm=' + $sForm + '&param1=' + $sParam1, 'Grid', $aURL.FormMaint, 'false',
		'get');

	return true;

}

//************************************************************************************************************
function AddSlashesJS($s) {

	if($s === null) return '';
	else if(IsInt($s)) return $s;
	else{

		$s = $s.replace(/\'/g,"\\'");
		$s = $s.replace(/\"/g,'\\"');
		$s = $s.replace(/\\/g,'\\\\');
		$s = $s.replace(/\0/g,'\\0');

	}

	return $s;

}

//************************************************************************************************************
function CleanForURL($s) {

	if($s === null) return '';
	else if(IsInt($s)) return $s;
	else{

		$s = $s.replace(/\'/g,'%27');
		$s = $s.replace(/\"/g,'%22');
		$s = $s.replace(/\\/g,'%5C');
		$s = $s.replace(/\\/g,'%5C');
		$s = $s.replace(/&/g, '%26');
		$s = $s.replace(/\?/g, '%3F');
		$s = $s.replace(/#/g, '%23');
		$s = $s.replace(/ /g, '%20');

	}

	return $s;

}

//************************************************************************************************************
function StripSlashesJS($s) {

	if($s === null) return '';
	else if(IsInt($s)) return $s;
	else{

		$s=$s.replace(/\\'/g,'\'');
		$s=$s.replace(/\\"/g,'"');
		$s=$s.replace(/\\\\/g,'\\');
		$s=$s.replace(/\\0/g,'\0');

	}

	return $s;

}

//************************************************************************************************************
function PageBreak3($sElementClass, $iPageLength, $sForceBreak1, $sHeader){

	if($iPageLength == '') $iPageLength = 900; 	//Total Page Length

	var $iCurrentTotalLength 	= 0; 	//Total length of current elements on page
	var $iElementLength			= 0;	//Element Length
	var $aSec = window.document.getElementsByClassName($sElementClass);	//Get elements by class

	for($i = 0; $i < $aSec.length; $i ++){

		if($aSec[$i]){

			$iCurrentTotalLength 	= $iCurrentTotalLength + $aSec[$i].offsetHeight;
			$iElementLength			= $aSec[$i].offsetHeight;

			if($aSec[$i].id == $sForceBreak1) {

			   	$aSec[$i].style.pageBreakBefore = "always";
			   	$iCurrentTotalLength = 0;

			}
			else{

			   	if($iCurrentTotalLength > ($iPageLength)) {

					if(typeof($sHeader) != 'undefined') {

					 	new Insertion.Before($aSec[$i], $sHeader);
					 	$iCurrentTotalLength = $aSec[$i].offsetHeight;

					 }
					 else {

					 	$aSec[$i].style.pageBreakBefore = "always";
					 	$iCurrentTotalLength = $aSec[$i].offsetHeight;

					 }

			   	}

			}

		}

	}

}

//Open window, except if blank********************************************************************************
function JumpCBO($sEle){

	if($sEle != '') location = $F($sEle);

}

//Maximize window*********************************************************************************************
function Maximize(){

	window.moveTo(0,0);
	window.resizeTo(screen.width,screen.height);

}

//************************************************************************************************************
function JumpCHK($sLoc, $oEle){

	var $sChecked;

	if($oEle.checked) $sChecked = '?' + $oEle.name + '=on';
	else $sChecked = '?' + $oEle.name + '=off';

	location = $sLoc + $sChecked;

}

//************************************************************************************************************
function PopUp($sURL, $iWidth, $iHeight, $iScroll, $iResize, $sID) {

	var $oDay = new Date();
	var $oPage;

	$sID = DefaultArg($sID, $oDay.getTime());

	$oPage = window.open($sURL, $sID, 'toolbar=0,scrollbars=' + $iScroll +
				',location=0,status=1,menubar=0,resizable=' + $iResize + ',width=' + $iWidth +',height=' +
				$iHeight + ',left=10,top=10');

	return $sID;

}

//************************************************************************************************************
function HighlightElementOn($sEle, $sChangeText){

	$sChangeText 					= ($sChangeText == 'true') ? 'Click to Change' : '';
	$($sEle).style.cursor			= 'pointer';
	$($sEle).style.backgroundColor	= '#FFFF00';

	if($sChangeText) ddrivetip($sChangeText, 100);

}

//************************************************************************************************************
function HighlightElementOff($sEle, $sBGColor){

	$sBGColor 					= typeof($sBGColor) != 'undefined' ? $sBGColor : '#D9DFDB';
	$($sEle).style.backgroundColor 	= $sBGColor;

	if(typeof(tipobj) != 'undefined') hideddrivetip();

}

//************************************************************************************************************
function PopUpDialog($sURL, $sID, $sScroll, $sStatus) {

	day 		= new Date();
	$sID 	= typeof($sID) != 'undefined' ? $sID : day.getTime();
	$sScroll 	= typeof($sScroll) != 'undefined' ? $sScroll : 0;
	$sStatus 	= typeof($sStatus) != 'undefined' ? $sStatus : 0;

	window.open($sURL, $sID, 'toolbar=0,scrollbars=' + $sScroll +
		',location=0,status=' + $sStatus + ',menubar=0,resizable=0,width=50,height=50,left=10,top=10');

}

//************************************************************************************************************
function FindEvent($sURL, $sMonth, $sYear, $sENOrgID, $sTitle) {

	window.open($sURL,'','width=535,height=400,directories=no,location=no,menubar=no,scrollbars=yes,' +
		'resizable=no');
	location = "/community/department/default.asp?Orgid=" + $sENOrgID + "&DeptTitle=" + $sTitle
		+ "&App=9&SC=Y&month=" + $sMonth + "&year=" + $sYear;

}

//************************************************************************************************************
function TimeOut($sFunction, $sTime){

    setTimeout($sFunction, $sTime  * 1000);

}

//************************************************************************************************************
function RefreshPage(){

	var $sURL = unescape(location);
	location.replace($sURL);

}

//************************************************************************************************************
function IsArray($oObj) {

   if ($oObj.constructor.toString().indexOf("Array") == -1) return false;
   else return true;

}

//Open report window******************************************************************************************
function ReportOpen($sReport){

	if($sReport != ''){

		window.open('/' + $sReport,'reporting_all', 'channelmode=yes, toolbar=yes, location=no, ' +
			'menubar=no, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

	}

}

//************************************************************************************************************
function RM5DataUpdateAjax($skey, $sNoReload){

	if($skey == 'All') $sPars = 'all=all';
	else $sPars = 'all_skey=' + $skey;

	AjaxUpdater($sPars, 'RM5DataUpdateHTML', '../library/rm5_data_update_code.php', 'false');

	if($sNoReload === true) return;
	else window.location.reload();

}

//************************************************************************************************************
function UpdateSchedules(){

	AjaxUpdater('ajaxFunction=PatientSchedules', 'UpdateSchedules', '../library/rm5_data_update_code.php',
		'false', 'get');

	window.location.replace(window.document.URL);

}

//************************************************************************************************************
//Generic Ajax Updater
//Async Default 		= true
//Method Default 		= POST
//EvalScripts Default 	= true
//************************************************************************************************************
function AjaxUpdater($sPars, $sID, $sURL, $sAsync, $sMethod, $sEvalScripts){

	$sMethod 		= (typeof($sMethod) == 'undefined' || ($sMethod != 'get' && $sMethod != 'post')) ?
						'post' : $sMethod;
	$sAsync 		= (typeof($sAsync) == 'undefined' || ($sAsync != 'true' && $sAsync != 'false')) ?
						'true' : $sAsync;
	$sEvalScripts 	= (typeof($sEvalScripts) == 'undefined' || ($sEvalScripts != 'true' &&
						$sEvalScripts != 'false')) ? 'true' : $sEvalScripts;

	$sAjax 			= new Ajax.Updater(AjaxID($sID), $sURL, { method: $sMethod, asynchronous: $sAsync,
						evalScripts: $sEvalScripts, parameters: $sPars });

	return $sAjax;

}

//************************************************************************************************************
function AjaxID($sEle, $sEleType){

	$sEle		= DefaultArg($sEle, 'AjaxIDPlaceHolder53542354');
	$sEleType 	= DefaultArg($sEleType, 'span');

	if(!$($sEle)){

	 	var $oEleID = window.document.createElement($sEleType);

	 	$oEleID.id	= $sEle;
	 	document.body.appendChild($oEleID);

	}

	return $sEle;

}

//************************************************************************************************************
function Landscape($sReport){

	if($sReport == 'Phase3and4'){

		$('phase3results').style.width = '960px';
		$('title').style.fontSize = "24px";
		$aTD = window.document.getElementsByClassName('phase3');

		for($i = 0; $i < $aTD.length; $i ++) $aTD[$i].style.fontSize = '20px';

		$aTD = window.document.getElementsByClassName('subheading');

		for($i = 0; $i < $aTD.length; $i ++) $aTD[$i].style.fontSize = '20px';

		$aTD = window.document.getElementsByClassName('header');

		for($i = 0; $i < $aTD.length; $i ++) $aTD[$i].style.fontSize = '20px';

	}

	window.print();

}

//************************************************************************************************************
function NewCal($sEle){

	if($($sEle)){

		//This variable has to be global
		cal1				= new calendar2($($sEle));
		cal1.year_scroll 	= true;
		cal1.time_comp 		= false;

	}

}

//************************************************************************************************************
function Dirty(){

	$('Dirty').innerHTML = '...';

}

//************************************************************************************************************
function IsInt(s){

	return (s.toString().search(/^-?[0-9]+$/) == 0);

}

//This is now the only UpdateField function that should be used.
//1 Argument: 	$($sField).name || $sName
//2 Arguments:	$($sField).name || $sName, $sValue
//3 Arguments: 	$($sField).name || $sName, $sTable, $id, $sValue
//4 Arguments:	$($sField).name || $sName, $sValue
//Arguments not specified will be assigned as follows:
//$sValue	= $F($sField)
//$sTable	= $F('sForm')
//$iID		= $F('id')
//************************************************************************************************************
function UpdateField($vArg0, $vArg1, $vArg2, $vArg3){

	var $sName 			= '';
	var $sFieldData 	= '';
	var $sFieldNames	= '';

	//Determine if $vArg0 is a form element
	var $bArg0IsFormElement = false;

	if($($vArg0) && typeof($($vArg0).type) != 'undefined') $bArg0IsFormElement = true;

	//Clear Dirty marker
	$(AjaxID('Dirty')).update('');

	//If $sField is not an element, use $sField as the field name
	if(!$bArg0IsFormElement) $sName = $vArg0;
	else $sName = $($vArg0).name;

	//If $sValue isn't passed, use $F($sField)
	if(typeof($vArg3) == 'undefined'){

		if(arguments.length == 2) {

			$vArg3 = $vArg1;

			if($('sForm')) $vArg1 = $F('sForm');

			if($('id')) $vArg2 = $F('id');

		}
		else if($bArg0IsFormElement){

			if($($vArg0).type == 'checkbox' && $($vArg0).checked === false) $vArg3 = '';
			else $vArg3 = $F($vArg0);

		}

	}

	$sFieldNames 	= 'sFieldNames=' + $sName;
	$sFieldData	= '&sFieldData=' + CleanForURL($vArg3);
	$vArg1 		= '&sForm=' + DefaultArg($vArg1, $('sForm') ? $F('sForm') : '');
	$vArg2 		= '&ID=' + DefaultArg($vArg2, $('id') ? $F('id') : '');

	if($vArg1 == '&sForm=' || $vArg2 == '&ID='){

		alert('Missing Table Name or ID: ' + $vArg1 + ', ' + $vArg2 +
				'. Administrator to be notified.');
		EmailNotificationAjax('<strong>Page: </strong>' + location.pathname +
			'<br /><strong>Error: </strong>Missing Table Name or ID<br /><strong>$vArg1: </strong>' +
			CleanForURL($vArg1) + '<br /><strong>$vArg2: </strong>' + CleanForURL($vArg2),
			'UpdateField Error');

		return false;

	}


	if($('modified_by_field')){

		$sFieldNames 	= $sFieldNames + '|||' + $F('modified_by_field');
		$sFieldData 	= $sFieldData + '' + '|||' + $F('modified_by_value');

	}

	var $sPars = encodeURI($sFieldNames + $sFieldData  + $vArg2 + $vArg1 + '&ajaxCommand=UpdateFields');

	AjaxUpdater($sPars, AjaxID('Dirty'), $aURL.Forms, 'false', 'post');

	return true;

}

//************************************************************************************************************
function HighlightRadioText($sEle, $iKey, $sID){

	if($sEle.checked){

		$aEle = document.getElementsByClassName($sID);

		$aEle.each(function($s){

			$($s).style.backgroundColor = '#D9DFDB';

		});

		$($sID + $iKey).style.backgroundColor = '#FFFF00';

	}

}

//************************************************************************************************************
function RM5DataUpdateAjaxFunction($sFunction, $sParam1, $sAsync){

	$sAsync = ($sAsync == 'false') ? 'false' : 'true';

	AjaxUpdater('ajaxFunction=' + $sFunction + '&param1=' + $sParam1, 'RM5DataUpdateHTML',
		'../library/rm5_data_update_code.php', $sAsync, 'get');

}

//Show element ($item) when select option ($index) is matched ($match)****************************************
function ShowItemCBO($index, $match, $item){

	$sMatchNoMatch = false;

	if(IsArray($match)){

		for($i = 0; $i < $match.length; $i ++)
			if($index == $match[$i]) $sMatchNoMatch = true;

	}
	else if($index == $match) $sMatchNoMatch = true;

	if($sMatchNoMatch) $($item).show();
	else{

		$($item).hide();
		$($item).value = '';

	}

}

//Show element ($item) when select option ($index) is matched ($match)****************************************
function ShowItem($value, $match, $item){

	if($value == $match) $($item).show();
	else $($item).hide();

}

//Show and Hide element when box is checked and unchecked*****************************************************
function ShowItemCHK($sChk, $sID){

	if(($($sChk).checked) === true) $($sID).show();
	else $($sID).hide();

}

//Clear a text box if Checkbox is not checked*****************************************************************
function ClearTextIfNotChecked($sChkID, $sTextID){ if($($sChkID) != true) $($sTextID).value = ''; }

//Clear a text box if Checkbox is checked*********************************************************************
function ClearTextIfChecked($sChkID, $sTextID){ if($($sChkID).checked === true) $($sTextID).value = ''; }

//Check box if Text is changed********************************************************************************
function CheckIfTextChanged($sTextID, $sChkID){

	if($F($sTextID)){

	 	$($sChkID).checked = true;
		UpdateField($sChkID);

	 }
	 else{

	 	$($sChkID).checked = false;
		UpdateField($sChkID);

	 }

}

//Uncheck box if Text is changed******************************************************************************
function UnCheckIfTextChanged($sTextID, $sChkID){

	if($F($sTextID) == '') $($sChkID).checked = true;
	else $($sChkID).checked = false;

}

//************************************************************************************************************
function ClearSubs($sField){

	if($($sField).checked == true) return;

	var $aFields = GetFormElementNamesbyPrefix('frmMain', $sField);

	var $sFieldNames 	= '';
	var $sFieldData 	= '';

	$aFields.each(function($sField){

		$($sField).checked 	= false;
		$($sField).value	= '';

		$sFieldNames 	= $sFieldNames + $($sField).name + '|||';
		$sFieldData	= $sFieldData + '' + '|||';

	});

	if($sFieldNames) $sFieldNames = $sFieldNames.substr(0, $sFieldNames.length - 3);

	if($sFieldData) $sFieldData = $sFieldData.substr(0, $sFieldData.length - 3);

	AjaxUpdater('sFieldNames=' + $sFieldNames + "&sFieldData=" + CleanForURL($sFieldData) + '&ID=' +
		$F('id') + '&sForm=' + $F('sForm') + '&ajaxCommand=UpdateFields', 'Dirty',
		$aURL.Forms);

}

//************************************************************************************************************
//Pass $iID = 0 if ID is unknown
function FormOpen($iID, $iFormNum, $iSkey, $sForm, $sNoReload, $sFormName, $sNew){

	$sFormName = typeof($sFormName) != 'undefined' ? $sFormName : $sForm;

	if($sNew == true){

		var $answer = confirm('Create a new ' + $sFormName + '?');

		if($answer === false) return;

	}

	if($sForm == 'inf'){

		var $sURL = '/form.php?id=' + $iID + '&sForm=' + $sForm;

		if($iID > 0){

			window.open($sURL,'form1', 'channelmode=yes, toolbar=yes, ' +
				'location=no, menubar=no, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

			if($('cboCaseNumStatus')) $('cboCaseNumStatus').value='';

		}
		else alert('ID is missing!');

	}
	else{

		$sURL = '/form.php?id=' + $iID + '&skey=' + $iSkey + '&sForm=' + $sForm + '&iFormNum=' + $iFormNum;

		if($iID || $iSkey){

			window.open($sURL,'form1', 'channelmode=yes, toolbar=yes, ' +
				'location=no, menubar=no, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

			if($('cboCaseNumStatus')) $('cboCaseNumStatus').value='';

		}
		else alert('ID and Skey missing!');

	}

	if(!$sNoReload) location.reload();

}

//************************************************************************************************************
function FormOpenNoSession($iID, $iFormNum, $iSkey, $sForm, $sNoReload, $sFormName, $sNew){

	$answer = true;

	if($sNew == true) $answer = confirm('Create a new ' + $sFormName + '?');

	if($answer === false) return;

	//For opening the form without session set
	$sForm = ($sForm != '') ? '&sForm=' + $sForm : '';

	$sURL = '/form.php?id=' + $iID + '&skey=' + $iSkey + $sForm + '&iFormNum=' + $iFormNum;

	if($iID || $iSkey){

		window.open($sURL,'form1', 'channelmode=yes, toolbar=yes, ' +
			'location=no, menubar=yes, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

		if($('cboCaseNumStatus')) $('cboCaseNumStatus').value='';

	}
	else alert('ID or Skey missing!');

	if($sNoReload != true) location.reload();

}

//************************************************************************************************************
function Debug($s){

	if(!_PRODUCTION) alert($s);

}

//************************************************************************************************************
function PrintNotes($sID, $sForm){

	if($sID != ''){

		window.open('/form_notes.php?id=' + $sID + '&sForm=' + $sForm, 'form_notes1',
			'channelmode=yes, toolbar=no,' +
			'location=no, menubar=no, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

	}

}

//Open report window******************************************************************************************
function FormReportOpen($sID, $sForm, $sOverwrite){

	var $sURL 		= 'library/load_report.php';
	var $sReport	= 'reports/saved/' + $sForm + '/' + $sID + '.htm';

	if($sID != '' && $sID != null){

		$sURL = '/' + $sURL + '?id=' + $sID + '&sReport=' + $sReport + '&sForm=' + $sForm +
				'&sOverwrite=' + $sOverwrite;

		window.open($sURL, 'form_report',
			'channelmode=yes, toolbar=yes, location=no, menubar=no, scrollbars=yes, ' +
			'resizable=yes, fullscreen=no, status=yes');

		if($('cboCaseNumStatus')) $('cboCaseNumStatus').value='';

	}

}

//Open report window for Medical Summary for all of indicated group*******************************************
function MSUGroupReport($sGroup){

	window.open('/reports/report_msu_week_v1.php?$sGroup=' + $week,'form_report', 'channelmode=yes, ' +
		'toolbar=yes, location=no, menubar=no, scrollbars=yes, resizable=yes, fullscreen=no, status=yes');

}

//Supress form submission by Enter key************************************************************************
function CheckEnter($e){ //$e is event object passed from function invocation

	//if which property of event object is supported (NN4)
	if($e && $e.which){

			$e 			= $e;
			characterCode 	= $e.which;

	}//character code is contained in NN4's which property
	else{

		$e 			= event;
		characterCode 	= $e.keyCode;

	}//character code is contained in IE's keyCode property

	//if generated character code is equal to ascii 13 (if enter key)
	if(characterCode == 13) return false;
	else return true;

}

//************************************************************************************************************
function GetFormElementNamesbyPrefix($sFormName, $sPrefix){

	$aFormFields 	= $($sFormName).getElements();
	$aReturn		= new Array();

	$aFormFields.each(function($sField){

		if($sField.name.startsWith($sPrefix)) $aReturn[$aReturn.length] = $sField;

	});

	return $aReturn;

}

//************************************************************************************************************
function InArray($aArray, $sMatch){

	for($x = 0; $x <= $aArray.length; $x ++){

		if($aArray[$x] == $sMatch) return true;

	}

	return false;
}

//************************************************************************************************************
function GetSerializedFieldDatabyPrefix($sFormName, $sPrefix){

	$aFormFields 	= GetFormElementNamesbyPrefix($sFormName, $sPrefix);
	$sReturn		= '';

	$aFormFields.each(function($sField){

		$sReturn = $sReturn + '&' + $sField.name + '=' + $F($sField);

	});

	return $sReturn;

}

//Clear a TEXT value******************************************************************************************
function ClearValue($sClearID, $sCurrentID, $sNoClearID){

	if($($sCurrentID) != $sNoClearID) $($sClearID).value = '';

}

//************************************************************************************************************
function EditForm($sPage, $sCommand, $sField){

	//If Report was pressed, save the form first
	if($sCommand == 'Report') EditForm($sPage, 'UpdateReport', $sField);

	if($($sField)) $skey = $F($sField);
	else $skey = $sField;

	if($sCommand == 'Update' || $sCommand == 'UpdateReport'){

		$sResults 	= 'MessageResults';
		$sPars 	= 'ajaxCommand=Update&skey=' + $skey + '&' + Form.serialize('frmPatient');

	}
	else{

		$sResults	= 'PatientResults';
		$sPars 	= 'ajaxCommand=' + $sCommand + '&skey=' + $skey;

	}

	AjaxUpdater($sPars, $sResults, $aURL[$sPage], 'false');

	if($sCommand == 'Update')
		AjaxUpdater('ajaxCommand=EditForm&skey=' + $skey, 'PatientResults', $aURL[$sPage], 'false');

}

//************************************************************************************************************
function SaveForm($sTable, $sField){

	AjaxUpdater('ajaxCommand=Update&sTable=' + $sTable + '&skey=' + $F($sField) + '&' +
		Form.serialize('frmPatient'), 'MessageResults', 'library/save_form_ajax.php', 'false');

}

//************************************************************************************************************
function Complete($sPage, $ID, $skey){

	$sConfirm = confirm('Mark this record complete?');

	if(!$sConfirm) return;

	if($sPage != 'Psych') EditForm($sPage, 'Update', $skey);

	AjaxUpdater('ajaxCommand=Complete&ID=' + $F($ID) + '&skey=' + $F($skey), 'MessageResults', $aURL[$sPage],
		'false');

	ReportNoUpdate($F($skey), 'Psych');

}

//************************************************************************************************************
function OnHold($sPage, $skey){

	$oConfirm	= confirm('Place patient on hold? This will mark the patient HOLD and remove any ' +
				'Phase and Treatment Schedule dates not attended.');

	if(!$oConfirm) return;

	AjaxUpdater('ajaxCommand=OnHold&skey=' + $skey, 'PlaceOnHold', $aURL[$sPage], 'false');

	EditForm($sPage, 'EditForm', $skey);

}

//************************************************************************************************************
function ReportNoUpdate($skey, $sPage){

	AjaxUpdater('ajaxCommand=Report&skey=' + $skey, 'PatientResults', $aURL[$sPage], 'false');

}

//************************************************************************************************************
function CheckDate($sValue, $sID){

	return;

	$aDays = new Array('a', 'b', 'c', 'd', 'e');

	$oDate = new Date($sValue + ' 00:00:00');

	$sCorrectDay = $sID.charAt($sID.length - 1);

	if($aDays[$oDate.getDay() - 1] != $sCorrectDay){

		alert("Your date is does not match the DAY selected.");
		$($sID).value = '';

	}


}

//************************************************************************************************************
function CheckClear($ID){

	if($($ID).checked === false){

		$sInput = '<input type="hidden" name="' + $ID.name + '" value="">';
		new Insertion.Before($ID.name, $sInput);

	}

}