//Declare root namespace
if (!PRIDE) var PRIDE = new Object();
if (!PRIDE.COMMON) PRIDE.COMMON = new Object();
if (!PRIDE.URL) PRIDE.URL = new Object();

PRIDE.URL.AjaxURL = '../library/ajax.php';

//************************************************************************************************************
PRIDE.COMMON = {

	iCurrentTotalLength:0,

	//*******************************************************************************************************
	/**
	 * Get all input/select/textarea elements from page (no form used)
	 * convert to URL and pass to $sPage
	 * @param $sPage Page to submit variables to
	 */
	submitPage:function ($sPage) {

		var $aInputs;
		var $sURL = '';

		$aInputs = $$('input', 'select', 'textarea');

		$aInputs.each(
			function ($oEle) {

				$sURL += $oEle.name + '=' + encodeURIComponent($oEle.value) + '&';

			}
		);

		location.href = $sPage + '?' + $sURL.substr(0, $sURL.length - 1);

	},

	//*******************************************************************************************************
	DaysInMonth:function ($iMonth, $iYear) {

		var $iMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

		if ($iMonth != 2) return $iMonthDays[$iMonth - 1];

		if ($iYear % 4 != 0) return $iMonthDays[1];

		if ($iYear % 100 == 0 && $iYear % 400 != 0) return $iMonthDays[1];

		return $iMonthDays[1] + 1;

	},

	loadJSCSSFile:function ($sFileName) {

		var $oFileElement;

		if ($sFileName.match('.js')) {

			$oFileElement = document.createElement('script');

			$oFileElement.setAttribute('type', 'text/javascript');
			$oFileElement.setAttribute('src', '/javascript/' + $sFileName);

		}
		else if ($sFileName.match('.css')) {

			$oFileElement = document.createElement('link');

			$oFileElement.setAttribute('rel', 'stylesheet');
			$oFileElement.setAttribute('type', 'text/css');
			$oFileElement.setAttribute('href', '/css/' + $sFileName);

		}

		if (typeof($oFileElement) != 'undefined') $$('head')[0].appendChild($oFileElement)

	},

	//*******************************************************************************************************
	QueryStringGet:function () {

		return window.location.href.slice(window.location.href.indexOf('?') + 1).toString();

	},

	//*******************************************************************************************************
	QueryStringReplace:function ($sVar, $sValue) {

		var $sQueryString = this.QueryStringGet();
		var $sNewLocation = null;
		var $oRegEx = new RegExp("(" + $sVar + "=)([a-zA-Z0-9%]*[^&])");

		if ($sQueryString.match($sVar))
			$sNewLocation = location.pathname + '?' +
			                $sQueryString.replace($oRegEx, '$1' + $sValue);
		else $sNewLocation = location.pathname + '?' + $sVar + '=' + $sValue;

		location.href = $sNewLocation;

	},

	//*******************************************************************************************************
	/**
	 * @param $sSQL
	 * @param $sAsync
	 * @param $sSelectUpdateEle
	 * @param $sOnComplete
	 * @return void
	 */
	SendSQL:function ($sSQL, $sAsync, $sSelectUpdateEle, $sOnComplete) {

		$sAsync = DefaultArg($sAsync, true);

		AjaxUpdater(
			'ajaxObject=PRIDE' +
			'&ajaxMethod=SendSQL' +
			'&sCommonSQL=' + encodeURIComponent($sSQL) +
			'&sSelectUpdateEle=' + $sSelectUpdateEle,
			'Common_SendSQL_Message',
			PRIDE.URL.PHPClass,
			$sAsync,
			null,
			true,
			$sOnComplete);

	},

	//*******************************************************************************************************
	/**
	 * @param $sElementClass
	 * @param $iPageLength
	 * @param $sForceBreak1
	 * @param $sHeader
	 * @return void
	 */
	PageBreak3:function ($sElementClass, $iPageLength, $sForceBreak1, $sHeader) {

		var $aElement = $$('[class=' + $sElementClass + ']');

		$aElement.each(
			function ($s) {
				PRIDE.COMMON.PageBreakHere($s, $iPageLength, $sForceBreak1, $sHeader);
			}
		);

	},

	//*******************************************************************************************************
	/**
	 * @param $sElement
	 * @param $iPageLength
	 * @param $sForceBreak1
	 * @param $sHeader
	 * @return void
	 */
	PageBreakHere:function ($sElement, $iPageLength, $sForceBreak1, $sHeader) {

		this.iCurrentTotalLength += $sElement.offsetHeight;

		if ($sElement.id == $sForceBreak1) {

			$sElement.style.pageBreakBefore = "always";
			this.iCurrentTotalLength = 0;

		}
		else {

			if (this.iCurrentTotalLength > ($iPageLength)) {

				if (typeof($sHeader) != 'undefined') {

					new Insertion.Before($sElement, $sHeader);
					this.iCurrentTotalLength = $sElement.offsetHeight;

				}
				else {

					$sElement.style.pageBreakBefore = "always";
					this.iCurrentTotalLength = $sElement.offsetHeight;

				}

			}

		}

	},

	//*******************************************************************************************************
	/**
	 * @param $sEle
	 * @param $iID
	 * @return void
	 */
	NotePrintToggle:function ($sEle, $iID) {

		if ($sEle.checked) $('notetblrow' + $iID).removeClassName('noprint');

		else $('notetblrow' + $iID).addClassName('noprint');

		var $aEle = $$('[class~=chkprint]');
		var $bPrint = false;

		$aEle.each(
			function ($sEle) {
				if ($sEle.checked) $bPrint = true;
			}
		);

		if ($bPrint) $('tblchkprint').removeClassName('noprint');
		else $('tblchkprint').addClassName('noprint');

	},

	//*******************************************************************************************************
	/**
	 * @param $sVarName
	 * @return string
	 */
	GetUrlVar:function ($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];

	},

	//*******************************************************************************************************
	/**
	 * @param $sName
	 * @param $sValue
	 * @param $sExpires
	 * @param $sPath
	 * @param $sDomain
	 * @param $sSecure
	 * @return void
	 */
	Set_Cookie:function ($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 + "=" + encodeURIComponent($sValue) +
		                  ( ( $sExpires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		                  ( ( $sPath ) ? ";path=" + $sPath : "" ) +
		                  ( ( $sDomain ) ? ";domain=" + $sDomain : "" ) +
		                  ( ( $sSecure ) ? ";secure" : "" );

	},

	//*******************************************************************************************************
	/**
	 * @param $sCheckName
	 * @return string|null|bool
	 */
	Get_Cookie:function ($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 = decodeURIComponent($aTempCookie[1].replace(/^\s+|\s+$/g, ''));

				// note that in cases where cookie is initialized but no value, null is returned
				return $sCookieValue;

			}

			$aTempCookie = null;
			$sCookieName = '';

		}

		if (!$bCookieFound) return null;

		return true;

	},

	//*******************************************************************************************************
	/**
	 * @return void
	 */
	Loading:function () {

		if (!$('Loading')) {

			$(document.body).insert(
				{Before:'<div id="Loading" style="position:absolute;right:15px;top:15px;"></div>'});

		}

		Ajax.Responders.register(
			{

				onCreate:function () {

					$('Loading').update(
						'<img src="../images/verify_anim_small.gif" ' +
						'style="height:25px">');

				},

				onComplete:function () {

					$('Loading').update('');

				}

			});

	},

	//*******************************************************************************************************
	/**
	 * @param $sSourceName
	 * @return bool
	 */
	CheckForJSSource:function ($sSourceName) {

		var $bReturn = false;

		$$('script').each(function ($oEle) {

			if ($oEle.src.match($sSourceName)) {

				$bReturn = true;
				throw $break;

			}

		});

		return $bReturn;

	},

	//*******************************************************************************************************
	/**
	 * @param $sAction
	 * @param $sRecordDescription
	 * @param $sQueryString
	 * @return void
	 */
	ProvLogs_Action:function ($sAction, $sRecordDescription, $sQueryString) {

		if ($sAction == 'Apps_ProviderLogs::Delete') {

			if (!confirm('Are you sure you want to delete the attendance record for ' +
			             $sRecordDescription))
				return;

		}

		window.location = location.pathname + '?sAction=' + $sAction + '&sRecordDescription=' +
		                  $sRecordDescription + $sQueryString;

	},

	//*******************************************************************************************************
	/**
	 * @param $text
	 * @param $li
	 * @return void
	 */
	ProvLogs_AddPatient:function ($text, $li) {

		window.location = location.pathname + '?sAction=self::AddToDate&iAddSkey=' + $li.id;

	},

	//*******************************************************************************************************
	isIOS:function () {

		return InArray(_MOBILEDEVICETYPE, ['IPAD', 'IPHONE']);

	}

};

