
/****************************************************************************
* 병원 정보 상세 조회
****************************************************************************/
function fn_selectHospitalJson(onlyOperatingHours) {
	let formData = new FormData();
	formData.append("menuClass", menuClass);
	formData.append("centerDivCd", $("#currentCenterDivCd").val() || 'DIET');

	$.ajax({
		url: encodeURI('/webhospital/selectHospital.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		async: true,
		success: function (data) {
			if ('0' == data.msgCode) {
				// 병원 정보
				let hospitalRows = data.rows[0];

				$("#muHospitalId").val(hospitalRows.muHospitalId);
				if ('Y' == hospitalRows.monOpenYn) {
					$('#checkMonOpenYn').prop('checked', true).trigger("change");

					let CheckMonOpenParent = $('#checkMonOpenYn').closest('li.on');
					CheckMonOpenParent.find("#monOpenStartTime").siblings("button").text(hospitalRows.monOpenStartTime);
					CheckMonOpenParent.find("#monOpenStartTime").val(hospitalRows.monOpenStartTime);
					CheckMonOpenParent.find("#monOpenEndTime").siblings("button").text(hospitalRows.monOpenEndTime);
					CheckMonOpenParent.find("#monOpenEndTime").val(hospitalRows.monOpenEndTime);
					CheckMonOpenParent.find("#monBreakStartTime").siblings("button").text(hospitalRows.monBreakStartTime);
					CheckMonOpenParent.find("#monBreakStartTime").val(hospitalRows.monBreakStartTime);
					CheckMonOpenParent.find("#monBreakEndTime").siblings("button").text(hospitalRows.monBreakEndTime);
					CheckMonOpenParent.find("#monBreakEndTime").val(hospitalRows.monBreakEndTime);
				}

				if ('Y' == hospitalRows.tueOpenYn) {
					$('#checkTueOpenYn').prop('checked', true).trigger("change");

					let CheckTueOpenParent = $('#checkTueOpenYn').closest('li.on');
					CheckTueOpenParent.find("#tueOpenStartTime").siblings("button").text(hospitalRows.tueOpenStartTime);
					CheckTueOpenParent.find("#tueOpenStartTime").val(hospitalRows.tueOpenStartTime);
					CheckTueOpenParent.find("#tueOpenEndTime").siblings("button").text(hospitalRows.tueOpenEndTime);
					CheckTueOpenParent.find("#tueOpenEndTime").val(hospitalRows.tueOpenEndTime);
					CheckTueOpenParent.find("#tueBreakStartTime").siblings("button").text(hospitalRows.tueBreakStartTime);
					CheckTueOpenParent.find("#tueBreakStartTime").val(hospitalRows.tueBreakStartTime);
					CheckTueOpenParent.find("#tueBreakEndTime").siblings("button").text(hospitalRows.tueBreakEndTime);
					CheckTueOpenParent.find("#tueBreakEndTime").val(hospitalRows.tueBreakEndTime);
				}

				if ('Y' == hospitalRows.wedOpenYn) {
					$('#checkWedOpenYn').prop('checked', true).trigger("change");

					let CheckWedOpenParent = $('#checkWedOpenYn').closest('li.on');
					CheckWedOpenParent.find("#wedOpenStartTime").siblings("button").text(hospitalRows.wedOpenStartTime);
					CheckWedOpenParent.find("#wedOpenStartTime").val(hospitalRows.wedOpenStartTime);
					CheckWedOpenParent.find("#wedOpenEndTime").siblings("button").text(hospitalRows.wedOpenEndTime);
					CheckWedOpenParent.find("#wedOpenEndTime").val(hospitalRows.wedOpenEndTime);
					CheckWedOpenParent.find("#wedBreakStartTime").siblings("button").text(hospitalRows.wedBreakStartTime);
					CheckWedOpenParent.find("#wedBreakStartTime").val(hospitalRows.wedBreakStartTime);
					CheckWedOpenParent.find("#wedBreakEndTime").siblings("button").text(hospitalRows.wedBreakEndTime);
					CheckWedOpenParent.find("#wedBreakEndTime").val(hospitalRows.wedBreakEndTime);
				}

				if ('Y' == hospitalRows.thuOpenYn) {
					$('#checkThuOpenYn').prop('checked', true).trigger("change");

					let CheckThuOpenParent = $('#checkThuOpenYn').closest('li.on');
					CheckThuOpenParent.find("#thuOpenStartTime").siblings("button").text(hospitalRows.thuOpenStartTime);
					CheckThuOpenParent.find("#thuOpenStartTime").val(hospitalRows.thuOpenStartTime);
					CheckThuOpenParent.find("#thuOpenEndTime").siblings("button").text(hospitalRows.thuOpenEndTime);
					CheckThuOpenParent.find("#thuOpenEndTime").val(hospitalRows.thuOpenEndTime);
					CheckThuOpenParent.find("#thuBreakStartTime").siblings("button").text(hospitalRows.thuBreakStartTime);
					CheckThuOpenParent.find("#thuBreakStartTime").val(hospitalRows.thuBreakStartTime);
					CheckThuOpenParent.find("#thuBreakEndTime").siblings("button").text(hospitalRows.thuBreakEndTime);
					CheckThuOpenParent.find("#thuBreakEndTime").val(hospitalRows.thuBreakEndTime);
				}

				if ('Y' == hospitalRows.friOpenYn) {
					$('#checkFriOpenYn').prop('checked', true).trigger("change");

					let CheckFriOpenParent = $('#checkFriOpenYn').closest('li.on');
					CheckFriOpenParent.find("#friOpenStartTime").siblings("button").text(hospitalRows.friOpenStartTime);
					CheckFriOpenParent.find("#friOpenStartTime").val(hospitalRows.friOpenStartTime);
					CheckFriOpenParent.find("#friOpenEndTime").siblings("button").text(hospitalRows.friOpenEndTime);
					CheckFriOpenParent.find("#friOpenEndTime").val(hospitalRows.friOpenEndTime);
					CheckFriOpenParent.find("#friBreakStartTime").siblings("button").text(hospitalRows.friBreakStartTime);
					CheckFriOpenParent.find("#friBreakStartTime").val(hospitalRows.friBreakStartTime);
					CheckFriOpenParent.find("#friBreakEndTime").siblings("button").text(hospitalRows.friBreakEndTime);
					CheckFriOpenParent.find("#friBreakEndTime").val(hospitalRows.friBreakEndTime);
				}

				if ('Y' == hospitalRows.satOpenYn) {
					$('#checkSatOpenYn').prop('checked', true).trigger("change");

					let CheckSatOpenParent = $('#checkSatOpenYn').closest('li.on');
					CheckSatOpenParent.find("#satOpenStartTime").siblings("button").text(hospitalRows.satOpenStartTime);
					CheckSatOpenParent.find("#satOpenStartTime").val(hospitalRows.satOpenStartTime);
					CheckSatOpenParent.find("#satOpenEndTime").siblings("button").text(hospitalRows.satOpenEndTime);
					CheckSatOpenParent.find("#satOpenEndTime").val(hospitalRows.satOpenEndTime);
					CheckSatOpenParent.find("#satBreakStartTime").siblings("button").text(hospitalRows.satBreakStartTime);
					CheckSatOpenParent.find("#satBreakStartTime").val(hospitalRows.satBreakStartTime);
					CheckSatOpenParent.find("#satBreakEndTime").siblings("button").text(hospitalRows.satBreakEndTime);
					CheckSatOpenParent.find("#satBreakEndTime").val(hospitalRows.satBreakEndTime);
				}

				if ('Y' == hospitalRows.sunOpenYn) {
					$('#checkSunOpenYn').prop('checked', true).trigger("change");

					let CheckSunOpenParent = $('#checkSunOpenYn').closest('li.on');
					CheckSunOpenParent.find("#sunOpenStartTime").siblings("button").text(hospitalRows.sunOpenStartTime);
					CheckSunOpenParent.find("#sunOpenStartTime").val(hospitalRows.sunOpenStartTime);
					CheckSunOpenParent.find("#sunOpenEndTime").siblings("button").text(hospitalRows.sunOpenEndTime);
					CheckSunOpenParent.find("#sunOpenEndTime").val(hospitalRows.sunOpenEndTime);
					CheckSunOpenParent.find("#sunBreakStartTime").siblings("button").text(hospitalRows.sunBreakStartTime);
					CheckSunOpenParent.find("#sunBreakStartTime").val(hospitalRows.sunBreakStartTime);
					CheckSunOpenParent.find("#sunBreakEndTime").siblings("button").text(hospitalRows.sunBreakEndTime);
					CheckSunOpenParent.find("#sunBreakEndTime").val(hospitalRows.sunBreakEndTime);
				}

				if ('Y' == hospitalRows.publicHolidayUseYn) {
					$('#checkPublicHolidayUseYn').prop('checked', true);
				} else {
					$('#checkPublicHolidayUseYn').prop('checked', false);
				}

				$("#txt_muMemberId").val(hospitalRows.muMemberId);
				$("#txt_memberName").val(hospitalRows.memberName);

				if (!onlyOperatingHours) {
					// 휴일 상세 정보
					fn_addRow2(hospitalRows.holidayRows);

					// 달력: 이미 생성되어 있으면 이벤트만 재조회, 없으면 새로 생성
					if (window.fcCalendar) {
						window.fcCalendar.refetchEvents();
					} else {
						fn_selectHospitalHolidayList();
					}
				}
			}
			else {
				modalEvent.danger("조회 오류", data.msgDesc);
			}
		},
		error: function (xhr, status, error) {
			modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
		},
		beforeSend: function () {

		},
		complete: function () {

		}
	});
}

/****************************************************************************
* 조회 row 추가 이벤트
****************************************************************************/
/****************************************************************************
* 조회 row 추가 이벤트
****************************************************************************/
function fn_addRow2(detailList) {
	let addRowHtml = '';

	if (0 < detailList.length) {
		// Rebuild Header (must match HTML exactly)
		addRowHtml += '<li class="list_title_li" style="display: flex !important; width: 100% !important; margin: 0 !important; padding: 10px 0 !important; background: #EDF5FF; border-radius: 5px; float: none !important; position: sticky; top: 0; z-index: 10;">';
		addRowHtml += '	<span class="list_title" style="width: 40px !important; display: flex; justify-content: center; align-items: center; float: none !important; border: none !important;"><input type="checkbox" id="checkAllHolidays"></span>';
		addRowHtml += '	<span class="list_title" style="flex: 1 !important; text-align: center; float: none !important; border: none !important; width: auto !important;">휴일명</span>';
		addRowHtml += '	<span class="list_title" style="width: 140px !important; text-align: center; float: none !important; border: none !important;">날짜</span>';
		addRowHtml += '	<span class="list_title" style="width: 100px !important; text-align: center; float: none !important; border: none !important;">일정반복</span>';
		addRowHtml += '	<span class="list_title" style="width: 70px !important; text-align: center; float: none !important; border: none !important;">저장</span>';
		addRowHtml += '</li>';

		for (let i = 0; i < detailList.length; i++) {
			let hospitalHolidayName = detailList[i].hospitalHolidayName;
			let locDate = detailList[i].locDate;
			let repeatYn = detailList[i].repeatYn;
			let repeatLabel = ('Y' == repeatYn) ? '반복' : '반복 안함';

			addRowHtml += '<li style="display: flex !important; width: 100% !important; float: none !important; align-items: center; border-bottom: 1px solid #eee; padding: 10px 0;">';
			addRowHtml += '<input type="hidden" name="muHospitalHolidayId" value="' + (detailList[i].muHospitalHolidayId || '') + '">';

			// Checkbox
			addRowHtml += '	<div class="check_box" style="width: 40px !important; display: flex; justify-content: center; align-items: center; float: none !important;">';
			addRowHtml += '		<input type="checkbox" name="checkHolidayRow" value="' + (detailList[i].muHospitalHolidayId || '') + '">';
			addRowHtml += '	</div>';

			// Name
			addRowHtml += '	<div class="input_box" style="flex: 1 !important; width: auto !important; float: none !important; border: none !important; padding: 0 5px;">';
			addRowHtml += '		<input type="text" name="hospitalHolidayName" value="' + hospitalHolidayName + '" placeholder="휴일명" maxlength="50" style="width: 100%; border: 1px solid #ddd; height: 34px; padding: 0 10px;">';
			addRowHtml += '	</div>';

			// Date
			// Use simpler structure to avoid CSS conflict
			addRowHtml += '	<div class="calendar_box" style="width: 140px !important; float: none !important; border: none !important; padding: 0 5px;">';
			addRowHtml += '		<div class="date_box" style="width: 100%; position: relative;">';
			addRowHtml += '			<img src="/image/web/calendar.svg" alt="calendar" style="position: absolute; left: 8px; top: 50%; transform: translateY(-50%); width: 16px;">';
			addRowHtml += '			<input type="date" class="date_picker" name="dateLocDate" value="' + locDate + '" style="width: 100%; padding-left: 30px; border: 1px solid #ddd; height: 34px; border-radius: 4px;">';
			addRowHtml += '		</div>';
			addRowHtml += '	</div>';

			// Repeat
			addRowHtml += '	<div class="select_list" style="width: 100px !important; float: none !important; border: none !important; padding: 0 5px;">';
			addRowHtml += '		<div class="select_box dropdown" style="width: 100%; height: 34px; border: 1px solid #ddd; border-radius: 4px; position: relative; background: #fff;">';
			addRowHtml += '			<button type="button" class="label" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="width: 100%; height: 100%; text-align: left; padding: 0 10px; background: transparent; border: none;">' + repeatLabel + '</button>';
			addRowHtml += '			<input type="hidden" name="repeatYn" value="' + repeatYn + '"/>';
			addRowHtml += '			<ul class="select_option_list dropdown-menu" style="width: 100%; padding: 0; margin: 0; border: 1px solid #ddd;">';
			addRowHtml += '				<li class="option_list_item first" onclick="fn_clickSelectValue(this, \'Y\', \'반복\');" style="padding: 5px; cursor: pointer; text-align: center;">반복</li>';
			addRowHtml += '				<li class="option_list_item" onclick="fn_clickSelectValue(this, \'N\', \'반복 안함\');" style="padding: 5px; cursor: pointer; text-align: center;">반복 안함</li>';
			addRowHtml += '			</ul>';
			addRowHtml += '		</div>';
			addRowHtml += '	</div>';

			// Save Button
			addRowHtml += '	<div class="save_box" style="width: 70px !important; text-align: center; float: none !important;">';
			// Using 60px width button or so
			addRowHtml += '		<button type="button" onclick="fn_saveHospitalHolidayRow(this);" style="background: #4a5568; color: #fff; border: none; padding: 0; width: 60px; height: 34px; border-radius: 4px; cursor: pointer; font-size: 13px;">저장</button>';
			addRowHtml += '	</div>';

			addRowHtml += '</li>';
		}
		$('#hospitalHolidayList').empty().html(addRowHtml).trigger("create");
	}
	else {
		// Add Header
		let headerHtml = '<li class="list_title_li" style="display: flex !important; width: 100% !important; margin: 0 !important; padding: 10px 0 !important; background: #EDF5FF; border-radius: 5px; float: none !important; position: sticky; top: 0; z-index: 10;">';
		headerHtml += '	<span class="list_title" style="width: 40px !important; display: flex; justify-content: center; align-items: center; float: none !important; border: none !important;"><input type="checkbox" id="checkAllHolidays"></span>';
		headerHtml += '	<span class="list_title" style="flex: 1 !important; text-align: center; float: none !important; border: none !important; width: auto !important;">휴일명</span>';
		headerHtml += '	<span class="list_title" style="width: 140px !important; text-align: center; float: none !important; border: none !important;">날짜</span>';
		headerHtml += '	<span class="list_title" style="width: 100px !important; text-align: center; float: none !important; border: none !important;">일정반복</span>';
		headerHtml += '	<span class="list_title" style="width: 70px !important; text-align: center; float: none !important; border: none !important;">저장</span>';
		headerHtml += '</li>';
		$('#hospitalHolidayList').html(headerHtml);

		// Show No Data message instead of empty row
		$('#hospitalHolidayList').append('<li class="no_data" style="width: 100%; text-align: center; padding: 20px 0;">지정한 휴일이 없습니다.</li>');
	}

	// 날짜  datepicker
	fn_datePicker("#hospitalHolidayList input[type='date']");

	// fn_hospitalRefreshOrderNumber is no longer needed since we don't have add/sub buttons per row.
	// But let's check full context.
}

/****************************************************************************
* row 추가 이벤트
****************************************************************************/
/****************************************************************************
* row 추가 이벤트
****************************************************************************/
/****************************************************************************
* row 추가 이벤트
****************************************************************************/
function fn_addRow(param) {
	// Remove No Data message if present
	if ($("#hospitalHolidayList .no_data").length > 0) {
		$("#hospitalHolidayList .no_data").remove();
	}

	let addRowHtml = '';
	addRowHtml += '<li style="display: flex !important; width: 100% !important; float: none !important; align-items: center; border-bottom: 1px solid #eee; padding: 10px 0;">';
	addRowHtml += '<input type="hidden" name="muHospitalHolidayId" value="">';

	// Checkbox
	addRowHtml += '	<div class="check_box" style="width: 40px !important; display: flex; justify-content: center; align-items: center; float: none !important;">';
	addRowHtml += '		<input type="checkbox" name="checkHolidayRow" value="">';
	addRowHtml += '	</div>';

	// Name
	addRowHtml += '	<div class="input_box" style="flex: 1 !important; width: auto !important; float: none !important; border: none !important; padding: 0 5px;">';
	addRowHtml += '		<input type="text" name="hospitalHolidayName" value="" placeholder="휴일명" maxlength="50" style="width: 100%; border: 1px solid #ddd; height: 34px; padding: 0 10px;">';
	addRowHtml += '	</div>';

	// Date
	addRowHtml += '	<div class="calendar_box" style="width: 140px !important; float: none !important; border: none !important; padding: 0 5px;">';
	addRowHtml += '		<div class="date_box" style="width: 100%; position: relative;">';
	addRowHtml += '			<img src="/image/web/calendar.svg" alt="calendar" style="position: absolute; left: 8px; top: 50%; transform: translateY(-50%); width: 16px;">';
	addRowHtml += '			<input type="date" class="date_picker" name="dateLocDate" style="width: 100%; padding-left: 30px; border: 1px solid #ddd; height: 34px; border-radius: 4px;">';
	addRowHtml += '		</div>';
	addRowHtml += '	</div>';

	// Repeat
	addRowHtml += '	<div class="select_list" style="width: 100px !important; float: none !important; border: none !important; padding: 0 5px;">';
	addRowHtml += '		<div class="select_box dropdown" style="width: 100%; height: 34px; border: 1px solid #ddd; border-radius: 4px; position: relative; background: #fff;">';
	addRowHtml += '			<button type="button" class="label" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="width: 100%; height: 100%; text-align: left; padding: 0 10px; background: transparent; border: none;">반복 안함</button>';
	addRowHtml += '			<input type="hidden" name="repeatYn" value="N"/>';
	addRowHtml += '			<ul class="select_option_list dropdown-menu" style="width: 100%; padding: 0; margin: 0; border: 1px solid #ddd;">';
	addRowHtml += '				<li class="option_list_item first" onclick="fn_clickSelectValue(this, \'Y\', \'반복\');" style="padding: 5px; cursor: pointer; text-align: center;">반복</li>';
	addRowHtml += '				<li class="option_list_item" onclick="fn_clickSelectValue(this, \'N\', \'반복 안함\');" style="padding: 5px; cursor: pointer; text-align: center;">반복 안함</li>';
	addRowHtml += '			</ul>';
	addRowHtml += '		</div>';
	addRowHtml += '	</div>';

	// Save Button
	addRowHtml += '	<div class="save_box" style="width: 70px !important; text-align: center; float: none !important;">';
	addRowHtml += '		<button type="button" onclick="fn_saveHospitalHolidayRow(this);" style="background: #4a5568; color: #fff; border: none; padding: 0; width: 60px; height: 34px; border-radius: 4px; cursor: pointer; font-size: 13px;">저장</button>';
	addRowHtml += '	</div>';

	addRowHtml += '</li>';
	$('#hospitalHolidayList').append(addRowHtml).trigger("create");

	// 날짜  datepicker
	fn_datePicker("#hospitalHolidayList input[type='date']");

	// fn_hospitalRefreshOrderNumber is removed
}

/****************************************************************************
* row 삭제 이벤트
****************************************************************************/
function fn_removeRow(param) {
	let liLength = $('#hospitalHolidayList').children('li').length;

	if (2 < liLength) {
		let liNum = $(param).closest('li').prevAll().length;
		$('#hospitalHolidayList').children('li').eq(liNum).remove();
	}
	else {
		modalEvent.warning("입력 오류", "더 이상 삭제할 수 없습니다.");
	}
}

/****************************************************************************
* row 삭제 이벤트
****************************************************************************/
function fn_removeRow2(param) {
	let liNum = $(param).closest('li').prevAll().length;
	$('#hospitalHolidayList').children('li').eq(liNum).remove();

	fn_addRow();
}

/****************************************************************************
* 전체 row 버튼 변경
****************************************************************************/
function fn_hospitalRefreshOrderNumber(param) {
	// row 추가/삭제 버튼 처리
	$(param).find(".add_box").hide();
	$(param).find('.subtract_box').show();
	$(param).children("li:eq(1)").find(".subtract_box").hide();
	$(param).children("li:eq(1)").find(".add_box").show();
}

/****************************************************************************
* 병원 정보 수정
****************************************************************************/
function fn_updateHospital() {
	let muHospitalId = $("#muHospitalId").val();

	let monOpenYn = $("#checkMonOpenYn").is(':checked') == true ? 'Y' : 'N';
	let monOpenStartTime = $("#monOpenStartTime").val();
	let monOpenEndTime = $("#monOpenEndTime").val();
	let monBreakStartTime = $("#monBreakStartTime").val();
	let monBreakEndTime = $("#monBreakEndTime").val();

	let tueOpenYn = $("#checkTueOpenYn").is(':checked') == true ? 'Y' : 'N';
	let tueOpenStartTime = $("#tueOpenStartTime").val();
	let tueOpenEndTime = $("#tueOpenEndTime").val();
	let tueBreakStartTime = $("#tueBreakStartTime").val();
	let tueBreakEndTime = $("#tueBreakEndTime").val();

	let wedOpenYn = $("#checkWedOpenYn").is(':checked') == true ? 'Y' : 'N';
	let wedOpenStartTime = $("#wedOpenStartTime").val();
	let wedOpenEndTime = $("#wedOpenEndTime").val();
	let wedBreakStartTime = $("#wedBreakStartTime").val();
	let wedBreakEndTime = $("#wedBreakEndTime").val();

	let thuOpenYn = $("#checkThuOpenYn").is(':checked') == true ? 'Y' : 'N';
	let thuOpenStartTime = $("#thuOpenStartTime").val();
	let thuOpenEndTime = $("#thuOpenEndTime").val();
	let thuBreakStartTime = $("#thuBreakStartTime").val();
	let thuBreakEndTime = $("#thuBreakEndTime").val();

	let friOpenYn = $("#checkFriOpenYn").is(':checked') == true ? 'Y' : 'N';
	let friOpenStartTime = $("#friOpenStartTime").val();
	let friOpenEndTime = $("#friOpenEndTime").val();
	let friBreakStartTime = $("#friBreakStartTime").val();
	let friBreakEndTime = $("#friBreakEndTime").val();

	let satOpenYn = $("#checkSatOpenYn").is(':checked') == true ? 'Y' : 'N';
	let satOpenStartTime = $("#satOpenStartTime").val();
	let satOpenEndTime = $("#satOpenEndTime").val();
	let satBreakStartTime = $("#satBreakStartTime").val();
	let satBreakEndTime = $("#satBreakEndTime").val();

	let sunOpenYn = $("#checkSunOpenYn").is(':checked') == true ? 'Y' : 'N';
	let sunOpenStartTime = $("#sunOpenStartTime").val();
	let sunOpenEndTime = $("#sunOpenEndTime").val();
	let sunBreakStartTime = $("#sunBreakStartTime").val();
	let sunBreakEndTime = $("#sunBreakEndTime").val();

	let publicHolidayUseYn = $("#checkPublicHolidayUseYn").is(':checked') == true ? 'Y' : 'N';


	// 휴일 정보
	let detailArray = new Object();

	if ("Y" != updateUseYn) {
		modalEvent.warning("", "수정 권한이 없습니다.");
		return false;
	}

	if (!muHospitalId) {
		modalEvent.warning("", "병원 정보가 없습니다.");
		return false;
	}

	if ('Y' == monOpenYn) {
		if (!monOpenStartTime) {
			modalEvent.warning("", "월요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!monOpenEndTime) {
			modalEvent.warning("", "월요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!monBreakStartTime) {
			modalEvent.warning("", "월요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!monBreakEndTime) {
			modalEvent.warning("", "월요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		monOpenYn = 'N'
		monOpenStartTime = '00:00';
		monOpenEndTime = '00:00';
		monBreakStartTime = '00:00';
		monBreakEndTime = '00:00';
	}


	if ('Y' == tueOpenYn) {
		if (!tueOpenStartTime) {
			modalEvent.warning("", "화요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!tueOpenEndTime) {
			modalEvent.warning("", "화요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!tueBreakStartTime) {
			modalEvent.warning("", "화요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!tueBreakEndTime) {
			modalEvent.warning("", "화요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		tueOpenYn = 'N'
		tueOpenStartTime = '00:00';
		tueOpenEndTime = '00:00';
		tueBreakStartTime = '00:00';
		tueBreakEndTime = '00:00';
	}

	if ('Y' == wedOpenYn) {
		if (!wedOpenStartTime) {
			modalEvent.warning("", "수요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!wedOpenEndTime) {
			modalEvent.warning("", "수요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!wedBreakStartTime) {
			modalEvent.warning("", "수요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!wedBreakEndTime) {
			modalEvent.warning("", "수요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		wedOpenYn = 'N'
		wedOpenStartTime = '00:00';
		wedOpenEndTime = '00:00';
		wedBreakStartTime = '00:00';
		wedBreakEndTime = '00:00';
	}

	if ('Y' == thuOpenYn) {
		if (!thuOpenStartTime) {
			modalEvent.warning("", "목요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!thuOpenEndTime) {
			modalEvent.warning("", "목요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!thuBreakStartTime) {
			modalEvent.warning("", "목요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!thuBreakEndTime) {
			modalEvent.warning("", "목요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		thuOpenYn = 'N'
		thuOpenStartTime = '00:00';
		thuOpenEndTime = '00:00';
		thuBreakStartTime = '00:00';
		thuBreakEndTime = '00:00';
	}

	if ('Y' == friOpenYn) {
		if (!friOpenStartTime) {
			modalEvent.warning("", "금요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!friOpenEndTime) {
			modalEvent.warning("", "금요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!friBreakStartTime) {
			modalEvent.warning("", "금요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!friBreakEndTime) {
			modalEvent.warning("", "금요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		friOpenYn = 'N'
		friOpenStartTime = '00:00';
		friOpenEndTime = '00:00';
		friBreakStartTime = '00:00';
		friBreakEndTime = '00:00';
	}

	if ('Y' == satOpenYn) {
		if (!satOpenStartTime) {
			modalEvent.warning("", "토요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!satOpenEndTime) {
			modalEvent.warning("", "토요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!satBreakStartTime) {
			modalEvent.warning("", "토요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!satBreakEndTime) {
			modalEvent.warning("", "토요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		satOpenYn = 'N'
		satOpenStartTime = '00:00';
		satOpenEndTime = '00:00';
		satBreakStartTime = '00:00';
		satBreakEndTime = '00:00';
	}

	if ('Y' == sunOpenYn) {
		if (!sunOpenStartTime) {
			modalEvent.warning("", "일요일 운영 시작시간 정보가 없습니다.");
			return false;
		}

		if (!sunOpenEndTime) {
			modalEvent.warning("", "일요일 운영 종료시간 정보가 없습니다.");
			return false;
		}

		if (!sunBreakStartTime) {
			modalEvent.warning("", "일요일 휴게 시작시간 정보가 없습니다.");
			return false;
		}

		if (!sunBreakEndTime) {
			modalEvent.warning("", "일요일 휴게 종료시간 정보가 없습니다.");
			return false;
		}
	}
	else {
		sunOpenYn = 'N'
		sunOpenStartTime = '00:00';
		sunOpenEndTime = '00:00';
		sunBreakStartTime = '00:00';
		sunBreakEndTime = '00:00';
	}

	if (!publicHolidayUseYn) {
		modalEvent.warning("", "법정 공휴일 정보가 없습니다.");
		return false;
	}

	// 휴일정보
	let holidayLi = $('#hospitalHolidayList').children('li');
	let liLength = holidayLi.length;

	let tempArray = new Array();
	for (let i = 1; i < liLength; i++) {
		let hospitalHolidayName = holidayLi.eq(i).find('input[name="hospitalHolidayName"]').val();
		let locDate = holidayLi.eq(i).find('input[name="dateLocDate"]').val();
		let repeatYn = holidayLi.eq(i).find('input[name="repeatYn"]').val();

		let arr_sub = new Object();
		arr_sub.hospitalHolidayName = hospitalHolidayName;
		arr_sub.locDate = locDate;
		arr_sub.repeatYn = repeatYn;
		tempArray.push(arr_sub);

		detailArray.data = tempArray;
	}

	modalEvent.info("수정", "선택한 병원 정보를 수정하시겠습니까?", function () {
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muHospitalId", muHospitalId);
		formData.append("monOpenYn", monOpenYn);
		formData.append("monOpenStartTime", monOpenStartTime);
		formData.append("monOpenEndTime", monOpenEndTime);
		formData.append("monBreakStartTime", monBreakStartTime);
		formData.append("monBreakEndTime", monBreakEndTime);
		formData.append("tueOpenYn", tueOpenYn);
		formData.append("tueOpenStartTime", tueOpenStartTime);
		formData.append("tueOpenEndTime", tueOpenEndTime);
		formData.append("tueBreakStartTime", tueBreakStartTime);
		formData.append("tueBreakEndTime", tueBreakEndTime);
		formData.append("wedOpenYn", wedOpenYn);
		formData.append("wedOpenStartTime", wedOpenStartTime);
		formData.append("wedOpenEndTime", wedOpenEndTime);
		formData.append("wedBreakStartTime", wedBreakStartTime);
		formData.append("wedBreakEndTime", wedBreakEndTime);
		formData.append("thuOpenYn", thuOpenYn);
		formData.append("thuOpenStartTime", thuOpenStartTime);
		formData.append("thuOpenEndTime", thuOpenEndTime);
		formData.append("thuBreakStartTime", thuBreakStartTime);
		formData.append("thuBreakEndTime", thuBreakEndTime);
		formData.append("friOpenYn", friOpenYn);
		formData.append("friOpenStartTime", friOpenStartTime);
		formData.append("friOpenEndTime", friOpenEndTime);
		formData.append("friBreakStartTime", friBreakStartTime);
		formData.append("friBreakEndTime", friBreakEndTime);
		formData.append("satOpenYn", satOpenYn);
		formData.append("satOpenStartTime", satOpenStartTime);
		formData.append("satOpenEndTime", satOpenEndTime);
		formData.append("satBreakStartTime", satBreakStartTime);
		formData.append("satBreakEndTime", satBreakEndTime);
		formData.append("sunOpenYn", sunOpenYn);
		formData.append("sunOpenStartTime", sunOpenStartTime);
		formData.append("sunOpenEndTime", sunOpenEndTime);
		formData.append("sunBreakStartTime", sunBreakStartTime);
		formData.append("sunBreakEndTime", sunBreakEndTime);
		formData.append("publicHolidayUseYn", publicHolidayUseYn);

		$.ajax({
			url: encodeURI('/webhospital/updateHospital.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			async: true,
			success: function (data) {
				if ('0' == data.msgCode) {
					modalEvent.success("수정 성공", data.msgDesc, function () {
						fn_selectHospitalJson(true);
					});
				}
				else {
					modalEvent.danger("수정 오류", data.msgDesc);
				}
			},
			error: function (xhr, status, error) {
				modalEvent.danger("수정 오류", "수정 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
			},
			beforeSend: function () {

			},
			complete: function () {

			}
		});
	});
}

/****************************************************************************
* 운영여부 변경 이벤트
* type : 요일(mon:월요일....)
****************************************************************************/
function fn_changeOpenYn(target, type) {
	let checked = $(target).is(':checked');

	if (checked) {
		// 기본 셋팅
		fn_setTimeValue("sel" + type + "OpenStartTime", "09:00");
		fn_setTimeValue("sel" + type + "OpenEndTime", "19:00");
		fn_setTimeValue("sel" + type + "BreakStartTime", "14:00");
		fn_setTimeValue("sel" + type + "BreakEndTime", "15:00");
		$(target).parents("li").find("button").prop("disabled", false);
		$(target).closest('li').addClass('on');
	}
	else {
		// 초기화
		$(target).parents("li").find("button").text("00:00");
		$(target).parents("li").find("input").text("00:00");
		$(target).parents("li").find("button").prop("disabled", true);
		$(target).closest('li').removeClass('on');
	}
}

/****************************************************************************
* select box 선택 값 셋팅
****************************************************************************/
function fn_clickSelectValue(target, param, paramText) {
	$(target).parent().siblings("button").text(paramText);
	$(target).parent().siblings("input").val(param);
}

/****************************************************************************
* 페이지 init
****************************************************************************/
function fn_pageInit() {
	// 탭 전환 시 캘린더 리사이즈 (풀캘린더 v6)
	$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		if (e.target.hash === '#schedule') {
			if (window.fcCalendar) {
				window.fcCalendar.render();
			}
		}
	});

	// 기본 센터: 다이어트
	$("#currentCenterDivCd").val('DIET');

	// 병원 상세 조회
	fn_selectHospitalJson();
}

/****************************************************************************
* 센터 전환
****************************************************************************/
function fn_switchCenter(centerDivCd) {
	$("#currentCenterDivCd").val(centerDivCd);
	fn_resetOperatingHoursForm();
	fn_selectHospitalJson();
}

/****************************************************************************
* 운영시간 폼 초기화
****************************************************************************/
function fn_resetOperatingHoursForm() {
	$('#checkMonOpenYn, #checkTueOpenYn, #checkWedOpenYn, #checkThuOpenYn, #checkFriOpenYn, #checkSatOpenYn, #checkSunOpenYn').prop('checked', false).trigger('change');
	$('#checkPublicHolidayUseYn').prop('checked', false);
	// 병원휴일 리스트 초기화
	$('#hospitalHolidayList').empty();
}


/****************************************************************************
* 병원 휴일 정보 조회 (달력용)
****************************************************************************/
function fn_selectHospitalHolidayList() {
	let calendarEl = document.getElementById('calendar');
	let calendar = new FullCalendar.Calendar(calendarEl, {
		initialView: 'dayGridMonth',
		fixedWeekCount: false,
		contentHeight: 'auto',
		headerToolbar: {
			left: 'prev,next today',
			center: 'title',
			right: 'dayGridMonth,listMonth'
		},
		locale: 'ko',
		dateClick: function (info) {
			fn_openSchedulePopup(info.dateStr);
		},
		events: function (info, successCallback, failureCallback) {
			let formData = new FormData();
			formData.append("paramStartDate", info.startStr);
			formData.append("paramEndDate", info.endStr);
			formData.append("muHospitalId", $("#muHospitalId").val());

			$.ajax({
				url: encodeURI('/webhospital/selectHospitalHolidayList.do'),
				data: formData,
				dataType: "json",
				processData: false,
				contentType: false,
				type: 'POST',
				success: function (data) {
					if ('0' == data.msgCode) {
						let events = [];
						let rows = data.rows;
						if (rows) {
							for (let i = 0; i < rows.length; i++) {
								let row = rows[i];
								let color = '#3985EA'; // 기본
								if (row.dateType === 'publicHoliday') {
									color = '#FF5252'; // 법정공휴일 Red
								} else if (row.dateType === 'hospitalHoliday') {
									color = '#2ECC71'; // 병원휴일 Green
								} else if (row.dateType === 'hospitalSchedule') {
									color = '#f39c12'; // 스케줄 Orange
								}

								events.push({
									title: row.hospitalHolidayName || row.publicHolidayName || '휴일',
									start: row.locDate,
									color: color,
									allDay: true
								});
							}
						}
						successCallback(events);
					} else {
						failureCallback(data.msgDesc);
					}
				},
				error: function () {
					failureCallback('실패');
				}
			});
		}
	});
	calendar.render();
	window.fcCalendar = calendar; // 전역 변수로 저장
}

/****************************************************************************
* 스케줄 팝업 열기
****************************************************************************/
function fn_openSchedulePopup(date) {
	// 시간 옵션 초기화 (최초 1회)
	if ($('#popOpenStartTime option').length == 0) {
		fn_initTimeSelect();
	}

	$("#popScheduleDate").val(date);
	$("#popMuHospitalScheduleId").val("");

	// 상세 조회
	let formData = new FormData();
	formData.append("muHospitalId", $("#muHospitalId").val());
	formData.append("searchDate", date);

	$.ajax({
		url: encodeURI('/webhospital/selectHospitalScheduleDetail.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function (data) {
			if ('0' == data.msgCode) {
				let row = data.rows;
				if (row) {
					// 수정 모드
					$("#popMuHospitalScheduleId").val(row.muHospitalScheduleId);
					$("input[name='popOpenYn'][value='" + row.openYn + "']").prop("checked", true);

					if (row.openYn == 'Y') {
						$("#popOpenStartTime").val(row.openStartTime);
						$("#popOpenEndTime").val(row.openEndTime);
						$("#popBreakStartTime").val(row.breakStartTime);
						$("#popBreakEndTime").val(row.breakEndTime);
						$("#popTimeArea").show();
					} else {
						$("#popTimeArea").hide();
					}

					$("#btnDeleteSchedule").show();
				} else {
					// 신규 모드

					// 1. 휴일 여부 확인 (서버에서 전달된 isHoliday 값)
					if (data.isHoliday == 'Y') {
						// 휴일이면 기본값: 휴무
						$("input[name='popOpenYn'][value='N']").prop("checked", true);
						$("#popTimeArea").hide();
						$("#btnDeleteSchedule").hide();
						$("#schedulePopup").show();
						return;
					}

					// 2. 휴일이 아니면 요일별 기본 설정 따름
					let dayOfWeek = new Date(date).getDay(); // 0:Sun, 1:Mon...
					let days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
					let dayStr = days[dayOfWeek];

					// 메인 화면의 해당 요일 설정 가져오기
					let isOpen = $("#check" + dayStr + "OpenYn").is(":checked");
					$("input[name='popOpenYn'][value='" + (isOpen ? 'Y' : 'N') + "']").prop("checked", true);

					if (isOpen) {
						$("#popOpenStartTime").val($("#" + dayStr.toLowerCase() + "OpenStartTime").val());
						$("#popOpenEndTime").val($("#" + dayStr.toLowerCase() + "OpenEndTime").val());
						$("#popBreakStartTime").val($("#" + dayStr.toLowerCase() + "BreakStartTime").val());
						$("#popBreakEndTime").val($("#" + dayStr.toLowerCase() + "BreakEndTime").val());
						$("#popTimeArea").show();
					} else {
						$("#popTimeArea").hide();
					}

					$("#btnDeleteSchedule").hide();
				}
				$("#schedulePopup").show();
			} else {
				modalEvent.danger("오류", data.msgDesc);
			}
		},
		error: function () {
			modalEvent.danger("오류", "조회 중 오류가 발생했습니다.");
		}
	});
}

/****************************************************************************
* 스케줄 팝업 닫기
****************************************************************************/
function fn_closeSchedulePopup() {
	$("#schedulePopup").hide();
}

/****************************************************************************
* 스케줄 저장
****************************************************************************/
function fn_saveSchedule() {
	let openYn = $("input[name='popOpenYn']:checked").val();

	if (openYn == 'Y') {
		if (!$("#popOpenStartTime").val() || !$("#popOpenEndTime").val()) {
			modalEvent.warning("알림", "운영시간을 선택해주세요.");
			return;
		}
	}

	let formData = new FormData();
	formData.append("muHospitalId", $("#muHospitalId").val());
	formData.append("muHospitalScheduleId", $("#popMuHospitalScheduleId").val());
	formData.append("scheduleDate", $("#popScheduleDate").val());
	formData.append("openYn", openYn);

	if (openYn == 'Y') {
		formData.append("openStartTime", $("#popOpenStartTime").val());
		formData.append("openEndTime", $("#popOpenEndTime").val());
		formData.append("breakStartTime", $("#popBreakStartTime").val());
		formData.append("breakEndTime", $("#popBreakEndTime").val());
	} else {
		// 휴무일 경우 시간 초기화
		formData.append("openStartTime", "00:00");
		formData.append("openEndTime", "00:00");
		formData.append("breakStartTime", "00:00");
		formData.append("breakEndTime", "00:00");
	}

	$.ajax({
		url: encodeURI('/webhospital/saveHospitalSchedule.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function (data) {
			if ('0' == data.msgCode) {
				fn_closeSchedulePopup();
				window.fcCalendar.refetchEvents(); // 달력 갱신
			} else {
				modalEvent.danger("오류", data.msgDesc);
			}
		},
		error: function () {
			modalEvent.danger("오류", "저장 중 오류가 발생했습니다.");
		}
	});
}

/****************************************************************************
* 스케줄 삭제
****************************************************************************/
function fn_deleteSchedule() {
	let formData = new FormData();
	formData.append("muHospitalId", $("#muHospitalId").val());
	formData.append("muHospitalScheduleId", $("#popMuHospitalScheduleId").val());

	$.ajax({
		url: encodeURI('/webhospital/deleteHospitalSchedule.do'),
		data: formData,
		dataType: "json",
		processData: false,
		contentType: false,
		type: 'POST',
		success: function (data) {
			if ('0' == data.msgCode) {
				fn_closeSchedulePopup();
				window.fcCalendar.refetchEvents(); // 달력 갱신
			} else {
				modalEvent.danger("오류", data.msgDesc);
			}
		},
		error: function () {
			modalEvent.danger("오류", "삭제 중 오류가 발생했습니다.");
		}
	});
}

/****************************************************************************
* 팝업 운영여부 변경
****************************************************************************/
function fn_changePopOpenYn(target) {
	if ($(target).val() == 'Y') {
		$("#popTimeArea").show();
	} else {
		$("#popTimeArea").hide();
	}
}

/****************************************************************************
* 시간 옵션 초기화
****************************************************************************/
function fn_initTimeSelect() {
	let html = "";
	for (let i = 0; i < 24; i++) {
		let hour = i < 10 ? "0" + i : i;
		html += '<option value="' + hour + ':00">' + hour + ':00</option>';
		html += '<option value="' + hour + ':30">' + hour + ':30</option>';
	}
	$("#popOpenStartTime, #popOpenEndTime, #popBreakStartTime, #popBreakEndTime").html(html);
}

/****************************************************************************
* 페이지 event
****************************************************************************/
function fn_pageEvent() {
	// 월요일 운영여부 체크
	$("#checkMonOpenYn").change(function () {
		fn_changeOpenYn(this, 'Mon');
	});

	// 화요일 운영여부 체크
	$("#checkTueOpenYn").change(function () {
		fn_changeOpenYn(this, 'Tue');
	});

	// 수요일 운영여부 체크
	$("#checkWedOpenYn").change(function () {
		fn_changeOpenYn(this, 'Wed');
	});

	// 목요일 운영여부 체크
	$("#checkThuOpenYn").change(function () {
		fn_changeOpenYn(this, 'Thu');
	});

	// 금요일 운영여부 체크
	$("#checkFriOpenYn").change(function () {
		fn_changeOpenYn(this, 'Fri');
	});

	// 토요일 운영여부 체크
	$("#checkSatOpenYn").change(function () {
		fn_changeOpenYn(this, 'Sat');
	});

	// 일요일 운영여부 체크
	$("#checkSunOpenYn").change(function () {
		fn_changeOpenYn(this, 'Sun');
	});

	// 저장 버튼
	$("#btnUpdateHospital").click(function () {
		fn_updateHospital();
	});

	// [New] 취소 버튼 (운영시간 탭)
	$("#btnCancelHospital").click(function () {
		modalEvent.info("취소", "수정 중인 내용을 취소하고 초기화하시겠습니까?", function () {
			fn_selectHospitalJson(true);
		});
	});

	// 병원 휴일 정보 수정 (신규 버튼 - 하단 일괄저장이 필요할 경우 사용)
	$("#btnUpdateHospitalHoliday").click(function () {
		fn_updateHospitalHoliday();
	});

	// [New] Row Add Button
	$("#btnAddRow").click(function () {
		fn_addRow();
	});

	// [New] Row Remove Button (Checked items)
	$("#btnRemoveRow").click(function () {
		fn_deleteCheckedHolidays();
	});

	// [New] Check All
	$(document).on("click", "#checkAllHolidays", function () {
		$("#hospitalHolidayList input[name='checkHolidayRow']").prop("checked", $(this).is(":checked"));
	});
}

/****************************************************************************
* 병원 휴일 행별 저장
****************************************************************************/
function fn_saveHospitalHolidayRow(btn) {
	let $li = $(btn).closest('li');
	let muHospitalId = $("#muHospitalId").val();
	let muHospitalHolidayId = $li.find('input[name="muHospitalHolidayId"]').val();
	let hospitalHolidayName = $li.find('input[name="hospitalHolidayName"]').val();
	let locDate = $li.find('input[name="dateLocDate"]').val();
	let repeatYn = $li.find('input[name="repeatYn"]').val();

	if (!hospitalHolidayName || hospitalHolidayName.trim() === "") {
		modalEvent.danger("오류", "휴일명을 입력해주세요.");
		return;
	}
	if (!locDate) {
		modalEvent.danger("오류", "날짜를 선택해주세요.");
		return;
	}

	modalEvent.info("저장", "해당 휴일을 저장하시겠습니까?", function () {
		let formData = new FormData();
		formData.append("menuClass", menuClass);
		formData.append("muHospitalId", muHospitalId);
		formData.append("muHospitalHolidayId", muHospitalHolidayId || "");
		formData.append("hospitalHolidayName", hospitalHolidayName);
		formData.append("locDate", locDate);
		formData.append("repeatYn", repeatYn || "N");

		$.ajax({
			url: encodeURI('/webhospital/saveHospitalHoliday.do'),
			data: formData,
			dataType: "json",
			processData: false,
			contentType: false,
			type: 'POST',
			success: function (data) {
				if ('0' == data.msgCode) {
					modalEvent.success("성공", "저장되었습니다.", function () {
						// 캘린더 리렌더링
						if (window.fcCalendar) {
							window.fcCalendar.refetchEvents();
						}
						// 휴일 목록 새로고침 (저장 후 ID가 변경될 수 있으므로)
						fn_selectHospitalJson();
					});
				} else {
					modalEvent.danger("오류", data.msgDesc);
				}
			},
			error: function () {
				modalEvent.danger("오류", "저장 중 오류가 발생했습니다.");
			}
		});
	});
}

/****************************************************************************
* 병원 지정 휴일 선택 삭제 (체크된 row 삭제)
****************************************************************************/
function fn_deleteCheckedHolidays() {
	let muHospitalId = $("#muHospitalId").val();
	let checkedBoxes = $('input[name="checkHolidayRow"]:checked');

	if (checkedBoxes.length === 0) {
		modalEvent.danger("알림", "삭제할 휴일을 선택해주세요.");
		return;
	}

	// 신규 row (ID가 없는 것)는 DOM에서 바로 제거, 기존 row는 서버에 삭제 요청
	let idsToDelete = [];
	let $newRows = $();

	checkedBoxes.each(function () {
		let holidayId = $(this).val();
		if (holidayId && holidayId.trim() !== "") {
			idsToDelete.push(holidayId.trim());
		} else {
			$newRows = $newRows.add($(this).closest('li'));
		}
	});

	modalEvent.info("삭제", "선택한 휴일 " + checkedBoxes.length + "건을 삭제하시겠습니까?", function () {
		// 신규 row는 DOM에서 즉시 제거
		$newRows.remove();

		if (idsToDelete.length > 0) {
			// 기존 row는 서버에 삭제 요청
			let formData = new FormData();
			formData.append("menuClass", menuClass);
			formData.append("muHospitalId", muHospitalId);
			formData.append("holidayIds", idsToDelete.join(","));

			$.ajax({
				url: encodeURI('/webhospital/deleteHospitalHolidays.do'),
				data: formData,
				dataType: "json",
				processData: false,
				contentType: false,
				type: 'POST',
				success: function (data) {
					if ('0' == data.msgCode) {
						modalEvent.success("성공", "삭제되었습니다.", function () {
							if (window.fcCalendar) {
								window.fcCalendar.refetchEvents();
							}
							fn_selectHospitalJson();
						});
					} else {
						modalEvent.danger("오류", data.msgDesc);
					}
				},
				error: function () {
					modalEvent.danger("오류", "삭제 중 오류가 발생했습니다.");
				}
			});
		} else {
			// 신규 row만 삭제한 경우
			modalEvent.success("성공", "삭제되었습니다.");
			// 남은 li가 헤더뿐이면 'no_data' 표시
			if ($("#hospitalHolidayList li").not('.list_title_li').length === 0) {
				$('#hospitalHolidayList').append('<li class="no_data" style="width: 100%; text-align: center; padding: 20px 0;">지정한 휴일이 없습니다.</li>');
			}
		}
	});
}

$(function () {
	// 페이지 init
	fn_pageInit();

	// 페이지 event
	fn_pageEvent();
});