<cfcomponent displayname="Authorization Functions" hint="I Return Authorization Information" output="false">
	
	<cfset client.Loc_ID = 0 />
	
   <cffunction name="init" displayname="Initialize Component" access="public" returntype="Authorization" hint="I initialize and return the Authorization object.">
		<cfreturn this>
	</cffunction>
    
    <cffunction name="getauthorizations"  returntype="any" access="public" output="false" >
	   <cfargument name="Auth_ID" required="no" hint="Auth_ID">
	  	<cfquery name = "getauth" datasource="#Application.DataSrc#">
			SELECT pAuths.*,pPayer.Auth_Req,pPayer.Output FROM #Request.prefix_db_agency#.pAuths 
			JOIN #Request.prefix_db_agency#.pPtPayer  ON pAuths.PtPayer_ID = pPtPayer.PtPayer_ID AND  pPtPayer.Status = 0
    		JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND  pPayer.Status = 0
			WHERE pAuths.STATUS !=  <cfqueryparam cfsqltype="cf_sql_integer" value="3">
			AND  pAuths.AutoAuth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#"> 
	  	</cfquery>
		<cfreturn getauth>
	</cffunction>

	<cffunction name="getauthorizationslist"  returntype="any" access="public" output="false" >
	   <cfargument name="Assmt_ID" required="no" hint="Assmt_ID" default="0">
	   	<cfargument name="Admit_ID" required="no" hint="Admit_ID" default="0">

	    <!----  <cfquery name = "getauths" datasource="#Application.DataSrc#">
	        UPDATE #Request.prefix_db_agency#.pAuths  
	        SET Status = <cfqueryparam cfsqltype="cf_sql_integer" value="1">
	     	WHERE Date_End < CURDATE()
	     	AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#">
	     	AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
	     </cfquery> --->

	  	<cfquery name = "getauth" datasource="#Application.DataSrc#">
			SELECT pAuths.*,pRevenue_Code.Visit_Type,pRevenue_Code.Rev_Code,pRevenue_Code.HCPCS,pPtPayer.Sub_First,pPayer.Pay_Name,pAssessments.F26,pAssessments.F177,pAssessments.F178,pAssessments.Admit_ID,pPayer.Pay_ID,pRevenue_Code.Description,pPayer.Output,pPayer.auth_measure,pPayer.bypass_compliance,pAdmit.Admit_Type,
			CONCAT(pEmployee.Emp_First , ", ", pEmployee.Emp_Last) AS name_by
			 FROM #Request.prefix_db_agency#.pAuths 
			JOIN #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pAuths.Rev_ID AND pRevenue_Code.Status = 0
			JOIN #Request.prefix_db_agency#.pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID AND pPtPayer.Status < 2
			JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND pPayer.Status = 0
			LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status = 0
			LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID 
			LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pAuths.Created_by = pEmployee.Emp_ID
			WHERE pAuths.STATUS  <  <cfqueryparam cfsqltype="cf_sql_integer" value="2">
			AND pAuths.Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#">
			<cfif arguments.Assmt_ID neq 0 >
				AND pAuths.Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
			</cfif>
			<cfif arguments.Admit_ID neq 0 >
				AND pAdmit.Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Admit_ID#">
			</cfif>
			<cfif arguments.Assmt_ID neq 0 >
				 AND pAssessments.Admit_ID  IN ( SELECT pAdmit.Admit_ID FROM #Request.prefix_db_agency#.pAdmit 
				 WHERE pAdmit.Status < 2 AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#"> )
			 </cfif>
			GROUP BY pAuths.AutoAuth_ID 
		</cfquery>
		<cfreturn getauth>

	</cffunction>

	<cffunction name="getactiveauth"  returntype="any" access="public" output="false" >
	   <cfargument name="Auth_ID" required="yes" hint="Auth_ID">

	  	<cfquery name = "getauth" datasource="#Application.DataSrc#">
			SELECT * FROM #Request.prefix_db_agency#.pAuths 
			WHERE STATUS !=  <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			AND Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#"> 
	  	</cfquery>
		<cfreturn getauth>
	</cffunction>

	<cffunction name="getfrequency"  access="remote" output="Yes" httpmethod="GET" returnformat="JSON">
			  <cfargument name="Visit_No" required="yes" hint="Visit_No"> 
			  <cfquery name="get_label" datasource="#Application.DataSrc#">    
			          SELECT * FROM  #Request.prefix_db_lookup#.pVisit_Frequency
			          WHERE Visit_No = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Visit_No#"> 
					  ORDER BY ID ASC
			 </cfquery> 
			 <cfset label_name = '' >
			 <cfset responsekey=[] />
			 <cfoutput query="get_label" group="Visit_No">
				 <cfset obj={"Set_1_visits"=#Set_1_visits# ,"Set_1_weeks" = #Set_1_weeks#,"Set_2_visits"=#Set_2_visits# ,"Set_2_weeks" = #Set_2_weeks#,"Set_3_visits"=#Set_3_visits# ,"Set_3_weeks" = #Set_3_weeks#,"Set_4_visits"=#Set_4_visits#,"Set_4_weeks" = #Set_4_weeks# }  />
                  <cfset arrayAppend(responsekey, obj) />
			 </cfoutput>
			 <cfset response={"answer_labels"= #responsekey#} />
			 <cfreturn response />
    </cffunction> 

   	<cffunction name="Checktotalvisits" access="remote" returnformat="plain" returntype="string">
		<cfargument name="Auth_ID" required="yes" hint="Auth ID">
		<cfargument name="Patient_ID" required="yes" hint="Patient_ID">
		<cfargument name="Assmt_ID" required="yes" hint="Assmt ID">
		<cfargument name="selectedvisit" required="no" hint="0" default="1">
		<!--- -1 = visit type unknown; 0 = regular; 1 = PRN --->
		<cfargument name="prn_visit" required="no" default="-1">
		<!--- When provided, also enforce pAuths_weeks frequency for that date --->
		<cfargument name="Visit_Date" required="no" default="">
		<cfargument name="Exclude_Schedule_ID" required="no" default="0">

        <cfif #Request.prefix_db_agency# neq 'prefix_db_agency_invalid'>
			<cfquery name="total_visit_regular" datasource="#Application.DataSrc#">
				SELECT IFNULL(count(*),0) AS totalcount FROM #Request.prefix_db_agency#.pSchedules
				WHERE  Patient_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
		        AND  Assmt_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
		        AND  Auth_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
		        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
		        AND (Visit_Type is NULL OR (Visit_Type  NOT LIKE '6%' AND Visit_Type  NOT LIKE '7%'))
		        AND IFNULL(Missed, 0) = 0
				AND IFNULL(Nonbillable, 0) = 0
				AND IFNULL(prn_visit, 0) != 1
				<cfif Val(arguments.Exclude_Schedule_ID) GT 0>
					AND Schedule_ID <> <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(arguments.Exclude_Schedule_ID)#">
				</cfif>
			</cfquery>
			<cfquery name="total_visit_prn" datasource="#Application.DataSrc#">
				SELECT IFNULL(count(*),0) AS totalcount FROM #Request.prefix_db_agency#.pSchedules
				WHERE  Patient_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
		        AND  Assmt_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
		        AND  Auth_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
		        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
		        AND (Visit_Type is NULL OR (Visit_Type  NOT LIKE '6%' AND Visit_Type  NOT LIKE '7%'))
		        AND IFNULL(Missed, 0) = 0
				AND IFNULL(Nonbillable, 0) = 0
				AND IFNULL(prn_visit, 0) = 1
				<cfif Val(arguments.Exclude_Schedule_ID) GT 0>
					AND Schedule_ID <> <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(arguments.Exclude_Schedule_ID)#">
				</cfif>
			</cfquery>

			<!--- One auth row only: duplicate pAssessments Status=0 rows otherwise multiply the join
			     and make getauth["Set_n_weeks"] / column casts throw ComplexObjectException. --->
			<cfquery name="getauth" datasource="#Application.DataSrc#">
				SELECT pAuths.*, pPayer.bypass_compliance, pPayer.auth_measure, pAdmit.Admit_Type
				FROM #Request.prefix_db_agency#.pAuths
				JOIN #Request.prefix_db_agency#.pPtPayer ON pAuths.PtPayer_ID = pPtPayer.PtPayer_ID AND pPtPayer.Status = 0
				JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND pPayer.Status = 0
				LEFT JOIN #Request.prefix_db_agency#.pAssessments ON pAuths.Assmt_ID = pAssessments.Assmt_ID AND pAssessments.Status = 0
				LEFT JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.Status = 0
				WHERE pAuths.Patient_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
		        AND  pAuths.Assmt_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
		        AND  pAuths.Auth_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
		        AND pAuths.Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
				ORDER BY pAssessments.AutoAssmt_ID DESC
				LIMIT 1
			</cfquery>
			<cfset regularAuthorized = 0 />
			<cfset prnAuthorized = 0 />
			<cfif getauth.recordcount GT 0>
				<cfset regularAuthorized = Val(getauth.Total_Visits[1]) - Val(getauth.prn_visits[1]) />
				<cfset prnAuthorized = Val(getauth.prn_visits[1]) />
			</cfif>

			<!--- Check if we should skip visit count validation --->
			<cfset skip_visit_validation = false>
			<cfif getauth.recordcount GT 0>
				<cfif getauth.bypass_compliance EQ 1>
					<cfset skip_visit_validation = true>
				<cfelseif getauth.Admit_Type EQ 'Non-Medical'>
					<cfset skip_visit_validation = true>
				<cfelseif getauth.auth_measure EQ 'units' OR getauth.auth_measure EQ 'hours'>
					<cfset skip_visit_validation = true>
				</cfif>
			</cfif>

			<!--- Units/hours, Non-Medical, and missing auth skip all visit-count rules.
			     bypass_compliance still skips the episode total, but weekly frequency is enforced
			     (same as Add Schedule calendar). --->
			<cfif getauth.recordcount GT 0 AND (getauth.Admit_Type EQ 'Non-Medical'
				OR getauth.auth_measure EQ 'units' OR getauth.auth_measure EQ 'hours')>
				<cfreturn 'Success'>
			</cfif>
			<cfif arguments.Auth_ID EQ 0>
				<cfreturn 'Success'>
			</cfif>

			<cfset addCount = (arguments.selectedvisit EQ 1) ? 1 : val(arguments.selectedvisit) />
			<cfset prnFlag = val(arguments.prn_visit) />

			<cfif NOT skip_visit_validation>
				<cfset withinLimit = false />

				<cfif prnFlag EQ 1>
					<cfset withinLimit = (total_visit_prn.totalcount + addCount) LTE prnAuthorized />
				<cfelseif prnFlag EQ 0>
					<cfset withinLimit = (total_visit_regular.totalcount + addCount) LTE regularAuthorized />
				<cfelse>
					<!--- Visit type unknown: allow when either pool still has capacity --->
					<cfset withinLimit = (regularAuthorized GT 0 AND total_visit_regular.totalcount LT regularAuthorized)
						OR (prnAuthorized GT 0 AND total_visit_prn.totalcount LT prnAuthorized) />
				</cfif>

				<cfif NOT withinLimit>
					<cfset message ="New visit exceeds total visits established in related authorization. Change the number of visits in the related authorization if necessary" />
					 <cfreturn message>
				</cfif>
			</cfif>

			<!--- Weekly frequency: match Add Schedule (all non-missed visits on this auth consume the week cap) --->
			<cfif prnFlag NEQ 1 AND Len(Trim(arguments.Visit_Date)) AND IsDate(arguments.Visit_Date) AND addCount GTE 1>
				<cfset visitDt = CreateDate(Year(arguments.Visit_Date), Month(arguments.Visit_Date), Day(arguments.Visit_Date)) />
				<cfset weekAllowed = "" />
				<cfset weekNoDisp = "" />
				<cfset weekStartDt = "" />
				<cfset weekEndDt = "" />

				<cfquery name="getAuthWeek" datasource="#Application.DataSrc#">
					SELECT Auths_weeks_ID, Week_No, Week_Start, Week_End, Total_visits
					FROM #Request.prefix_db_agency#.pAuths_weeks
					WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
					AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
					AND DATE(Week_Start) <= <cfqueryparam cfsqltype="cf_sql_date" value="#visitDt#">
					AND DATE(Week_End) >= <cfqueryparam cfsqltype="cf_sql_date" value="#visitDt#">
					ORDER BY Auths_weeks_ID
					LIMIT 1
				</cfquery>
				<cfif getAuthWeek.recordcount GT 0>
					<cfset weekAllowed = Val(getAuthWeek.Total_visits) />
					<cfset weekNoDisp = getAuthWeek.Week_No />
					<cfset weekStartDt = getAuthWeek.Week_Start />
					<cfset weekEndDt = getAuthWeek.Week_End />
				<cfelseif getauth.recordcount GT 0 AND IsDate(getauth.Date_Start)>
					<cfset authStartDt = CreateDate(Year(getauth.Date_Start), Month(getauth.Date_Start), Day(getauth.Date_Start)) />
					<cfset weekBaseStart = DateAdd("d", -(DayOfWeek(authStartDt) - 1), authStartDt) />
					<cfset weekNoFromStart = Int(DateDiff("d", weekBaseStart, visitDt) / 7) + 1 />
					<cfif weekNoFromStart GTE 1>
						<cfquery name="getAuthWeekByNo" datasource="#Application.DataSrc#">
							SELECT Auths_weeks_ID, Week_No, Week_Start, Week_End, Total_visits
							FROM #Request.prefix_db_agency#.pAuths_weeks
							WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
							AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
							AND Week_No = <cfqueryparam cfsqltype="cf_sql_integer" value="#weekNoFromStart#">
							ORDER BY Auths_weeks_ID
							LIMIT 1
						</cfquery>
						<cfif getAuthWeekByNo.recordcount GT 0>
							<cfset weekAllowed = Val(getAuthWeekByNo.Total_visits) />
							<cfset weekNoDisp = getAuthWeekByNo.Week_No />
							<cfset weekStartDt = getAuthWeekByNo.Week_Start />
							<cfset weekEndDt = getAuthWeekByNo.Week_End />
						<cfelse>
							<cfset orderedWeekVisits = ArrayNew(1) />
							<cfloop index="k" from="1" to="4">
								<!--- Adobe CF: query.col[row]; QueryGetCell is Lucee-only. Dynamic ["col"] is an array (Val() fails). --->
								<cfswitch expression="#k#">
									<cfcase value="1">
										<cfset setWeeks = Val(getauth.Set_1_weeks[1]) />
										<cfset setVisits = Val(getauth.Set_1_visits[1]) />
									</cfcase>
									<cfcase value="2">
										<cfset setWeeks = Val(getauth.Set_2_weeks[1]) />
										<cfset setVisits = Val(getauth.Set_2_visits[1]) />
									</cfcase>
									<cfcase value="3">
										<cfset setWeeks = Val(getauth.Set_3_weeks[1]) />
										<cfset setVisits = Val(getauth.Set_3_visits[1]) />
									</cfcase>
									<cfdefaultcase>
										<cfset setWeeks = Val(getauth.Set_4_weeks[1]) />
										<cfset setVisits = Val(getauth.Set_4_visits[1]) />
									</cfdefaultcase>
								</cfswitch>
								<cfloop from="1" to="#setWeeks#" index="i">
									<cfset ArrayAppend(orderedWeekVisits, setVisits) />
								</cfloop>
							</cfloop>
							<cfif weekNoFromStart LTE ArrayLen(orderedWeekVisits)>
								<cfset weekAllowed = orderedWeekVisits[weekNoFromStart] />
								<cfset weekNoDisp = weekNoFromStart />
								<cfset weekStartDt = DateAdd("d", (weekNoFromStart - 1) * 7, weekBaseStart) />
								<cfset weekEndDt = DateAdd("d", 6, weekStartDt) />
							</cfif>
						</cfif>
					</cfif>
				</cfif>

				<cfif IsNumeric(weekAllowed) AND IsDate(weekStartDt) AND IsDate(weekEndDt)>
					<cfset authSkill = "" />
					<cfif getauth.recordcount GT 0 AND StructKeyExists(getauth, "Skill")>
						<cfset authSkill = Trim(getauth.Skill) />
					</cfif>
					<cfquery name="weekVisitCount" datasource="#Application.DataSrc#">
						SELECT IFNULL(COUNT(DISTINCT Schedule_ID),0) AS totalcount
						FROM #Request.prefix_db_agency#.pSchedules
						WHERE Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
						AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
						AND IFNULL(Missed, 0) = 0
						AND DATE(Visit_Date) >= <cfqueryparam cfsqltype="cf_sql_date" value="#weekStartDt#">
						AND DATE(Visit_Date) <= <cfqueryparam cfsqltype="cf_sql_date" value="#weekEndDt#">
						<cfif Val(arguments.Exclude_Schedule_ID) GT 0>
							AND Schedule_ID <> <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(arguments.Exclude_Schedule_ID)#">
						</cfif>
						AND (
							Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
							<cfif getauth.recordcount GT 0 AND Val(getauth.Assmt_ID) GT 0 AND Len(authSkill)>
								OR (
									Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#getauth.Assmt_ID#">
									AND IFNULL(Auth_ID, 0) = 0
									AND (Skill = <cfqueryparam cfsqltype="cf_sql_varchar" value="#authSkill#">
										OR Skill LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="#authSkill# %">)
								)
							</cfif>
						)
					</cfquery>
					<cfif (weekVisitCount.totalcount + addCount) GT Val(weekAllowed)>
						<cfreturn "New visit exceeds weekly frequency for this authorization (Week #weekNoDisp# allows #Val(weekAllowed)# visit(s); #weekVisitCount.totalcount# already scheduled for #DateFormat(weekStartDt,'mm/dd/yyyy')# - #DateFormat(weekEndDt,'mm/dd/yyyy')#). Update the authorization week frequency if necessary." />
					</cfif>
				</cfif>
			</cfif>

			<cfreturn 'Success'>
		<cfelse>
			<cfreturn 'Failure'>
		</cfif>
	</cffunction>

	<!--- Match patientpayers_forms.cfm: default Util_Force Yes for Medicare when not explicitly saved on pPtPayer --->
	<cffunction name="getEffectiveUtilForce" access="public" returntype="numeric" output="false">
		<cfargument name="utilForce" required="false" default="">
		<cfargument name="m0150" required="false" default="">
		<cfif Len(Trim("" & arguments.utilForce)) OR (IsNumeric(arguments.utilForce) AND Val(arguments.utilForce) EQ 0)>
			<cfreturn Val(arguments.utilForce) />
		</cfif>
		<cfif Len(Trim(arguments.m0150)) AND Left(Trim(arguments.m0150), 1) EQ "1" AND Left(Trim(arguments.m0150), 2) NEQ "10">
			<cfreturn 1 />
		</cfif>
		<cfreturn 0 />
	</cffunction>

	<cffunction name="checkUtilForceHippsCap" access="remote" returnformat="plain" returntype="string">
		<cfargument name="Auth_ID" required="no" default="0">
		<cfargument name="Patient_ID" required="yes">
		<cfargument name="Assmt_ID" required="yes">
		<cfargument name="PtPayer_ID" required="yes">
		<cfargument name="Total_Visits" required="yes" default="0">
		<cfargument name="no_assessments" required="no" default="0">

		<cfset var hippsCapMessage = "Visits exceeds average for this HIPPS Score. Contact Clinical Director." />

		<cfif Val(arguments.no_assessments) EQ 1 OR Val(arguments.Assmt_ID) EQ 0 OR Val(arguments.PtPayer_ID) EQ 0>
			<cfreturn "Success">
		</cfif>
		<cfif #Request.prefix_db_agency# EQ 'prefix_db_agency_invalid'>
			<cfreturn "Success">
		</cfif>

		<cfquery name="getUtilForcePayer" datasource="#Application.DataSrc#">
			SELECT pPayer.M0150, pPtPayer.Util_Force
			FROM #Request.prefix_db_agency#.pPtPayer pPtPayer
			JOIN #Request.prefix_db_agency#.pPayer pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND pPayer.Status = 0
			WHERE pPtPayer.PtPayer_ID = <cfqueryparam value="#arguments.PtPayer_ID#" cfsqltype="cf_sql_integer">
			AND pPtPayer.Status = 0
			LIMIT 1
		</cfquery>
		<cfset var effectiveUtilForce = 0 />
		<cfif getUtilForcePayer.recordcount GT 0>
			<cfset effectiveUtilForce = getEffectiveUtilForce(getUtilForcePayer.Util_Force, getUtilForcePayer.M0150) />
		</cfif>
		<cfif getUtilForcePayer.recordcount EQ 0
			OR effectiveUtilForce NEQ 1
			OR NOT (Left(Trim(getUtilForcePayer.M0150), 1) EQ "1" AND Left(Trim(getUtilForcePayer.M0150), 2) NEQ "10")>
			<cfreturn "Success">
		</cfif>

		<cfquery name="getUtilForceAssessment" datasource="#Application.DataSrc#">
			SELECT F300, F297
			FROM #Request.prefix_db_agency#.pAssessments
			WHERE Assmt_ID = <cfqueryparam value="#arguments.Assmt_ID#" cfsqltype="cf_sql_integer">
			AND Status = 0
			LIMIT 1
		</cfquery>
		<cfif getUtilForceAssessment.recordcount EQ 0 OR Len(Trim(getUtilForceAssessment.F300)) EQ 0>
			<cfreturn "Success">
		</cfif>

		<cfset var hippsAvgF300 = 0 />
		<cfset var hippsAvgF297 = 0 />
		<cfquery name="getUtilForceHippsAvgF300" datasource="#Application.DataSrc#">
			SELECT IFNULL(Total_skilled, 0) AS Total_skilled
			FROM #Request.prefix_db_lookup#.CW_Visit_Utilization
			WHERE HIPPS_Code = <cfqueryparam value="#Trim(getUtilForceAssessment.F300)#" cfsqltype="cf_sql_varchar">
			LIMIT 1
		</cfquery>
		<cfif getUtilForceHippsAvgF300.recordcount GT 0>
			<cfset hippsAvgF300 = Val(getUtilForceHippsAvgF300.Total_skilled) />
		</cfif>
		<cfif Len(Trim(getUtilForceAssessment.F297)) GT 0>
			<cfquery name="getUtilForceHippsAvgF297" datasource="#Application.DataSrc#">
				SELECT IFNULL(Total_skilled, 0) AS Total_skilled
				FROM #Request.prefix_db_lookup#.CW_Visit_Utilization
				WHERE HIPPS_Code = <cfqueryparam value="#Trim(getUtilForceAssessment.F297)#" cfsqltype="cf_sql_varchar">
				LIMIT 1
			</cfquery>
			<cfif getUtilForceHippsAvgF297.recordcount GT 0>
				<cfset hippsAvgF297 = Val(getUtilForceHippsAvgF297.Total_skilled) />
			</cfif>
		</cfif>
		<cfset var hippsAvgVisits = hippsAvgF300 + hippsAvgF297 />
		<cfif hippsAvgVisits LTE 0>
			<cfreturn "Success">
		</cfif>
		<cfquery name="getAssmtAuthVisitSum" datasource="#Application.DataSrc#">
			SELECT IFNULL(SUM(Total_Visits), 0) AS total_visits
			FROM #Request.prefix_db_agency#.pAuths
			WHERE Assmt_ID = <cfqueryparam value="#arguments.Assmt_ID#" cfsqltype="cf_sql_integer">
			AND Status = 0
		</cfquery>
		<cfset var oldAuthVisits = 0 />
		<cfif Val(arguments.Auth_ID) GT 0>
			<cfquery name="getCurrentAuthVisits" datasource="#Application.DataSrc#">
				SELECT IFNULL(Total_Visits, 0) AS Total_Visits
				FROM #Request.prefix_db_agency#.pAuths
				WHERE Auth_ID = <cfqueryparam value="#arguments.Auth_ID#" cfsqltype="cf_sql_integer">
				AND Status = 0
				LIMIT 1
			</cfquery>
			<cfif getCurrentAuthVisits.recordcount GT 0>
				<cfset oldAuthVisits = Val(getCurrentAuthVisits.Total_Visits) />
			</cfif>
		</cfif>
		<cfset var projectedAuthVisits = Val(getAssmtAuthVisitSum.total_visits) - oldAuthVisits + Val(arguments.Total_Visits) />
		<cfif projectedAuthVisits GT hippsAvgVisits>
			<cfreturn hippsCapMessage>
		</cfif>
		<cfreturn "Success">
	</cffunction>

	<cffunction name="checkauthnumber"   access="remote" returnformat="plain" returntype="string">
		<cfargument name="Auth_ID" required="yes" hint="Auth ID"  default="0">
		<cfargument name="Auth_No" required="yes" hint="Auth No">
		<cfargument name="Patient_ID" required="yes" hint="Patient_ID">
		<cfargument name="Assmt_ID" required="yes" hint="Assmt ID">
		<cfargument name="PtPayer_ID" required="yes" hint="PtPayer_ID" default="0">

	  	<cfquery name = "getauth" datasource="#Application.DataSrc#">
			SELECT * FROM #Request.prefix_db_agency#.pAuths 
			WHERE STATUS =  <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#"> 
			AND Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#"> 
			AND Auth_No = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.Auth_No#"> 
			AND PtPayer_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.PtPayer_ID#"> 
	  	</cfquery>
		<cfif getauth.recordcount GTE 1 AND  arguments.Auth_ID EQ 0>
			<cfreturn 'Failure'> 
		<cfelseif getauth.recordcount GTE 1 AND  arguments.Auth_ID NEQ  getauth.Auth_ID>
			<cfreturn 'Failure'>
		<cfelse>
			<cfreturn 'Success'>
		</cfif>
	</cffunction>


	<cffunction name="checkSupervisory" access="remote" returnformat="plain" returntype="string">
		<cfargument name="Auth_ID" required="yes" hint="Auth ID">
		<cfargument name="Patient_ID" required="yes" hint="Patient_ID">
		<cfargument name="Assmt_ID" required="yes" hint="Assmt ID">
		<cfargument name="selectedvisit" required="no" hint="0" default="1">
		<cfargument name="Visit_Date" required="no" hint="VisitDate">
		<cfargument name="Emp_ID" required="yes" hint="Emp_ID">

         <cfif #Request.prefix_db_agency# neq 'prefix_db_agency_invalid'>
         	<cfquery name="getauth" datasource="#Application.DataSrc#">
		    	SELECT * FROM #Request.prefix_db_agency#.pAuths 
		    	WHERE  Auth_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
		        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
		    </cfquery>

		    <cfset Request.Skill = getauth.Skill />

        	<cfquery name="getemployee" datasource="#Application.DataSrc#">
				SELECT * FROM #Request.prefix_db_lookup#.pEmployee
				WHERE  Emp_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Emp_ID#">
		        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
		        <cfif Request.Skill EQ 'HHA' >
		            AND (Skill_1 IN ('HHA','CNA') OR  Skill_2 IN ('HHA','CNA') OR Skill_3 IN ('HHA','CNA'))
		        <cfelseif Request.Skill EQ 'PTA'>
		        	AND (Skill_1 IN ('PTA') OR  Skill_2 IN ('PTA') OR Skill_3 IN ('PTA'))
		        <cfelseif Request.Skill EQ 'OTA'>
		        	AND (Skill_1 IN ('OTA') OR  Skill_2 IN ('OTA') OR Skill_3 IN ('OTA'))
		        </cfif>
			</cfquery>
			<cfquery name="getass" datasource="#Application.DataSrc#">
				SELECT * FROM #Request.prefix_db_agency#.pAssessments
				WHERE  Assmt_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
		        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			</cfquery>
			<cfset countVar = 0 />
			<cfset empskill_1 = #getemployee.Skill_1# />
			<cfset empskill_2 = #getemployee.Skill_2# />
			<cfset empskill_3 = #getemployee.Skill_3# />
			<cfset Request.Date_Start = #getass.F177# />
		    <cfset Request.Date_End   = #getass.F178# />
		    <cfset message = '' />
		    <cfset Request.Date_Start = #Request.Date_Start# />
			<cfif getemployee.recordcount GT 0 AND (Request.Skill EQ 'PTA' OR  Request.Skill EQ 'OTA'  OR Request.Skill EQ 'HHA')>
				<cfloop from = "1" to ="8"  index="weekcount" step="1"> 
					<cfset Request.Date_End = #DateAdd("d",6,Request.Date_Start)# />
					<cfset Request.Date_End = #DateFormat(Request.Date_End,"yyyy-mm-dd")# />
					<cfif (weekcount EQ 2 OR weekcount EQ 4 OR weekcount EQ 6 OR weekcount EQ 8)>
						<cfquery name="getsupervisits" datasource="#Application.DataSrc#">
							SELECT * FROM #Request.prefix_db_agency#.pSchedules
							WHERE  Assmt_ID =  <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
					        AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
					        AND Visit_Date BETWEEN  '#Request.Date_Start#' AND '#Request.Date_End#'
					        AND Supervision = 1
					        <cfif Request.Skill EQ 'HHA' >
					        	AND  Skill =  <cfqueryparam cfsqltype="cf_sql_varchar" value="SN">
					        <cfelseif  Request.Skill EQ 'PTA' >
					        	AND  Skill =  <cfqueryparam cfsqltype="cf_sql_varchar" value="PT">
					        <cfelseif  Request.Skill EQ 'OTA' >
					        	AND  Skill =  <cfqueryparam cfsqltype="cf_sql_varchar" value="OT">
					        </cfif>
						</cfquery>
					    <cfif  getsupervisits.recordcount EQ 0> 
							<cfset message = message & 'Week ' & #weekcount# & " " /> 
							<cfbreak>
						</cfif>
						<cfif arguments.Visit_Date GTE Request.Date_Start OR  arguments.Visit_Date LTE Request.Date_End>
							<cfbreak>
						</cfif>
					</cfif>	
					<cfset Request.Date_Start =  #DateAdd("d",1,Request.Date_End)#  />		
					<cfset Request.Date_Start = #DateFormat(Request.Date_Start,"yyyy-mm-dd")# />			
				</cfloop>
				<cfif message NEQ ''>
					 <cfset message = message & "Supervision visits must be scheduled every other week before aide or assistant can be scheduled" />
				<cfelse>
					<cfset message =  "Success" />
				</cfif>
				<cfreturn  message>
		    <cfelse>
				<cfreturn 'Success'>
			</cfif>
		<cfelse>
			<cfreturn 'Failure'>
		</cfif> 

	</cffunction>


	<cffunction name="getunschedulevisits"   access="remote"  returnFormat= "JSON" >
		<cfargument name="Rev_CodeID" required="yes" hint="Rev_CodeID"  default="0">
		<cfargument name="Patient_ID" required="yes" hint="Patient_ID">

	  	<cfquery name = "getauth" datasource="#Application.DataSrc#">
			SELECT pAuths.* FROM #Request.prefix_db_agency#.pAuths 
			JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status = 0
			WHERE pAuths.Status =  <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			AND pAuths.Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#"> 
			AND pAuths.Skill IN  ( SELECT Visit_Type FROM #Request.prefix_db_agency#.pRevenue_Code  
			 WHERE Rev_CodeID = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.Rev_CodeID#"> )
			AND pAssessments.Admit_ID  IN ( SELECT pAdmit.Admit_ID FROM #Request.prefix_db_agency#.pAdmit 
			WHERE pAdmit.Status < 2 AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#"> )
			GROUP BY pAuths.Auth_ID 
	  	</cfquery>

  		<cfset request.totremaining = 0 >
  		<cfloop query="getauth">
  			<cfquery  datasource="#Application.DataSrc#" name="Getvisitcount">
				SELECT *
				FROM #Request.prefix_db_agency#.pSchedules s
				WHERE s.Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#getauth.Auth_ID#" maxlength="10">
				AND s.Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#" maxlength="10">
				AND s.Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0" maxlength="10">
			</cfquery>
  	 		<cfquery  dbtype="query" name="getprn">
				SELECT * FROM Getvisitcount
				WHERE  prn_visit  = 1
				 AND (Visit_Type is NULL OR (Visit_Type  NOT LIKE '6%' AND Visit_Type  NOT LIKE '7%'))
			</cfquery>
			<cfquery  dbtype="query" name="getmissed">
				SELECT * FROM Getvisitcount
				WHERE   Missed  > 0
				 <!---AND (Visit_Type is NULL OR (Visit_Type  NOT LIKE '6%' AND Visit_Type  NOT LIKE '7%'))--->
			</cfquery>

			<cfquery  dbtype="query" name="getcompleted">
				SELECT * FROM Getvisitcount
				WHERE  Missed = 0
                and Visit_Date < #Now()#
			</cfquery>                     
            <cfset novisits = Total_visits - (Getvisitcount.recordcount) + (getmissed.recordcount  ) />   
            <cfset request.totremaining = request.totremaining + novisits />
        </cfloop>


        <cfif  request.totremaining gt 0 >
        	<cfset message = "There are " & #request.totremaining# & " " & #getauth.Skill#   & " visits for a prior authorization. Do you want to rollover unscheduled visits?"/>
        	 <cfset response_key={"statusCode"= 200,"statusText"= 'success',"data"= message, Skill =#getauth.Skill#,Unscheduled_Visits = #request.totremaining# } />
        	<cfreturn  response_key>
        <cfelse>
			 <cfset response_key={"statusCode"= 200,"statusText"= 'failure',"data"= "No schedules found", Unscheduled_Visits = #request.totremaining# } />
        	<cfreturn  response_key>
		</cfif>
	</cffunction>


	<cffunction name="show_weeklydates"  access="remote" output="Yes" returnFormat= "plain">   
		<cfargument name="Auth_ID" required="yes" default="0">
		<cfargument name="Assmt_ID" required="no" default="0">
		<cfargument name="Date_Start" required="yes" default="">
		<cfargument name="Date_End" required="yes" default= "">
		<cfargument name="Rev_ID" required="no" default="0">
		<cfset message = "Success">

			<cfif NOT isDate(arguments.Date_Start) OR NOT isDate(arguments.Date_End)>
				<cfreturn "">
			</cfif>

			<cfquery  name="getauthorizations" datasource="#Application.DataSrc#">
			    SELECT   pAssessments.F177,pAssessments.F178  
			    FROM  #Request.prefix_db_agency#.pAssessments 
			    WHERE pAssessments.Status= 0
			    AND pAssessments.Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(arguments.Assmt_ID)#">
			</cfquery>

			<cfset arguments.Date_Start = dateFormat(arguments.Date_Start, "yyyy-mm-dd") />
			<cfset arguments.Date_End = dateFormat(arguments.Date_End, "yyyy-mm-dd") />
			<cfset strating_date = arguments.Date_Start />
			<cfset ending_date = arguments.Date_End />
			<cfif Val(arguments.Assmt_ID) GT 0
				AND getauthorizations.recordcount GT 0
				AND isDate(getauthorizations.F177)
				AND isDate(getauthorizations.F178)
				AND parseDateTime(arguments.Date_End) GT parseDateTime(getauthorizations.F178)>
				<cfset strating_date = getauthorizations.F177 />
				<cfset ending_date = getauthorizations.F178 />
			</cfif>
			<cfif isDate(strating_date) AND isDate(ending_date)>
			    <cfscript>
			        // Define start and end dates for the range
			        startDate = strating_date;  // Example start date: August 1, 2024
			        endDate = ending_date;    // Example end date: August 31, 2024

			        FirstWeekStart = createDateTime(year(startDate), month(startDate), day(startDate), 0, 0, 0);
			        // Initialize variables
			        currentWeekStart = createDateTime(year(startDate), month(startDate), day(startDate), 0, 0, 0);
			        currentWeekStart = dateAdd("d", -DayOfWeek(currentWeekStart) + 1, currentWeekStart); // Start of the week (Sunday)
			        weeks = []; // Array to hold week data
			        week_no =  1;
			        // Loop through each week in the date range
			        while (currentWeekStart LTE endDate) 
			        {
			                // Calculate end of the week
			                currentWeekEnd = dateAdd("d", 6, currentWeekStart); // End of the week (Saturday)
			                if (currentWeekEnd GT endDate) {
			                    currentWeekEnd = endDate; // Adjust end date if it exceeds the range
			                }
			                // Collect dates for the current week
			                weekDates = [];
			                dateIter = currentWeekStart;
			                while (dateIter LTE currentWeekEnd) {
			                    arrayAppend(weekDates, dateFormat(dateIter, "yyyy-mm-dd"));
			                    dateIter = dateAdd("d", 1, dateIter);
			                }

			                // Store week information in the weeks array
			                if (week_no == 1)
			                {
			                    arrayAppend(weeks, {start = FirstWeekStart, end = currentWeekEnd, dates = weekDates});
			                }
			                else
			                {
			                    arrayAppend(weeks, {start = currentWeekStart, end = currentWeekEnd, dates = weekDates});
			                }
			                //arrayAppend(weeks, {start = currentWeekStart, end = currentWeekEnd, dates = weekDates});
			                week_no = week_no + 1;
			                // Move to the next week
			                currentWeekStart = dateAdd("d", 7, currentWeekStart);
			        }
				</cfscript>
				<cfquery name="getauthallweeks" datasource="#Application.DataSrc#">
				     SELECT * FROM #Request.prefix_db_agency#.pAuths_weeks
				     WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">  AND status = 0
				</cfquery>

				<cfsavecontent	variable = "html_weeklydates"> 
					<cfloop from="1" to="#arraylen(weeks)#" index="i">
							<cfset week_start = #weeks[i].start# >
					        <cfset week_end = #weeks[i].end# >
					        <cfset WeeK_Total_visits = 0 >
							<cfquery name="getauthweeks" dbtype="query">
							     SELECT * FROM getauthallweeks
							     WHERE Week_No = '#i#'
							     <!--- AND Week_Start = '#DateFormat(week_start,"yyyy-mm-dd")#'
							     AND Week_End = '#DateFormat(week_end,"yyyy-mm-dd")#' --->							      
							</cfquery>
							<cfif getauthweeks.recordcount gt 0>
								<cfset WeeK_Total_visits =#getauthweeks.Total_visits# />
							</cfif>
			                <cfif i LTE  #arraylen(weeks)#>
			                <div class="form-group auth-week-group">
			                   <div class="auth-week-row">
			                       <label class="control-label" for="WeeK_Total_visits#i#">Week #i# visit/s : #DateFormat(Week_Start,"mm/dd/yyyy")# - #DateFormat(Week_End,"mm/dd/yyyy")#</label>
			                       <div class="auth-week-radio-group" role="radiogroup" aria-label="Week #i# visit count">
			                           <cfloop index="j" from ="0" to="7">
			                               <label class="auth-week-radio-label">
			                                   <input type="radio" class="week-visits-radio" name="week_radio_#i#" value="#j#" data-week="#i#" <cfif WeeK_Total_visits EQ j>checked</cfif> onchange="setWeekVisitValue(#i#, #j#);">
			                                   <span>#j#</span>
			                               </label>
			                           </cfloop>
			                       </div>
			                   </div>
			                   <input type="hidden" id="WeeK_Total_visits#i#" name="WeeK_Total_visits#i#" value="#WeeK_Total_visits#">
			                </div>
			                <cfelse>
			                     <input type="hidden" id="WeeK_Total_visits#i#" name="WeeK_Total_visits#i#"  value="0">
			                </cfif>
		            </cfloop> 
		        </cfsavecontent>
		        <cfreturn html_weeklydates >
		    <cfelse>
		    	<cfreturn message >
		    </cfif>
	        
	</cffunction>

	<cffunction name="check_visit_date_auth" access="remote" returnformat="plain" returntype="string">
		<cfargument name="Patient_ID" required="yes" hint="Patient ID">
		<cfargument name="Assmt_ID" required="yes" hint="Assessment ID">
		<cfargument name="Auth_ID" required="yes" hint="Assessment ID">
		<cfargument name="Visit_Date" required="yes" hint="Visit Date">

		<cfset visit_date_valid = true>
		
		<!--- Check pAuths table for valid authorization periods --->
		<cfquery name="get_auths" datasource="#Application.DataSrc#">
			SELECT pAuths.Date_Start, pAuths.Date_End
			FROM #Request.prefix_db_agency#.pAuths 
			WHERE pAuths.Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
			AND pAuths.Status = 0
			AND pAuths.Auth_ID= '#arguments.Auth_ID#'
			<cfif arguments.Assmt_ID NEQ '' AND arguments.Assmt_ID NEQ '0'>
				AND pAuths.Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
			</cfif>
		</cfquery>
		
		<cfif get_auths.recordcount gt 0>
			<cfloop query="get_auths">
				<cfif get_auths.Date_Start NEQ '' AND get_auths.Date_End NEQ ''>
					<cfset auth_start = DateFormat(get_auths.Date_Start, "yyyy-mm-dd")>
					<cfset auth_end = DateFormat(get_auths.Date_End, "yyyy-mm-dd")>
					<cfset visit_date = DateFormat(arguments.Visit_Date, "yyyy-mm-dd")>
					
					<cfif visit_date LT auth_start OR visit_date GT auth_end>
						<cfset visit_date_valid = false>
						<cfbreak>
					</cfif>
				</cfif>
			</cfloop>
		</cfif>
		
		<cfif visit_date_valid>
			<cfreturn "valid">
		<cfelse>
			<cfreturn "invalid">
		</cfif>
	</cffunction>

	<cffunction name="checkOverScheduling" access="remote" returnformat="plain" returntype="string">
		<cfargument name="Auth_ID" required="yes" hint="Auth ID">
		<cfargument name="Patient_ID" required="yes" hint="Patient ID">
		<cfargument name="Assmt_ID" required="yes" hint="Assmt ID">
		<cfargument name="StartTime" required="yes" hint="Start Time">
		<cfargument name="EndTime" required="yes" hint="End Time">
		<cfargument name="Visit_Date" required="yes" hint="Visit Date">
		<cfargument name="Exclude_Schedule_ID" required="no" default="0" hint="Schedule ID to exclude from calculation (for editing existing visits)">

		<cfif #Request.prefix_db_agency# neq 'prefix_db_agency_invalid'>
			<!--- Get authorization details including auth_measure, Total_Visits, bypass_compliance, and admit_type --->
			<cfquery name="getauth" datasource="#Application.DataSrc#">
				SELECT pAuths.*, pPayer.auth_measure, pPayer.bypass_compliance, pAdmit.Admit_Type
				FROM #Request.prefix_db_agency#.pAuths 
				JOIN #Request.prefix_db_agency#.pPtPayer ON pAuths.PtPayer_ID = pPtPayer.PtPayer_ID AND pPtPayer.Status = 0
				JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND pPayer.Status = 0
				LEFT JOIN #Request.prefix_db_agency#.pAssessments ON pAuths.Assmt_ID = pAssessments.Assmt_ID AND pAssessments.Status = 0
				LEFT JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.Status = 0
				WHERE pAuths.Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
				AND pAuths.Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			</cfquery>

			<cfif getauth.recordcount gt 0>
				<cfset auth_measure = getauth.auth_measure>
				<cfset total_visits = getauth.Total_Visits>
				<cfset bypass_compliance = getauth.bypass_compliance>
				<cfset admit_type = getauth.Admit_Type>
				
				<!--- Check if we should skip visit count validation --->
				<cfset skip_visit_validation = false>
				<cfif bypass_compliance EQ 1>
					<cfset skip_visit_validation = true>
				<cfelseif admit_type EQ 'Non-Medical'>
					<cfset skip_visit_validation = true>
				</cfif>
				
				<!--- Only check over-scheduling for units or hours if not skipping validation --->
				<cfif NOT skip_visit_validation AND (auth_measure EQ 'units' OR auth_measure EQ 'hours' OR auth_measure EQ '')>
					<!--- Calculate visit duration based on auth_measure --->
					<cfif auth_measure EQ 'units' OR auth_measure EQ ''>
						<!--- For units: every 15 minutes = 1 unit --->
						<!--- Parse time strings (format: HH:MM) --->
						<cfset start_hour = ListGetAt(arguments.StartTime, 1, ':')>
						<cfset start_minute = ListGetAt(arguments.StartTime, 2, ':')>
						<cfset end_hour = ListGetAt(arguments.EndTime, 1, ':')>
						<cfset end_minute = ListGetAt(arguments.EndTime, 2, ':')>
						
						<!--- Convert to total minutes --->
						<cfset start_total_minutes = (start_hour * 60) + start_minute>
						<cfset end_total_minutes = (end_hour * 60) + end_minute>
						
						<!--- Calculate duration in minutes --->
						<cfset duration_minutes = end_total_minutes - start_total_minutes>
						
						<!--- Handle case where end time is next day --->
						<cfif duration_minutes LT 0>
							<cfset duration_minutes = duration_minutes + 1440> <!--- Add 24 hours (1440 minutes) --->
						</cfif>
						
						<!--- Calculate units (every 15 minutes = 1 unit) --->
						<cfset visit_units = Round(duration_minutes / 15)>
						
					<cfelseif auth_measure EQ 'hours'>
						<!--- For hours: calculate total hours --->
						<!--- Parse time strings (format: HH:MM) --->
						<cfset start_hour = ListGetAt(arguments.StartTime, 1, ':')>
						<cfset start_minute = ListGetAt(arguments.StartTime, 2, ':')>
						<cfset end_hour = ListGetAt(arguments.EndTime, 1, ':')>
						<cfset end_minute = ListGetAt(arguments.EndTime, 2, ':')>
						
						<!--- Convert to total minutes --->
						<cfset start_total_minutes = (start_hour * 60) + start_minute>
						<cfset end_total_minutes = (end_hour * 60) + end_minute>
						
						<!--- Calculate duration in minutes --->
						<cfset duration_minutes = end_total_minutes - start_total_minutes>
						
						<!--- Handle case where end time is next day --->
						<cfif duration_minutes LT 0>
							<cfset duration_minutes = duration_minutes + 1440> <!--- Add 24 hours (1440 minutes) --->
						</cfif>
						
						<!--- Convert to hours --->
						<cfset visit_hours = Round((duration_minutes / 60) * 100) / 100>
					</cfif>

					<!--- Get all scheduled visits for this authorization (excluding current visit if editing) --->
					<cfquery name="getscheduled" datasource="#Application.DataSrc#">
						SELECT StartTime, EndTime, Visit_Date
						FROM #Request.prefix_db_agency#.pSchedules 
						WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
						AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
						AND Missed = 0
						<cfif arguments.Exclude_Schedule_ID NEQ 0>
							AND Schedule_ID <> <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Exclude_Schedule_ID#">
						</cfif>
					</cfquery>

					<!--- Calculate total scheduled units/hours --->
					<cfset total_scheduled_units = 0>
					<cfset total_scheduled_hours = 0>
					
					<cfloop query="getscheduled">
						<!--- Parse scheduled visit times (format: HH:MM) --->
						<cfset sch_start_hour = ListGetAt(getscheduled.StartTime, 1, ':')>
						<cfset sch_start_minute = ListGetAt(getscheduled.StartTime, 2, ':')>
						<cfset sch_end_hour = ListGetAt(getscheduled.EndTime, 1, ':')>
						<cfset sch_end_minute = ListGetAt(getscheduled.EndTime, 2, ':')>
						
						<!--- Convert to total minutes --->
						<cfset sch_start_total_minutes = (sch_start_hour * 60) + sch_start_minute>
						<cfset sch_end_total_minutes = (sch_end_hour * 60) + sch_end_minute>
						
						<!--- Calculate duration in minutes --->
						<cfset sch_duration_minutes = sch_end_total_minutes - sch_start_total_minutes>
						
						<!--- Handle case where end time is next day --->
						<cfif sch_duration_minutes LT 0>
							<cfset sch_duration_minutes = sch_duration_minutes + 1440> <!--- Add 24 hours (1440 minutes) --->
						</cfif>
						
						<!--- Calculate units and hours --->
						<cfset sch_units = Round(sch_duration_minutes / 15)>
						<cfset sch_hours = Round((sch_duration_minutes / 60) * 100) / 100>
						
						<cfset total_scheduled_units = total_scheduled_units + sch_units>
						<cfset total_scheduled_hours = total_scheduled_hours + sch_hours>
					</cfloop>
 					<!--- Add current visit to total --->
					<cfif auth_measure EQ 'units' OR auth_measure EQ ''>
						<cfset total_scheduled_units = total_scheduled_units + visit_units>
						<cfif total_scheduled_units GT total_visits>
							<cfreturn "Over-scheduling detected: Total scheduled units (#total_scheduled_units#) exceeds authorized visits (#total_visits#). Each 15-minute period counts as 1 unit.">
						</cfif>
					<cfelseif auth_measure EQ 'hours'>
						<cfset total_scheduled_hours = total_scheduled_hours + visit_hours>
						<cfif total_scheduled_hours GT total_visits>
							<cfreturn "Over-scheduling detected: Total scheduled hours (#total_scheduled_hours#) exceeds authorized visits (#total_visits#).">
						</cfif>
					</cfif>
				</cfif>
				
				<cfreturn "Success">
			<cfelse>
				<cfreturn "Authorization not found">
			</cfif>
		<cfelse>
			<cfreturn "Failure">
		</cfif>
	</cffunction>

	<cffunction name="getScheduleAuthAmount" access="public" returntype="numeric" output="false">
		<cfargument name="schedule_units" required="true">
		<cfargument name="StartTime" type="string" required="false" default="">
		<cfargument name="EndTime" type="string" required="false" default="">
		<cfargument name="auth_measure" type="string" required="false" default="visits">

		<cfset measure = LCase(Trim(arguments.auth_measure)) />
		<cfif measure EQ 'visits'>
			<cfreturn 1 />
		</cfif>

		<!--- Prefer the actual visit Start/End times over the stored Total_Units: Total_Units can be
			  stale (e.g. computed from a mistyped EndTime earlier than StartTime, which the legacy
			  formula wrapped past midnight into ~90+ units) and is not always recalculated when the
			  times are corrected. Fall back to Total_Units only when the times are unusable. --->
		<cfset schedAmount = val(arguments.schedule_units) />
		<cfif Len(Trim(arguments.StartTime)) AND Len(Trim(arguments.EndTime)) AND ListLen(arguments.StartTime, ':') GTE 2 AND ListLen(arguments.EndTime, ':') GTE 2>
			<cfset start_total_minutes = (val(ListGetAt(arguments.StartTime, 1, ':')) * 60) + val(ListGetAt(arguments.StartTime, 2, ':')) />
			<cfset end_total_minutes = (val(ListGetAt(arguments.EndTime, 1, ':')) * 60) + val(ListGetAt(arguments.EndTime, 2, ':')) />
			<cfset duration_minutes = end_total_minutes - start_total_minutes />
			<!--- An EndTime of exactly midnight with a later StartTime means the visit was never
				  clocked out, not an overnight visit; don't wrap it into a huge duration. --->
			<cfif duration_minutes LT 0 AND end_total_minutes NEQ 0>
				<cfset duration_minutes = duration_minutes + 1440 />
			</cfif>
			<cfif duration_minutes GT 0>
				<cfif measure EQ 'hours'>
					<cfset schedAmount = Round((duration_minutes / 60) * 100) / 100 />
				<cfelse>
					<cfset schedAmount = Round(duration_minutes / 15) />
				</cfif>
			</cfif>
		</cfif>

		<cfreturn schedAmount />
	</cffunction>

	<cffunction name="getCompletedAuthAmount" access="public" returntype="numeric" output="false">
		<cfargument name="Auth_ID" type="numeric" required="true">
		<cfargument name="Patient_ID" type="numeric" required="true">
		<cfargument name="Assmt_ID" type="numeric" required="true">
		<cfargument name="auth_measure" type="string" required="false" default="visits">
		<!--- visits only: regular excludes PRN; prn counts PRN only; all counts both pools --->
		<cfargument name="visitPool" type="string" required="false" default="regular">

		<cfif #Request.prefix_db_agency# EQ 'prefix_db_agency_invalid'>
			<cfreturn 0 />
		</cfif>

		<!--- Default: missed / non-billable do not consume auth. Include_Missed_Visits=1 opts in. --->
		<cfset var includeMissedVisits = 0 />
		<cfset var authDateStart = "" />
		<cfset var authDateEnd = "" />
		<cftry>
			<cfquery name="qAuthMissedFlag" datasource="#Application.DataSrc#">
				SELECT IFNULL(Include_Missed_Visits, 0) AS Include_Missed_Visits,
					Date_Start, Date_End
				FROM #Request.prefix_db_agency#.pAuths
				WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
				AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
				LIMIT 1
			</cfquery>
			<cfif qAuthMissedFlag.recordcount GT 0>
				<cfset includeMissedVisits = Val(qAuthMissedFlag.Include_Missed_Visits) />
				<cfif IsDate(qAuthMissedFlag.Date_Start)><cfset authDateStart = qAuthMissedFlag.Date_Start /></cfif>
				<cfif IsDate(qAuthMissedFlag.Date_End)><cfset authDateEnd = qAuthMissedFlag.Date_End /></cfif>
			</cfif>
			<cfcatch>
				<!--- Older schemas without Include_Missed_Visits: still load cert dates --->
				<cfquery name="qAuthDates" datasource="#Application.DataSrc#">
					SELECT Date_Start, Date_End
					FROM #Request.prefix_db_agency#.pAuths
					WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
					AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
					LIMIT 1
				</cfquery>
				<cfif qAuthDates.recordcount GT 0>
					<cfif IsDate(qAuthDates.Date_Start)><cfset authDateStart = qAuthDates.Date_Start /></cfif>
					<cfif IsDate(qAuthDates.Date_End)><cfset authDateEnd = qAuthDates.Date_End /></cfif>
				</cfif>
			</cfcatch>
		</cftry>

		<cfquery name="getAuthSchedules" datasource="#Application.DataSrc#">
			SELECT IFNULL(Total_Units, 0) AS schedule_units, StartTime, EndTime
			FROM #Request.prefix_db_agency#.pSchedules
			WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
			AND status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Patient_ID#">
			AND Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Assmt_ID#">
			AND (Visit_Type IS NULL OR (Visit_Type NOT LIKE '6%' AND Visit_Type NOT LIKE '7%'))
			<!--- Missed / non-billable must not consume auth unless auth opts in --->
			<cfif includeMissedVisits NEQ 1>
				AND IFNULL(Missed, 0) = 0
				AND IFNULL(Nonbillable, 0) = 0
			</cfif>
			<cfif IsDate(authDateStart)>
				AND DATE(Visit_Date) >= <cfqueryparam cfsqltype="cf_sql_date" value="#authDateStart#">
			</cfif>
			<cfif IsDate(authDateEnd)>
				AND DATE(Visit_Date) <= <cfqueryparam cfsqltype="cf_sql_date" value="#authDateEnd#">
			</cfif>
			<cfset poolFilter = LCase(Trim(arguments.visitPool)) />
			<cfif LCase(Trim(arguments.auth_measure)) EQ 'visits'>
				<cfif poolFilter EQ 'prn'>
					AND IFNULL(prn_visit, 0) = 1
				<cfelseif poolFilter EQ 'regular'>
					AND IFNULL(prn_visit, 0) != 1
				</cfif>
			</cfif>
		</cfquery>

		<cfset measure = LCase(Trim(arguments.auth_measure)) />
		<cfif measure EQ 'units' OR measure EQ '' OR measure EQ 'hours'>
			<cfset completed = 0 />
			<cfloop query="getAuthSchedules">
				<cfset completed = completed + getScheduleAuthAmount(getAuthSchedules.schedule_units, getAuthSchedules.StartTime, getAuthSchedules.EndTime, arguments.auth_measure) />
			</cfloop>
			<cfreturn completed />
		</cfif>

		<cfreturn getAuthSchedules.recordcount />
	</cffunction>

	<cffunction name="getAuthorizedAuthAmount" access="public" returntype="numeric" output="false">
		<cfargument name="Auth_ID" type="numeric" required="true">

		<cfquery name="getauth" datasource="#Application.DataSrc#">
			SELECT Total_Visits, IFNULL(prn_visits, 0) AS prn_visits
			FROM #Request.prefix_db_agency#.pAuths
			WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
			AND Status = 0
		</cfquery>

		<cfif getauth.recordcount EQ 0>
			<cfreturn 0 />
		</cfif>

		<cfreturn val(getauth.Total_Visits) - val(getauth.prn_visits) />
	</cffunction>

	<cffunction name="getAuthorizedPrnAmount" access="public" returntype="numeric" output="false">
		<cfargument name="Auth_ID" type="numeric" required="true">

		<cfquery name="getauth" datasource="#Application.DataSrc#">
			SELECT IFNULL(prn_visits, 0) AS prn_visits
			FROM #Request.prefix_db_agency#.pAuths
			WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.Auth_ID#">
			AND Status = 0
		</cfquery>

		<cfif getauth.recordcount EQ 0>
			<cfreturn 0 />
		</cfif>

		<cfreturn val(getauth.prn_visits) />
	</cffunction>

	<cffunction name="isAuthLimitReached" access="public" returntype="boolean" output="false">
		<cfargument name="Auth_ID" type="numeric" required="true">
		<cfargument name="Patient_ID" type="numeric" required="true">
		<cfargument name="Assmt_ID" type="numeric" required="true">
		<cfargument name="auth_measure" type="string" required="false" default="visits">

		<cfset var measure = LCase(Trim(arguments.auth_measure)) />
		<cfif measure EQ 'units' OR measure EQ '' OR measure EQ 'hours'>
			<cfset var authorized = getAuthorizedAuthAmount(arguments.Auth_ID) />
			<cfif authorized LTE 0>
				<cfreturn false />
			</cfif>
			<cfset var completed = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'all') />
			<cfreturn completed GTE authorized />
		</cfif>

		<cfset var authorizedRegular = getAuthorizedAuthAmount(arguments.Auth_ID) />
		<cfset var authorizedPrn = getAuthorizedPrnAmount(arguments.Auth_ID) />
		<cfif authorizedRegular LTE 0 AND authorizedPrn LTE 0>
			<cfreturn false />
		</cfif>

		<cfset var completedRegular = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'regular') />
		<cfset var completedPrn = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'prn') />
		<cfset var regularExhausted = (authorizedRegular LTE 0) OR (completedRegular GTE authorizedRegular) />
		<cfset var prnExhausted = (authorizedPrn LTE 0) OR (completedPrn GTE authorizedPrn) />

		<cfif authorizedRegular GT 0 AND authorizedPrn GT 0>
			<cfreturn regularExhausted AND prnExhausted />
		<cfelseif authorizedPrn GT 0>
			<cfreturn prnExhausted />
		</cfif>

		<cfreturn regularExhausted />
	</cffunction>

	<cffunction name="getAuthLimitMessage" access="public" returntype="string" output="false">
		<cfargument name="Auth_ID" type="numeric" required="true">
		<cfargument name="Patient_ID" type="numeric" required="true">
		<cfargument name="Assmt_ID" type="numeric" required="true">
		<cfargument name="auth_measure" type="string" required="false" default="visits">

		<cfset var measure = LCase(Trim(arguments.auth_measure)) />
		<cfset var label = 'visits' />
		<cfif measure EQ 'units' OR measure EQ ''>
			<cfset label = 'units' />
		<cfelseif measure EQ 'hours'>
			<cfset label = 'hours' />
		</cfif>

		<cfif measure EQ 'units' OR measure EQ '' OR measure EQ 'hours'>
			<cfset var authorized = getAuthorizedAuthAmount(arguments.Auth_ID) />
			<cfset var completed = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'all') />
			<cfreturn "Authorization limit reached (#authorized# #label#). Completed #label#: #completed#" />
		</cfif>

		<cfset var authorizedRegular = getAuthorizedAuthAmount(arguments.Auth_ID) />
		<cfset var authorizedPrn = getAuthorizedPrnAmount(arguments.Auth_ID) />
		<cfset var completedRegular = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'regular') />
		<cfset var completedPrn = getCompletedAuthAmount(arguments.Auth_ID, arguments.Patient_ID, arguments.Assmt_ID, arguments.auth_measure, 'prn') />

		<cfif authorizedPrn GT 0>
			<cfreturn "Authorization limit reached (#authorizedRegular# regular + #authorizedPrn# PRN #label#). Completed: #completedRegular# regular, #completedPrn# PRN" />
		</cfif>

		<cfreturn "Authorization limit reached (#authorizedRegular# #label#). Completed #label#: #completedRegular#" />
	</cffunction>

	<!--- 485-style week rows from pAuths_weeks: "WK1: 1 (06/24/26-06/27/26), WK9: 1 (...)" --->
	<cffunction name="formatAuthWeeksLabel" access="public" returntype="string" output="false">
		<cfargument name="authId" type="numeric" required="true" />
		<cfargument name="skill" type="string" required="false" default="" />

		<cfset var weeksLabel = "" />
		<cfset var weekPart = "" />
		<cfset var getAuthWeeks = "" />

		<cfif Val(arguments.authId) LTE 0>
			<cfreturn "" />
		</cfif>

		<cfquery name="getAuthWeeks" datasource="#Application.DataSrc#">
			SELECT Week_No, Total_visits, Week_Start, Week_End
			FROM #Request.prefix_db_agency#.pAuths_weeks
			WHERE Auth_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(arguments.authId)#">
			  AND Status = <cfqueryparam cfsqltype="cf_sql_integer" value="0">
			  AND Total_visits <> 0
			ORDER BY Week_No ASC
		</cfquery>

		<cfloop query="getAuthWeeks">
			<cfset weekPart = "WK" & Week_No & ": " & Total_visits
				& " (" & DateFormat(Week_Start, "mm/dd/yy") & "-" & DateFormat(Week_End, "mm/dd/yy") & ")" />
			<cfset weeksLabel = ListAppend(weeksLabel, weekPart, ", ") />
		</cfloop>

		<cfif Len(weeksLabel) AND Len(Trim(arguments.skill))>
			<cfreturn Trim(arguments.skill) & " frequency " & weeksLabel />
		</cfif>
		<cfreturn weeksLabel />
	</cffunction>

	<!--- Build 485 weeks label from form week radios (WeeK_Total_visits#) before pAuths_weeks insert --->
	<cffunction name="formatAuthWeeksFromForm" access="public" returntype="string" output="false">
		<cfargument name="dateStart" type="any" required="true" />
		<cfargument name="dateEnd" type="any" required="true" />
		<cfargument name="formScope" type="struct" required="true" />
		<cfargument name="skill" type="string" required="false" default="" />
		<cfargument name="maxWeeks" type="numeric" required="false" default="20" />

		<cfset var weeksLabel = "" />
		<cfset var weekPart = "" />
		<cfset var i = 0 />
		<cfset var weekVisits = 0 />
		<cfset var startDate = "" />
		<cfset var endDate = "" />
		<cfset var FirstWeekStart = "" />
		<cfset var currentWeekStart = "" />
		<cfset var currentWeekEnd = "" />
		<cfset var week_no = 1 />
		<cfset var weeks = [] />

		<cfif NOT IsDate(arguments.dateStart) OR NOT IsDate(arguments.dateEnd)>
			<cfreturn "" />
		</cfif>

		<cfset startDate = CreateDateTime(Year(arguments.dateStart), Month(arguments.dateStart), Day(arguments.dateStart), 0, 0, 0) />
		<cfset endDate = CreateDateTime(Year(arguments.dateEnd), Month(arguments.dateEnd), Day(arguments.dateEnd), 0, 0, 0) />
		<cfset FirstWeekStart = startDate />
		<cfset currentWeekStart = DateAdd("d", -DayOfWeek(startDate) + 1, startDate) />

		<cfloop condition="currentWeekStart LTE endDate">
			<cfset currentWeekEnd = DateAdd("d", 6, currentWeekStart) />
			<cfif currentWeekEnd GT endDate>
				<cfset currentWeekEnd = endDate />
			</cfif>
			<cfif week_no EQ 1>
				<cfset arrayAppend(weeks, {start = FirstWeekStart, end = currentWeekEnd}) />
			<cfelse>
				<cfset arrayAppend(weeks, {start = currentWeekStart, end = currentWeekEnd}) />
			</cfif>
			<cfset week_no = week_no + 1 />
			<cfset currentWeekStart = DateAdd("d", 7, currentWeekStart) />
			<cfif week_no GT Val(arguments.maxWeeks)>
				<cfbreak />
			</cfif>
		</cfloop>

		<cfloop from="1" to="#ArrayLen(weeks)#" index="i">
			<cfset weekVisits = 0 />
			<cfif StructKeyExists(arguments.formScope, "WeeK_Total_visits" & i)>
				<cfset weekVisits = Val(arguments.formScope["WeeK_Total_visits" & i]) />
			</cfif>
			<cfif weekVisits GT 0>
				<cfset weekPart = "WK" & i & ": " & weekVisits
					& " (" & DateFormat(weeks[i].start, "mm/dd/yy") & "-" & DateFormat(weeks[i].end, "mm/dd/yy") & ")" />
				<cfset weeksLabel = ListAppend(weeksLabel, weekPart, ", ") />
			</cfif>
		</cfloop>

		<cfif Len(weeksLabel) AND Len(Trim(arguments.skill))>
			<cfreturn Trim(arguments.skill) & " frequency " & weeksLabel />
		</cfif>
		<cfreturn weeksLabel />
	</cffunction>

	<!--- Match 485 auth frequency display: standard label, pAuths_weeks rows, or set breakdown (1w2) --->
	<cffunction name="formatVisitFrequencyLabel" access="public" returntype="string" output="false">
		<cfargument name="visitFreq" type="numeric" required="false" default="0" />
		<cfargument name="standardFrequencyLabel" type="string" required="false" default="" />
		<cfargument name="set1Visits" type="numeric" required="false" default="0" />
		<cfargument name="set1Weeks" type="numeric" required="false" default="0" />
		<cfargument name="set2Visits" type="numeric" required="false" default="0" />
		<cfargument name="set2Weeks" type="numeric" required="false" default="0" />
		<cfargument name="set3Visits" type="numeric" required="false" default="0" />
		<cfargument name="set3Weeks" type="numeric" required="false" default="0" />
		<cfargument name="set4Visits" type="numeric" required="false" default="0" />
		<cfargument name="set4Weeks" type="numeric" required="false" default="0" />
		<cfargument name="authId" type="numeric" required="false" default="0" />
		<cfargument name="skill" type="string" required="false" default="" />

		<cfset var freqLabel = "" />
		<cfset var stdLabel = Trim(arguments.standardFrequencyLabel) />
		<cfset var weeksLabel = "" />

		<cfif Val(arguments.visitFreq) GT 0 AND Len(stdLabel) GT 0 AND UCase(stdLabel) NEQ "CUSTOM">
			<cfreturn stdLabel />
		</cfif>

		<!--- Custom / blank freq: prefer 485 weeks table when Auth_ID is known --->
		<cfif Val(arguments.authId) GT 0>
			<cfset weeksLabel = formatAuthWeeksLabel(authId = arguments.authId, skill = arguments.skill) />
			<cfif Len(weeksLabel)>
				<cfreturn weeksLabel />
			</cfif>
		</cfif>

		<cfif Val(arguments.set1Visits) GT 0>
			<cfset freqLabel = Val(arguments.set1Visits) & "w" & Val(arguments.set1Weeks) />
		</cfif>
		<cfif Val(arguments.set2Visits) GT 0>
			<cfset freqLabel = freqLabel & (Len(freqLabel) ? ", " : "") & Val(arguments.set2Visits) & "w" & Val(arguments.set2Weeks) />
		</cfif>
		<cfif Val(arguments.set3Visits) GT 0>
			<cfset freqLabel = freqLabel & (Len(freqLabel) ? ", " : "") & Val(arguments.set3Visits) & "w" & Val(arguments.set3Weeks) />
		</cfif>
		<cfif Val(arguments.set4Visits) GT 0>
			<cfset freqLabel = freqLabel & (Len(freqLabel) ? ", " : "") & Val(arguments.set4Visits) & "w" & Val(arguments.set4Weeks) />
		</cfif>

		<cfif Len(freqLabel) GT 0>
			<cfreturn freqLabel />
		</cfif>
		<cfif Len(stdLabel) GT 0 AND UCase(stdLabel) NEQ "CUSTOM">
			<cfreturn stdLabel />
		</cfif>
		<cfreturn "CUSTOM" />
	</cffunction>

            
</cfcomponent>