//************************************************************************************************************
/**
 * Added to provide for closing either Modal or Popup, if not a Modal
 * @return void
 */
function Modal_Close() {

	if (typeof(parent.oWin) != 'undefined') {

		parent.oWin.setDestroyOnClose();
		parent.oWin.close();
	}
	else window.close();

}

//************************************************************************************************************
/**
 * CKEditor_GetSetValue
 * @param $sEle
 * @param $sValue
 * @return string
 */
function $FC($sEle, $sValue) {

	$sValue = DefaultArg($sValue, null);

	if ($sValue !== null) CKEDITOR.instances[$sEle].setData($sValue);

	return CKEDITOR.instances[$sEle].getData();

}

//************************************************************************************************************
/**
 * @param $vEle
 * @return string
 */
function ArgsToGet($vEle) {

	var $sReturn = '';

	if (Object.isArray($vEle)) {

		$vEle.each(function ($sEle) {

			$sReturn += $($sEle).name + '=' + $F($sEle) + '&';

		});

		$sReturn = $sReturn.slice(0, $sReturn.length - 1);

	}
	else $sReturn = $($vEle).name + '=' + $F($vEle);

	return $sReturn;

}

//************************************************************************************************************
/**
 * @param $sArg
 * @param $sValue
 * @return string
 */
function DefaultArg($sArg, $sValue) {

	if (typeof($sArg) == 'undefined') return $sValue;

	//If string, clean it!
	if (Object.isString($sArg)) $sArg = $sArg.strip();

	//If PHP has converted the JS type of undefined to a string called undefined, check for that
	if ($sArg == 'undefined') return $sValue;

	return $sArg;

}

//************************************************************************************************************
/**
 * Comma creates a comma-delimited list of an array
 * @param $aArray
 * @param $sReturn
 * @param $sPrefix
 * @param $sSuffix
 * @return string
 */
function Comma($aArray, $sReturn, $sPrefix, $sSuffix) {

	$sReturn = DefaultArg($sReturn, '');
	$sPrefix = DefaultArg($sPrefix, '');
	$sSuffix = DefaultArg($sSuffix, '');

	var $sTemp = '';

	if (Object.isArray($aArray)) {

		$aArray.each(function ($s, $index) {

				if ($s.strip() == '') throw $continue;

				$sTemp = $sTemp + $sPrefix + $s + $sSuffix;

				if (typeof($aArray[$index + 1]) != 'undefined') $sTemp += ',';

			}
		);

	}
	else if ($sReturn != '') $sTemp = $sPrefix + $sReturn + $sSuffix;

	return $sTemp;

}

//************************************************************************************************************
/**
 * @param $sValue
 * @param $sVariable
 * @param $bFilter
 * @param $sUpdateTimeEle
 * @return bool
 */
function StoreValueInSessionJS($sValue, $sVariable, $bFilter, $sUpdateTimeEle) {

	var $bReturn;

	$bFilter = DefaultArg($bFilter, false);
	$sUpdateTimeEle = DefaultArg($sUpdateTimeEle, false);
	$sUpdateTimeEle = $sUpdateTimeEle ? '&sUpdateTime=' + $sUpdateTimeEle : '';
	$sValue = (typeof($sValue) != 'number' && $($sValue)) ? $F($sValue) : $sValue;

	if ($bFilter) {

		if (!InArray(window.event.keyCode, [32, 13, 190, 10, 188, 8])) return false;

	}

	$bReturn = AjaxUpdater(
		'ajaxObject=Common' +
		'&ajaxMethod=StoreValueInSession' +
		'&sTempVariable=' + encodeURIComponent($sVariable) +
		'&sTempValue=' + encodeURIComponent($sValue) +
		$sUpdateTimeEle,
		'Dirty',
		PRIDE.URL.PHPClass);

	return $bReturn;

}

//************************************************************************************************************
/**
 * @param $iID
 * @param $iDay
 * @param $iUserID
 * @param $sForm
 * @param $sRefSrc
 * @return void
 */
function SignDay($iID, $iDay, $iUserID, $sForm, $sRefSrc) {

	AjaxUpdater(
		'ajaxCommand=SignDayAjax&iID=' + $iID + '&iDay=' + $iDay + '&iUserID=' + $iUserID +
		'&sForm=' + $sForm + '&sRefSrc=' + $sRefSrc,
		'sig' + $iDay,
		PRIDE.URL.Forms);

	opener.location.reload();

}

//************************************************************************************************************
function SignDayDelete($iID, $iDay, $iUserID, $sForm) {

	AjaxUpdater(
		'ajaxCommand=SignDayAjaxDelete' +
		'&iID=' + $iID +
		'&iDay=' + $iDay +
		'&iUserID=' + $iUserID +
		'&sForm=' + $sForm,
		'sig' + $iDay,
		PRIDE.URL.Forms);

	opener.location.reload();

}

//************************************************************************************************************
function Load_AutoComplete($sFunction, $sLookupFunction, $sCompleteType, $iMinChars) {

	if (!PRIDE.COMMON.CheckForJSSource('scriptaculous')) alert('Scriptaculous is not loaded!');

	$sCompleteType = '_' + DefaultArg($sCompleteType, 'patient');
	$iMinChars = DefaultArg($iMinChars, 2);
	$sLookupFunction = DefaultArg($sLookupFunction, 'Patient');

	return new Ajax.Autocompleter(
		'autocomplete' + $sCompleteType + '_name',
		'autocomplete' + $sCompleteType + '_name_choices',
		PRIDE.URL.PHPClass +
		'?ajaxObject=Lookup' +
		'&ajaxMethod=' + $sLookupFunction +
		'&sCompleteType=' + $sCompleteType,
		{afterUpdateElement:$sFunction, minChars:$iMinChars,
			paramName:'autocomplete' + $sCompleteType + '_parameter_name'});

}

//************************************************************************************************************
/**
 * @deprecated
 * @param $sFunc
 */
function Load_AutoCompleteTicket($sFunc) {

	return new Ajax.Autocompleter(
		'autocomplete_ticket_name',
		'autocomplete_ticket_name_choices',
		PRIDE.URL.PHPClass +
		'?ajaxObject=Lookup' +
		'&ajaxMethod=Ticket' +
		'&iTicketsCategoryID=' + Tickets_CategoryID(),
		{callback:function ($x, $s) {
			return $s +
			       '&chkDescription=' + $('chkDescription').checked +
			       '&sFormFunction=' + $sFormFunction;
		},
			afterUpdateElement:$sFunc,
			minChars:2,
			indicator:'indicator1'});

}

//************************************************************************************************************
function ShowD($s) {

	if ($('a' + $s).innerHTML == '+') $('a' + $s).innerHTML = '-';
	else $('a' + $s).innerHTML = '+';

	$('d' + $s).toggle();

}

//************************************************************************************************************
function EmailNotificationAjaxError($sError) {

	EmailNotificationAjaxJS(null, null, null, null, null, $sError, location.pathname,
		PRIDE.COMMON.QueryStringGet(), false);

}

//************************************************************************************************************
/**
 * @param $sMessage
 * @param $sSubject
 * @param $sTo
 * @param $sFrom
 * @param $sCC
 * @param $sEmailNotificationAjaxError
 * @param $sEmailNotificationAjaxErrorPage
 * @param $sEmailNotificationAjaxErrorQueryString
 * @param $bAsync
 *
 */
function EmailNotificationAjaxJS($sMessage, $sSubject, $sTo, $sFrom, $sCC, $sEmailNotificationAjaxError, $sEmailNotificationAjaxErrorPage, $sEmailNotificationAjaxErrorQueryString, $bAsync) {

	if (typeof($sMessage) == 'undefined' && typeof($sEmailNotificationAjaxError) == 'undefined') return;

	$sEmailNotificationAjaxError = DefaultArg($sEmailNotificationAjaxError, null);

	$sSubject = DefaultArg($sSubject, 'Test');
	$sTo = DefaultArg($sTo, 'it@pridedallas.com');
	$sFrom = DefaultArg($sFrom, 'app01@pridedallas.com');
	$sCC = DefaultArg($sCC, '');
	$bAsync = DefaultArg($bAsync, true);

	var $sPars = 'ajaxCommand=Email::sendMessageJavaScriptAlert&sMessage=' + CleanForURL($sMessage) +
	             '&sSubject=' + CleanForURL($sSubject) + '&sTo=' + $sTo + '&sFrom=' +
	             $sFrom + '&sCC=' + $sCC + '&sEmailNotificationAjaxError=' +
	             CleanForURL($sEmailNotificationAjaxError) + '&sEmailNotificationAjaxErrorPage=' +
	             CleanForURL($sEmailNotificationAjaxErrorPage) +
	             '&sEmailNotificationAjaxErrorQueryString=' +
	             CleanForURL($sEmailNotificationAjaxErrorQueryString);

	AjaxUpdater($sPars, 'MessageResults', PRIDE.URL.PHPClass, $bAsync);

}

//************************************************************************************************************
/**
 * Set $sFormName form id or page name
 * to use PRIDE.COMMON.submitPage() instead of standard form.submit()
 */
function ConfirmAndSubmit($sConfirmMessage, $sHiddenElementName, $sHiddenElementValue, $sFormNameOrPageToSubmit) {

	$sFormNameOrPageToSubmit = DefaultArg($sFormNameOrPageToSubmit, 'frmMain');

	var $sConfirm = confirm($sConfirmMessage);

	if ($sConfirm) {

		$('hdncomphere').innerHTML = '<input type="hidden" name="' + $sHiddenElementName + '"' +
		                             'value="' + $sHiddenElementValue + '">';

		if (Object.isElement($($sFormNameOrPageToSubmit))) $($sFormNameOrPageToSubmit).submit();
		else {

			if ($sFormNameOrPageToSubmit.match(".")) PRIDE.COMMON.submitPage($sFormNameOrPageToSubmit);
			else alert("Argument 3 ($sFormNameOrPageToSubmit) has to be either a form id or page name!");

		}

	}

}

//************************************************************************************************************
function MarkOPNOPC($iSkey, $sType) {

	if ($iSkey == '') return;

	var $sDate = $F('hdnEndDate' + $iSkey);

	if ($sDate == '') alert('No End Date entered!');
	else {

		var $sConfirm = confirm('Mark patient ' + $sType + ' and enter discharge date of ' + $sDate + ' ?');

		if ($sConfirm)
			AjaxUpdater(
				'ajaxCommand=MarkOPNOPC' +
				'&iSkey=' + $iSkey +
				'&sDate=' + $sDate +
				'&sType=' + $sType,
				'results',
				PRIDE.URL.OPT,
				false,
				'get');

	}

}

//************************************************************************************************************
function MarkORD($iSkey) {

	if ($iSkey == '') return;

	var $sConfirm = confirm('Mark patient ORD?');

	if ($sConfirm)
		AjaxUpdater(
			'ajaxCommand=MarkORD' +
			'&iSkey=' + $iSkey,
			'results',
			PRIDE.URL.OPT,
			true,
			'get');

}

//************************************************************************************************************
function CleanForURL($s) {

	if ($s === null) return '';

	if (IsInt($s) || typeof($s) == 'undefined') return $s;

	$s = $s.replace(/%/g, '%25');
	$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 Maximize() {

	var $iWidth = top.screen.availWidth;
	var $iHeight = top.screen.availHeight;

	if ($iWidth > 1280) $iWidth = 1280;

	if (screen.width < 1400) window.moveTo(0, 0);

	window.resizeTo($iWidth, $iHeight);

}

//************************************************************************************************************
function PopUp($sURL, $iWidth, $iHeight, $iScroll, $iResize, $sID, $iLeft, $iTop) {

	var $oDay = new Date();

	$sID = DefaultArg($sID, $oDay.getTime());
	$iLeft = DefaultArg($iLeft, 10);
	$iTop = DefaultArg($iTop, 10);
	$iScroll = DefaultArg($iScroll, 1);
	$iResize = DefaultArg($iResize, 1);
	$iWidth = DefaultArg($iWidth, 200);
	$iHeight = DefaultArg($iHeight, 200);

	return self.window.open(
		$sURL,
		$sID,
		'toolbar=0' +
		',scrollbars=' + $iScroll +
		',location=0' +
		',status=1' +
		',menubar=0' +
		',resizable=' + $iResize +
		',width=' + $iWidth +
		',height=' + $iHeight +
		',left=' + $iLeft +
		',top=' + $iTop);

}

//************************************************************************************************************
function PopUpDialog($sURL, $sID, $bScroll, $bStatus) {

	var $oDay = new Date();

	$sID = typeof($sID) != 'undefined' ? $sID : $oDay.getTime();
	$bScroll = typeof($bScroll) != 'undefined' ? $bScroll : 0;
	$bStatus = typeof($bStatus) != 'undefined' ? $bStatus : 0;

	self.window.open(
		$sURL,
		$sID,
		'toolbar=0' +
		',scrollbars=' + $bScroll +
		',location=0' +
		',status=' + $bStatus +
		',menubar=0' +
		',resizable=0' +
		',left=10' +
		',top=10');

}

//************************************************************************************************************
function convertSecondsToMilliseconds($iSeconds) {

	return $iSeconds * 1000;

}

//************************************************************************************************************
/**
 * location.replace(decodeURI(location))
 */
function RefreshPage() {

	var $sURL = decodeURI(location);
	location.replace($sURL);

}

//************************************************************************************************************
/**
 * Open report window
 * @param $sReport
 */
function ReportOpen($sReport) {

	if ($sReport)
		self.window.open(
			'/' + $sReport,
			'reporting_all',
			'channelmode=yes' +
			',toolbar=yes' +
			',location=no' +
			',menubar=no' +
			',scrollbars=yes' +
			',resizable=yes' +
			',fullscreen=no' +
			',status=yes');

}

//************************************************************************************************************
/**
 * @param $sClass
 * @param $sMethod
 * @param $iSeconds
 */
function PeriodicalAjaxUpdaterOnDomLoaded($sClass, $sMethod, $sLocation, $iSeconds) {

	if ($iSeconds < 10) $iSeconds = 10;

	if (!$('Loading')) {

		$(document.body).insert(
			{Before:'<div id="Loading" style="position:absolute;right:15px;top:15px;"></div>'});

	}

	Ajax.Responders.register(
		{

			onCreate:function () {

				$('Loading').update('<img src="../images/verify_anim_small.gif" style="height:25px">');

			},

			onComplete:function () {

				$('Loading').update('');

			}

		});

	document.observe(
		'dom:loaded',
		function () {
			new PeriodicalExecuter(
				function () {
					AjaxUpdater(
						'ajaxObject=' + $sClass +
						'&ajaxMethod=' + $sMethod,
						$sLocation,
						PRIDE.URL.PHPClass);
				},
				$iSeconds);
		});

}

//************************************************************************************************************
/**
 * Updates data from RM5 via Ajax
 * @param $iSkey (int) Patient skey
 * @param $bReload (bool) True to reload page, Default = false
 * @param $bAlertComplete (bool) True to show alert when complete, Default = false
 * @param $oDisableButton (object) use this most of the time
 */
function RM5DataUpdateAjax($iSkey, $bReload, $bAlertComplete, $oDisableButton) {

	var $sPars, $sDisableButtonText;

	$bReload = DefaultArg($bReload, false);
	$oDisableButton = DefaultArg($oDisableButton, null);
	$bAlertComplete = DefaultArg($bAlertComplete, false);

	if ($($oDisableButton)) {

		$($oDisableButton).disable();
		$sDisableButtonText = $F($oDisableButton);
		$($oDisableButton).value = 'Updating...';

	}

	if ($iSkey == 'All') $sPars = 'all=all';
	else $sPars = 'all_skey=' + $iSkey;

	AjaxUpdater(
		'ajaxObject=Apps_RM5DataUpdate' +
		'&ajaxMethod=Init' +
		'&' + $sPars,
		'RM5DataUpdateHTML',
		PRIDE.URL.PHPClass,
		true,
		null,
		null,
		function () {
			RM5DataUpdateAjax_Complete($bAlertComplete, $bReload, $oDisableButton, $sDisableButtonText);
		}
	);

}

//************************************************************************************************************
/**
 * @param $bAlertComplete
 * @param $bReload
 * @param $oDisableButton
 * @param $sDisableButtonText
 */
function RM5DataUpdateAjax_Complete($bAlertComplete, $bReload, $oDisableButton, $sDisableButtonText) {

	if ($bAlertComplete) alert('RM5 data has been updated!' + ($bReload ? ' Reloading....' : ''));

	if ($bReload === true) window.location.reload();

	if ($($oDisableButton)) {

		$($oDisableButton).value = $sDisableButtonText;
		$($oDisableButton).enable();

	}

}

//************************************************************************************************************
/**
 * @param $sPars parameters (ex. ajaxCommand=UpdateName&sFirstName=Keith&sLastName=Davis)
 * @param $sID ID of element to return HTML to
 * @param $sAsync asynchronous transfer, true or false (Default = true)
 * @param $sMethod 'post' or 'get' (Default = 'post', unless _MOBILEDEVICE == true)
 * @param $sEvalScripts true or false (Default = true)
 * @param $sOnComplete callback function on completion of ajax request (function(){ alert('hello'); }
 * @param $sOnCreate register onCreate function
 * @param $sOnFailure register onFailure function
 * @param $sOnSuccess register onSuccess function
 */
function AjaxUpdater($sPars, $sID, $sAsync, $sMethod, $sEvalScripts, $sOnComplete, $sOnCreate, $sOnFailure, $sOnSuccess) {

	$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;

	if (!Object.isString($sPars))
		$sPars = Object.toQueryString($sPars);

	return new Ajax.Updater(
		AjaxID($sID),
		PRIDE.URL.AjaxURL,
		{method:$sMethod,
			asynchronous:$sAsync,
			evalScripts:$sEvalScripts,
			parameters:$sPars,
			onComplete:$sOnComplete,
			onCreate:$sOnCreate,
			onFailure:$sOnFailure,
			onSuccess:$sOnSuccess});

}

//************************************************************************************************************
/**
 * @param $sEle
 * @param $sEleType
 */
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);

}

//************************************************************************************************************
/**
 * @param $oEle
 * @param $iProvSkey
 */
function CheckForProvCode($oEle, $iProvSkey) {

	AjaxUpdater(
		'ajaxObject=PRIDE' +
		'&ajaxMethod=CheckForProvCode' +
		'&sProvCode=' + CleanForURL($oEle.value) +
		'&iProv5Skey=' + $iProvSkey +
		'&sElement=' + $oEle.id,
		'ProvCodeResult',
		PRIDE.URL.PHPClass);

}

//************************************************************************************************************
/**
 * @param $oText
 * @param $oLi
 */
function ChooseProvider_EditForm($oText, $oLi) {

	$('choice').show();
	$('choice').value = $oText.value;
	$('hdnChoice').value = $oText;
	$('iProvider').value = $oLi.id;
	$('autocomplete_provider_name').value = '';

	if ($('iProvider').value != '' && $('iProvider').value != 'NO RECORDS FOUND')
		$('cmdSelect').enable();

}

//************************************************************************************************************
/**
 * @param $sReport
 */
function Landscape($sReport) {

	var $i = 0;

	if ($sReport == 'Phase2') {

		$('phase3results').style.width = '960px';
		$('title').style.fontSize = "24px";

		var $aTD = $$('[class=phase3]');

		for ($i = 0; $i < $aTD.length; $i++) $aTD[$i].style.fontSize = '20px';

		$aTD = $$('[class=subheading]');

		for ($i = 0; $i < $aTD.length; $i++) $aTD[$i].style.fontSize = '20px';

		$aTD = $$('[class=header]');

		for ($i = 0; $i < $aTD.length; $i++) $aTD[$i].style.fontSize = '20px';

	}

	window.print();

}

//************************************************************************************************************
function Dirty() {

	AjaxID('Dirty').innerHTML = '...';

}

//************************************************************************************************************
function IsInt($vValue) {

	if (typeof($vValue) == 'undefined') return false;

	return ($vValue.toString().search(/^-?[0-9]+$/) == 0);

}

//************************************************************************************************************
function setPointerStyleToCursor($vElement) {

	$($vElement).style.cursor = 'pointer';

}

//************************************************************************************************************
function UpdateFieldStoreInitialValue($oEle) {

	if (typeof($sUpdateFieldInitialValueCalendar) !== 'undefined') {

		$sUpdateFieldInitialValue = $sUpdateFieldInitialValueCalendar;

		delete $sUpdateFieldInitialValueCalendar;

	}
	else {

		if (InArray($oEle.type, ['checkbox', 'radio']) && $oEle.checked === false)
			$sUpdateFieldInitialValue = '';
		else $sUpdateFieldInitialValue = $oEle.value;

	}

}

//************************************************************************************************************
/**
 * This is now the only UpdateField function that should be used.<br />
 * 1 Argument:	 $($sField).name || $sName<br />
 * ---(Pass array for multiple - ONLY 1 ARGUMENT)<br />
 * 2 Arguments:	$($sField).name || $sName, $sValue<br />
 * 3 Arguments:	$($sField).name || $sName, $sTable, $id<br />
 * 4 Arguments:	$($sField).name || $sName, $sTable, $id, $sValue<br />
 * Arguments not specified will be assigned as follows:<br />
 * $sValue			= $F($sField)<br />
 * $sUpdateFieldTable	= $F('UpdateFieldTable') || $F('sForm')<br />
 * $iUpdateFieldID		= $F('UpdateFieldID') || $F('id')<br />
 * @param $vArg0
 * @param $vArg1
 * @param $vArg2
 * @param $vArg3 If element is checkbox, cannot use this field, must use different name and id and use this
 */
function UpdateField($vArg0, $vArg1, $vArg2, $vArg3) {

	var $sName = '';
	var $sFieldData = '';
	var $sFieldNames = '';
	var $sUpdateFieldTable = '';
	var $iUpdateFieldID = '';
	var $sTable;
	var $sID;
	var $bArg0IsFormElement = false;

	if ($('sUpdateFieldTable')) $sUpdateFieldTable = $F('sUpdateFieldTable');
	//Needed for backwards compatiblity, sForm as table name is deprecated
	else if ($('sForm')) $sUpdateFieldTable = $F('sForm');

	if ($('iUpdateFieldID')) $iUpdateFieldID = $F('iUpdateFieldID');
	//Needed for backwards compatiblity, id as is deprecated
	else if ($('id')) $iUpdateFieldID = $F('id');

	//Clear Dirty marker
	$(AjaxID('Dirty')).update('');

	//Code for multiple inputs by css selector
	if (Object.isArray($vArg0)) {

		$sFieldNames = 'sFieldNames=';
		$sFieldData = '&sFieldData=';

		$vArg0.each(
			function ($oEle) {

				$sFieldNames += $oEle.name + '|||';
				$sFieldData += (($($vArg0).type == 'checkbox' && $($vArg0).checked === false) ? '' :
					CleanForURL($F($oEle))) + '|||';

			}
		);

	}
	else {

		//Determine if $vArg0 is a form element
		if ($($vArg0) && typeof($($vArg0).type) != 'undefined') $bArg0IsFormElement = true;

		//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 $vArg1 or $F($vArg0)
		if (typeof($vArg3) == 'undefined') {

			if (arguments.length == 2) {

				//DO NOT CHANGE THE ORDER OF THESE
				if ($bArg0IsFormElement && $($vArg0).type == 'checkbox' && $($vArg0).checked === false)
					$vArg3 = '';
				else $vArg3 = $vArg1;

				$vArg1 = $sUpdateFieldTable;
				$vArg2 = $iUpdateFieldID;

			}
			else {

				if ($bArg0IsFormElement && $($vArg0).type == 'checkbox' && $($vArg0).checked === false)
					$vArg3 = '';
				else $vArg3 = $F($vArg0);

				//Check to see if value has changed, if not exit
				if (typeof($sUpdateFieldInitialValue) !== 'undefined' &&
				    $sUpdateFieldInitialValue !== null) {

					if ($sUpdateFieldInitialValue == $vArg3) return false;

					delete $sUpdateFieldInitialValue;

				}

			}

		}

		$sFieldNames = 'sFieldNames=' + encodeURIComponent($sName);
		$sFieldData = '&sFieldData=' + encodeURIComponent(CleanForURL($vArg3));

	}

	$sTable = '&sUpdateFieldTable=' +
	          encodeURIComponent(DefaultArg($vArg1, $sUpdateFieldTable ? $sUpdateFieldTable : ''));
	$sID = '&iUpdateFieldID=' +
	       encodeURIComponent(DefaultArg($vArg2, $iUpdateFieldID ? $iUpdateFieldID : ''));

	if ($('modified_by_field')) {

		$sFieldNames = $sFieldNames + '|||' + $F('modified_by_field');
		$sFieldData = $sFieldData + '|||' + $F('modified_by_value');

	}

	var $sPars = $sFieldNames + $sFieldData + $sTable + $sID + '&ajaxCommand=PRIDE::UpdateFields';

	//Fire away!!
	AjaxUpdater(
		$sPars,
		AjaxID('Dirty'),
		PRIDE.URL.PHPClass,
		false,
		null,
		null,
		null,
		null,
		function () {
			alert('Data failed to save! Contact Administrator.');
		}
	);

	return true;

}

//************************************************************************************************************
/**
 * @param $iNum
 */
function FormatCurrency($iNum) {

	$iNum = $iNum.toString().replace(/\$|,/g, '');

	if (isNaN($iNum))	$iNum = "0";

	//noinspection AssignmentResultUsedJS
	var $bSign = ($iNum == ($iNum = Math.abs($iNum)));
	$iNum = Math.floor($iNum * 100 + 0.50000000001);
	var $iCents = $iNum % 100;
	$iNum = Math.floor($iNum / 100).toString();

	if ($iCents < 10) $iCents = "0" + $iCents;

	for (var i = 0; i < Math.floor(($iNum.length - (1 + i)) / 3); i++)
		$iNum = $iNum.substring(0, $iNum.length - (4 * i + 3)) + ',' +
		        $iNum.substring($iNum.length - (4 * i + 3));

	return ((($bSign) ? '' : '-') + '$' + $iNum + '.' + $iCents);

}

//************************************************************************************************************
/**
 * @param $sEle
 * @param $iKey
 * @param $sID
 * @param $sSectionID
 */
function HighlightRadioText($sEle, $iKey, $sID, $sSectionID) {

	var $aEle = new Array();

	$sSectionID = DefaultArg($sSectionID, null);

	if ($sEle.checked) {

		if ($sSectionID) $aEle = $($sSectionID).select('[class=' + $sID + ']');
		else $aEle = $$('[class=' + $sID + ']');

		$aEle.each(function ($s) {

			$($s).style.backgroundColor = '#D9DFDB';

		});

		$($sID + $iKey).style.backgroundColor = '#FFFF00';

	}

}

//************************************************************************************************************
/**
 * @param $sField				Column name
 * @param $sValue				Column data
 * @param $sTable				Table name
 * @param $iSkey				Skey value
 */
function UpdateFieldRM5($sField, $sValue, $sTable, $iSkey) {

	var $sFieldName = 'sFieldName=' + $sField;
	var $sFieldData = '&sFieldData=' + CleanForURL($sValue);

	var $sPars = encodeURI(
		$sFieldName +
		$sFieldData +
		'&cboActivePatient=' + $iSkey +
		'&sTable=' + $sTable +
		'&ajaxCommand=UpdateFieldRM5' +
		'&sLocationPathname=' + location.pathname);

	AjaxUpdater($sPars, 'Dirty', PRIDE.URL.Forms, false, 'get');

}

//************************************************************************************************************
function VerifyPatientExists() {

	if ($F('ssn2') == '' || $F('episode') == '' || $F('doi') == '') return false;
	else
		AjaxUpdater(
			'ajaxObject=Form_INF' +
			'&ajaxMethod=doesPatientAlreadyExistInCase5' +
			'&sSSN=' + $F('ssn2') +
			'&sEpisode=' + $F('episode') +
			'&sOnDate=' + $F('doi'),
			'AjaxMessages',
			PRIDE.URL.Forms);

	return true;

}

//************************************************************************************************************
function RM5DataUpdateAjaxAll($oEle) {

	alert('Click only once!');

	$($oEle).disable();

	AjaxUpdater(
		'ajaxObject=Apps_RM5DataUpdate&ajaxMethod=Init&all_rm5=yes',
		'RM5DataUpdateHTML',
		PRIDE.URL.PHPClass);

	location.reload();

}

//************************************************************************************************************
function RM5DataUpdateAjaxFunction($sFunction, $sParam1, $sAsync) {

	AjaxUpdater(
		'ajaxObject=Apps_RM5DataUpdate&ajaxMethod=' + $sFunction + '&ajaxParam1=' + $sParam1,
		'RM5DataUpdateHTML',
		PRIDE.URL.PHPClass,
		$sAsync,
		'get');

}

//Show element ($item) when select option ($index) is matched ($match)****************************************
function ShowItemCBO($sIndex, $sMatch, $sItem) {

	var $sMatchNoMatch = false;
	var $i;

	if (Object.isArray($sMatch)) {

		for ($i = 0; $i < $sMatch.length; $i++)
			if ($sIndex == $sMatch[$i]) $sMatchNoMatch = true;

	}
	else if ($sIndex == $sMatch) $sMatchNoMatch = true;

	if ($sMatchNoMatch) $($sItem).show();
	else {

		$($sItem).hide();
		$($sItem).value = '';

	}

}

//Show element ($item) when select option ($index) is matched ($match)****************************************
function ShowItemClearSubsCBO($sIndex, $sMatch, $sSubField1, $sSubField2) {

	var $sMatchNoMatch = false;

	if (Object.isArray($sMatch)) {

		for ($i = 0; $i < $sMatch.length; $i++)
			if ($sIndex == $sMatch[$i]) $sMatchNoMatch = true;

	}
	else if ($sIndex == $sMatch) $sMatchNoMatch = true;

	if ($sMatchNoMatch) $($sSubField1).show();
	else {

		$($sSubField1).hide();
		$($sSubField2).hide();
		ClearSubs($sSubField1);

	}

}

//Show element ($item) when select option ($index) is matched ($match)****************************************
function ShowItem($sValue, $sMatch, $sItem) {

	if ($sValue == $sMatch) $($sItem).show();
	else $($sItem).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).checked != 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) {

	$($sChkID).checked = $F($sTextID) == '';

	UpdateField($sChkID);

}

//************************************************************************************************************
function ClearSubs($sField, $sResetColor, $sResetPrefix) {

	if ($($sField).checked) return;

	$sResetColor = DefaultArg($sResetColor, false);
	$sResetPrefix = DefaultArg($sResetPrefix, false);

	var $aFields = GetFormElementNamesbyPrefix('frmMain', $sField);

	$aFields.each(function ($sField) {

		$($sField).checked = false;

		if ($sResetColor && $sResetPrefix)
			if ($($sResetPrefix + $($sField).id))
				$($sResetPrefix + $($sField).id).style.backgroundColor = $sResetColor;

	});

	UpdateField($aFields);

	Form_KeepAlive();

}

//************************************************************************************************************
//Pass $iID = 0 if ID is unknown
function FormOpen($iID, $iFormNum, $iSkey, $sForm, $sNoReload, $sFormName, $sNew) {

	$sFormName = typeof($sFormName) != 'undefined' ? $sFormName : $sForm;

	if ($sNew) {

		if (confirm('Create a new ' + $sFormName + '?') === false) return;

	}

	if ($sForm == 'inf') {

		if ($iID > 0) {

			self.window.open(
				'/form.php?id=' + $iID + '&sForm=' + $sForm,
				'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 {

		if ($iID || $iSkey) {

			self.window.open(
				'/form.php?id=' + $iID + '&cboActivePatient=' + $iSkey + '&sForm=' + $sForm +
				'&iFormNum=' + $iFormNum,
				'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) {

	if ($sNew) {

		var $sAnswer = confirm('Create a new ' + $sFormName + '?');

		if (!$sAnswer) return;

	}

	//For opening the form without session set
	$sForm = ($sForm != '') ? '&sForm=' + $sForm : '';

	if ($iID || $iSkey) {

		self.window.open(
			'/form.php?id=' + $iID +
			'&cboActivePatient=' +
			$iSkey +
			$sForm +
			'&iFormNum=' + $iFormNum,
			'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($sMessage) {

	if (_PRODTESTDEV != PROD) alert($sMessage);

}

//************************************************************************************************************
function PrintNotes($sID, $sForm) {

	if ($sID != '') {

		self.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
 * @param $sID
 * @param $sForm
 * @param $bOverwrite
 */
function FormReportOpen($sID, $sForm, $bOverwrite) {

	$bOverwrite = DefaultArg($bOverwrite, false);

	if ($sID != '' && $sID != null) {

		var $sURL = '/library/load_report.php' +
		            '?id=' + $sID +
		            '&sReport=reports/saved/' + $sForm + '/' + $sID + '.htm' +
		            '&sForm=' + $sForm +
		            '&bOverwrite=' + ($bOverwrite ? 1 : 1);

		self.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 = '';

	}

}

//Supress form submission by Enter key************************************************************************
function CheckEnter($e) { //$e is event object passed from function invocation

	var $sCharCode;

	//if which property of event object is supported (NN4)
	if ($e && $e.which) {

		$sCharCode = $e.which;

	}//character code is contained in NN4's which property
	else {

		$e = event;
		$sCharCode = $e.keyCode;

	}//character code is contained in IE's keyCode property

	//if generated character code is equal to ascii 13 (if enter key)
	return $sCharCode != 13;

}

//************************************************************************************************************
function GetFormElementNamesbyPrefix($sFormName, $sPrefix) {

	var $aFormFields = $($sFormName).getElements();
	var $aReturn = new Array();

	$aFormFields.each(

		function ($sField) {

			if ($sField.name.startsWith($sPrefix)) $aReturn[$aReturn.length] = $sField;

		}

	);

	return $aReturn;

}

//************************************************************************************************************
function InArray($sNeedle, $aHaystack) {

	var $x;

	for ($x = 0; $x <= $aHaystack.length; $x++) {

		if ($aHaystack[$x] == $sNeedle) return true;

	}

	return false;

}

//************************************************************************************************************
function EditFormJS($sClass, $sCommand, $sField) {

	var $sResults;
	var $sPars;
	var $iSkey;

	//If Report was pressed, save the form first
	if ($sCommand == 'Report') EditFormJS($sClass, 'UpdateReport', $sField);

	if (Object.isElement($($sField))) $iSkey = $F($sField);
	else $iSkey = $sField;

	if ($sCommand == 'Update' || $sCommand == 'UpdateReport') {

		$sResults = 'MessageResults';
		$sPars = 'ajaxObject=' + $sClass +
		         '&ajaxMethod=Update' +
		         '&cboActivePatient=' + $iSkey +
		         '&' + Form.serialize('frmPatient');

	}
	else {

		$sResults = 'PatientResults';
		$sPars = 'ajaxObject=' + $sClass +
		         '&ajaxMethod=' + $sCommand +
		         '&cboActivePatient=' + $iSkey;

	}

	AjaxUpdater($sPars, $sResults, PRIDE.URL.PHPClass, false);

	if ($sCommand == 'Update')
		AjaxUpdater(
			'ajaxObject=' + $sClass +
			'&ajaxMethod=EditForm' +
			'&cboActivePatient=' + $iSkey,
			'PatientResults',
			PRIDE.URL.PHPClass,
			false);

}

//************************************************************************************************************
function SaveForm($sTable, $sField) {

	AjaxUpdater(
		'ajaxCommand=Update' +
		'&sTable=' + $sTable +
		'&cboActivePatient=' + $F($sField) +
		'&' + Form.serialize('frmPatient'),
		'MessageResults',
		'library/save_form_ajax.php',
		false);

}

//************************************************************************************************************
function OnHold($sClass, $iSkey) {

	var $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(
		'ajaxObject=' + $sClass +
		'&ajaxMethod=OnHold' +
		'&cboActivePatient=' + $iSkey,
		'PlaceOnHold',
		PRIDE.URL.PHPClass,
		false);

	EditFormJS($sClass, 'EditForm', $iSkey);

}

//************************************************************************************************************
function CheckClear($ID) {

	if ($($ID).checked === false)
		new Insertion.Before($ID.name, '<input type="hidden" name="' + $ID.name + '" value="">');

}

//************************************************************************************************************
function Modal($sURL) {

	var $aOptions = arguments[1];
	var $aArgs = {resizable:false,
		draggable:false,
		minimizable:false,
		maximizable:false,
		recenterAuto:true,
		closable:true,
		ModalId:'thismodal',
		Title:'',
		left:100,
		top:100,
		width:200,
		height:200};

	for (var $aArgName in $aOptions) $aArgs[$aArgName] = $aOptions[$aArgName];

	if (_MOBILEDEVICE) {

		PopUpDialog($sURL, $aArgs.Title, 1);

		return;

	}

	oWin = new Window(
		{className:'bluelighting',
			title:$aArgs.Title,
			id:$aArgs.ModalId,
			showEffectOptions:{duration:null},
			hideEffectOptions:{duration:null},
			url:$sURL,
			showCenter:true,
			showProgress:true,
			destroyOnClose:true,
			resizable:$aArgs.resizable,
			draggable:$aArgs.draggable,
			minimizable:$aArgs.minimizable,
			maximizable:$aArgs.maximizable,
			recenterAuto:$aArgs.recenterAuto,
			closable:$aArgs.closable,
			left:$aArgs.left,
			top:$aArgs.top,
			width:$aArgs.width,
			height:$aArgs.height});
	oWin.setZIndex(1000);
	oWin.showCenter(true);

}

//************************************************************************************************************
/**
 *
 */
function Modal_CheckShowCenter() {

	if (!parent.oWin.visible) parent.oWin.showCenter(true);
	else parent.oWin._center();

}

//************************************************************************************************************
function ConfirmModal($sDialogText) {

	var $aOptions = arguments[1];

	var $aArgs = {okLabel:'OK', onOK:'return', onCancel:'return', ModalId:'thismodal', Title:''};

	for (var $oArgName in $aOptions) $aArgs[$oArgName] = $aOptions[$oArgName];

	Dialog.confirm($sDialogText, {width:300,
		title:$aArgs.Title,
		okLabel:$aArgs.okLabel,
		className:'bluelighting',
		showEffectOptions:{duration:null},
		hideEffectOptions:{duration:null},
		id:$aArgs.ModalId,
		onCancel:function () {
			eval($aArgs.onCancel);
		},
		onOk:function () {
			eval($aArgs.onOK);
		}});

}

