
//Modal
modalShow = function(actionUrl, title, modalId) {
    if(!modalId) {
        logger('modalId is empty!');
        return false;
    }
    const md = new bootstrap.Modal(modalId, {});
    const $modal = $(modalId);

    $modal.find('.modal-body').load(actionUrl, function(response, status, xhr) {
        if (status === "error") {
            logger(xhr.status);
        }
        $modal.find('.modal-title').text(title);
        md.show();
    });
};

popupWindow = function(url, title, w, h) {
	var screenX = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft;
	var	screenY = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop;
    var left = Math.round((window.screen.width/2)-(w/2)) + screenX;
    var top = Math.round((window.screen.height/2)-(h/2)) + screenY;
    var popup =window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, '
            + 'menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=' + w
            + ', height=' + h + ', top=' + top + ', left=' + left);
	try{
		popup.focus();
	}catch (e) {
		bootboxAlert({title:'확인',size:'small',message:'팝업이 차단되어 있습니다.</br> 자세한 해제방법은 FAQ를 참고해주시기 바랍니다.'});
	}
};

const imgUploadCallback = (cb,value,meta,seCode) => {
	const input = document.createElement('input');
	input.setAttribute('type', 'file');
	input.setAttribute('accept', 'image/*');

	input.addEventListener('change', (e) => {
		const file = e.target.files[0];
		let form_data = new FormData();
		form_data.append('atchFile', file);
		form_data.append('atchFileIdntfNo', $('#imgAtchFileId').val());
		form_data.append('seCode', seCode);
		$.ajax({
			data: form_data,
			type: "POST",
			url: '/comn/file/imgUpload.json',
			cache: false,
			contentType: false,
			enctype: 'multipart/form-data',
			processData: false,
			success: function(result) {
				let atchFileIdntfNo = result.data.atchFileIdntfNo;
				let fileSn = result.data.fileSn;
				//let thumbUrl = "/fms/getThumbnail.do?atchFileIdntfNo="+atchFileIdntfNo+'&fileSn='+fileSn
				let imageUrl = "/comn/file/getImage.do?atchFileIdntfNo="+atchFileIdntfNo+'&fileSn='+fileSn

				cb(imageUrl, { title: file.name });
			}
		});
	});
	input.click();
}

const fileUploadCallback = (cb,value,meta,seCode) => {
	const input = document.createElement('input');
	input.setAttribute('type', 'file');
	input.setAttribute('accept', '.zip,.pdf,.hwp');

	input.addEventListener('change', (e) => {
		const file = e.target.files[0];
		if(file.size > 10000000){
			alert('10M 미만 파일만 업로드 가능합니다.');
			return false;
		}
		let form_data = new FormData();
		form_data.append('atchFile', file);
		form_data.append('atchFileIdntfNo', $('#imgAtchFileId').val());
		form_data.append('seCode', seCode);
		$.ajax({
			data: form_data,
			type: "POST",
			url: '/comn/file/fileUpload.json',
			cache: false,
			contentType: false,
			enctype: 'multipart/form-data',
			processData: false,
			success: function(result) {
				let atchFileIdntfNo = result.data.atchFileIdntfNo;
				let fileSn = result.data.fileSn;
				let fileUrl = "/comn/file/downloadFile.do?atchFileIdntfNo="+atchFileIdntfNo+'&fileSn='+fileSn

				cb(fileUrl, { title: file.name },{ text: file.name });
			},
		});
	});
	input.click();
}


let uploadChain = Promise.resolve();

const image_upload_handler = (blobInfo, progress) =>
	new Promise((resolve, reject) => {
		uploadChain = uploadChain
			.then(() => {
				return new Promise(r => setTimeout(r, 100));
			})
			.then(() => {
				// 2. 실제 업로드 수행 (기존 로직)
				return new Promise((chainResolve) => {
					const xhr = new XMLHttpRequest();
					xhr.withCredentials = false;
					xhr.open('POST', '/comn/file/imgUpload.json');

					xhr.onload = () => {
						if (xhr.status === 403) {
							reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
							chainResolve(); // 다음 파일 업로드 진행을 위해 체인 해제
							return;
						}

						if (xhr.status < 200 || xhr.status >= 300) {
							reject('HTTP Error: ' + xhr.status);
							chainResolve();
							return;
						}

						let json;
						try {
							json = JSON.parse(xhr.responseText);
						} catch (e) {
							reject('Invalid JSON: ' + xhr.responseText);
							chainResolve();
							return;
						}

						if (!json || typeof json.success !== 'boolean') {
							reject('Invalid JSON Response structure');
							chainResolve();
							return;
						}

						if (json.success) {
							let result = json;
							let atchFileIdntfNo = result.data.atchFileIdntfNo;
							let fileSn = result.data.fileSn;

							let imageUrl = "/comn/file/getImage.do?atchFileIdntfNo=" + atchFileIdntfNo + '&fileSn=' + fileSn;

							// 성공 시 TinyMCE에 URL 전달
							resolve(imageUrl);
						} else {
							reject(json.message || 'Image upload failed on server.');
						}

						chainResolve();
					};

					xhr.onerror = () => {
						reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
						chainResolve();
					};

					const formData = new FormData();
					formData.append('atchFile', blobInfo.blob());

					xhr.send(formData);
				});
			})
			.catch(() => {
			});
	});

/**  Web Editor: tinymce */
initWebEditor_tinymce  = function(seCode) {
	tinymce.remove();
	const $contentsCount = $('#contents-count');
	tinymce.init({
		content_style: "body p { margin-block: 0; }",
		selector: '.tinymce-editor',
		language: 'ko_KR', //언어팩 설정
		branding: false, //하단부 브랜드 로고 제거
		promotion: false, //upgrade button 제거
		menubar: '',
		element_format: 'xhtml',
		quickbars_insert_toolbar: false,
		placeholder: '내용을 입력하세요.',
		// 기본 삽입 및 도구에 '이미지','코드' 추가
		plugins: [
			'image',
			'link',
			'preview',
			'searchreplace',
			'table',
			'code',
			'quickbars',
			'media',
			//'wordcount'
		],
		file_picker_types: 'file image media',
		min_height: 500,
		//툴바 customizing
		toolbar: [
			{ name: 'font', items: [ 'fontfamily', 'fontsize' ] },
			{ name: 'formatting', items: [ 'bold', 'italic', 'forecolor' ] },
			{ name: 'alignment', items: [ 'alignleft', 'aligncenter', 'alignright', 'alignjustify' ] },
			{ name: 'indentation', items: [ 'outdent', 'indent' ] },
			{ name: 'table', items: [ 'table']  },
			{ name: 'link', items: [ 'link']  },
			{ name: 'added', items: ['image', 'code','lineheight']},
			{ name: 'youtubeBtn', items: ['youtubeBtn']}
		],
		line_height_formats: '2pt 4pt 6pt 8pt 10pt 12pt 14pt',
		font_family_formats: '나눔고딕=Nanum Gothic;맑은고딕=Malgun Gothic;굴림체=Gulim;돋움체=Dotum;바탕체=Batang;궁서체=Gungsuh;' +
			'Arial=arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; AkrutiKndPadmini=Akpdmi-n',
		extended_valid_elements: 'iframe[src|width|height|name|align|frameborder|allowfullscreen|allow|style]',
		sandbox_iframes: false,
		xss_sanitization: false,
		//파일 업로드 콜백 방식
		file_picker_callback: (cb, value, meta) => {
			if (meta.filetype === 'file') {
				fileUploadCallback(cb, value, meta, seCode);
			}
			if (meta.filetype === 'image') {
				imgUploadCallback(cb, value, meta, seCode);
			}
		},
		//upload_handler 커스터마이징 방식
		images_upload_handler: image_upload_handler,
		// init_instance_callback : function(ed) {
		/*
        ed.on('WordCountUpdate', function (e) {
            console.log(e.wordCount.charactersWithoutSpaces);
        });
         */
		/*
        ed.on('keyup',function(e) {
            const cntnt = ed.getContent({format: 'raw'});
            const cnt = cntnt.length;
            $contentsCount.text(cnt);
        });
         */
		// }
		setup: function (editor) {
			editor.ui.registry.addButton('youtubeBtn', {
				icon: 'embed',
				tooltip: '유튜브 영상 삽입',
				onAction: function () {
					editor.windowManager.open({
						title: '유튜브 영상 삽입',
						body: {
							type: 'panel',
							items: [
								{
									type: 'input',
									name: 'youtubeUrl',
									label: '유튜브 링크 (URL)',
									placeholder: '예: https://youtu.be/...'
								}
							]
						},
						buttons: [
							{ type: 'cancel', text: '취소' },
							{ type: 'submit', text: '삽입', primary: true }
						],
						onSubmit: function (api) {
							const data = api.getData();
							const url = data.youtubeUrl.trim();
							let videoId = null;

							try {
								if (url.includes("youtu.be/")) {
									const parts = url.split("youtu.be/");
									if (parts.length > 1) videoId = parts[1].split(/[?#]/)[0];
								} else if (url.includes("youtube.com/watch")) {
									const urlObj = new URL(url);
									videoId = urlObj.searchParams.get("v");
								} else if (url.includes("youtube.com/shorts/")) {
									const parts = url.split("/shorts/");
									if (parts.length > 1) videoId = parts[1].split(/[?#]/)[0];
								}

								if (!videoId) {
									editor.windowManager.alert('유효하지 않은 유튜브 URL입니다.');
									return;
								}

								const nextNodeId = 'next-node-' + Math.floor(Math.random() * 1000000);
								const embedHtml = `
                                    <div class="youtube-wrapper" contenteditable="false" style="width: 600px; max-width: 100%; margin-bottom: 10px;">
                                        <div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
                                            <span class="mce-preview-object mce-object-iframe" 
                                                  data-mce-object="iframe" 
                                                  data-mce-p-allowfullscreen="allowfullscreen" 
                                                  data-mce-p-src="//www.youtube.com/embed/${videoId}"
                                                  style="display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%;" 
                                            >
                                                <iframe 
                                                    src="https://www.youtube.com/embed/${videoId}" 
                                                    width="100%" 
                                                    height="100%" 
                                                    style="width: 100%; height: 100%;"
                                                    frameborder="0" 
                                                    allowfullscreen>
                                                </iframe>
                                            </span>
                                        </div>
                                    </div>
                                    <p id="${nextNodeId}">&nbsp;</p>
                                `;

								editor.insertContent(embedHtml);

								setTimeout(() => {
									const nextNode = editor.dom.select('#' + nextNodeId)[0];
									if (nextNode) {
										editor.selection.select(nextNode, true);
										editor.selection.collapse(false); // 커서를 문단 끝으로 이동
										editor.dom.setAttrib(nextNode, 'id', null); // 임시 ID 제거
									}
								}, 100);

								api.close();
							} catch (e) {
								editor.windowManager.alert('URL 분석 중 오류가 발생했습니다.');
							}
						}
					});
				}
			});

			const maxLength = 4000;
			const updateCharCount = () => {
				const content = editor.getContent({ format: 'text' }) || '';
				const length = content.length;

				const countEl = document.getElementById('charCount');
				if (countEl) countEl.innerText = length + " / " + maxLength + "자";

				if (length > maxLength) {
					const trimmed = content.substring(0, maxLength);
					editor.setContent(trimmed);
					editor.selection.select(editor.getBody(), true);
					editor.selection.collapse(false);
				}

				const statusBarRight = document.querySelector('.tox-statusbar__right-container');
				if (statusBarRight) {
					statusBarRight.style.setProperty('display', 'none', 'important');
				}
			};

			editor.on('init', updateCharCount);
			editor.on('input', updateCharCount);
			editor.on('paste', () => setTimeout(updateCharCount, 0));
			editor.on('keyup', updateCharCount);
			editor.on('change', updateCharCount);
		}
	});
};

// Prevent Bootstrap dialog from blocking focusin
document.addEventListener('focusin', function (e) {
	if (e.target.closest('.tox-tinymce-aux, .moxman-window, .tam-assetmanager-root') !== null) {
		e.stopImmediatePropagation();
	}
});

bootbox.addLocale('ko', {
	OK : '확인',
	CANCEL : '취소',
	CONFIRM : '확인'
});
bootbox.setDefaults({
	locale: 'ko',
	centerVertical: true

});

//debug
logger = function(str) {
    console.log(str);
};

//신고 양식
pstDclrPop = function(contsIdntfNo, contsSeCd, wrtrNm) {
	let modalContent;
	if(!contsIdntfNo || !contsSeCd) {
		modalContent = `
			<div>대상 게시물을 찾을 수 없습니다.</div>
		`;

	}else {
		let seName = '';
		switch (contsSeCd) {
			case 'CSC01':
				seName = '게시판';
				break;
			case 'CSC02':
				seName = '수업안내마당';
				break;
			case 'CSC03':
				seName = '댓글';
				break;
			case 'CSC04':
				seName = '메시지';
				break;
			default:
				seName = '';
		}
		modalContent = `
			<form name="pstDclrForm" method="post" action="/comn/dclr/writePstDclr.json">
				<fieldset>
					<legend class="visually-hidden">신고양식</legend>
					<input type="hidden" name="contsIdntfNo" value="` + contsIdntfNo + `"/>
					<input type="hidden" name="contsSeCd" value="` + contsSeCd + `"/>
					<div class="row">
						<div class="col-lg-3 mb-2">
							<label class="bar p-1 border-bottom">구분</label>
						</div>
						<div class="col-lg-9 mb-2">
							<div class="border-bottom p-1">` + seName + `</div>
						</div>
					</div>
					<div class="row">
						<div class="col-lg-3 mb-2">
							<label class="bar p-1 border-bottom">작성자</label>
						</div>
						<div class="col-lg-9 mb-2">
							<div class="border-bottom p-1">` + wrtrNm + `</div>
						</div>
					</div>
					<div class="row">
						<div class="col-lg-12 mb-2">
							<label class="p-1">신고내용</label>
						</div>
						<div class="col-lg-12 mb-2">
							<textarea name="pstDclrCn" rows="3" class="form-control" placeholder="신고 사유를 입력하세요."></textarea>
						</div>
					</div>
					<div class="text-end mt-2">
						<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">취소</button>
						<button type="submit" class="btn btn-primary">신고</button>
					</div>
				</fieldset>
			</form>
			`;
	}

	const modalBox = `
		<div class="modal-dialog modal-dialog-centered modal-lg">
			<div class="modal-content">
				<div class="modal-header">
					<h1 class="modal-title fs-6">신고하기</h1>
					<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="닫기"></button>
				</div>
				<div class="modal-body">
				` + modalContent + `
				</div>
			</div>
		</div>
	`;

	const modalEl = document.createElement('div');
	modalEl.setAttribute('class', 'modal fade modal-popup');
	modalEl.setAttribute('id', 'popupDclrModal');
	modalEl.setAttribute('tabindex', '-1');
	//20240104 xss 보안약점 조치
	//modalEl.innerHTML = modalBox;
	modalEl.insertAdjacentHTML('afterbegin',modalBox);

	const modal = new bootstrap.Modal(modalEl, {});
	modalEl.addEventListener('hidden.coreui.modal', event => {
		modalEl.remove();
	});
	modal.show();
};


//세션 스토리지 저장
saveSessionStorage = function(key, obj) {
	sessionStorage.setItem(key, JSON.stringify(obj));
};

//세션 스토리지 일기
readSessionStorage = function(key) {
	return sessionStorage.getItem(key);
};

saveJsonStorage = function(key, obj) {
	localStorage.setItem(key, JSON.stringify(obj));
}
readJsonStorage = function(key) {
	const strObj = localStorage.getItem(key);
	return JSON.parse(strObj);
};
/*
* 엑셀 blbo 생성 및 다운로드
* @param string title
* @param [Object] 예시 : [{"A컬럼":"값","B컬럼":"값" ... }]
* */
createXlsx =  (title="데이터",jsonAry,option) => {
	/* 엑셀 workbook 생성 */
	const worksheet = XLSX.utils.json_to_sheet(jsonAry);
	const workbook = XLSX.utils.book_new();
	XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");

	/* 각 컬럼 width값 계산 */
	if (option !== undefined && option.width !== undefined) {
		let wchArr = [] ;
		switch (typeof option.width){
			case "number":
			case "string":
				for(let i=0;i<Object.keys(jsonAry[0]).length;i++){
					wchArr.push({wch:parseInt(option.width)});
				}
				break;
			case "object":
				option.width.forEach((v)=>{
					wchArr.push({wch:parseInt(v)});
				});
				break;
		}
		worksheet["!cols"] = wchArr;
	}

	/* xlxs 생성 및 다운로드*/
	XLSX.writeFile(workbook, title+".xlsx", { compression: true });
};


(function() {
	$(document).ready(function (){
		try{
			let alertMsg = '';
			let redirectUrl = '';
			switch (global_errCd) {
				case 'ERR01': alertMsg = '로그인 후 이용 가능합니다.'; break;
				case 'ERR02': alertMsg = '잘못된 접근입니다.'; break;
				case 'ERR03': alertMsg = '접근 권한이 없습니다.'; break;
				case 'ERR04': alertMsg = '검색어는 2자이상 입력하세요.'; break;
				case 'ERR05': alertMsg = '아이톡톡 국영수 심화과정은 군지역의 초,중학생만 참여 가능합니다.'; break;
				case 'ERR06': alertMsg = '사용자 정보 수정이 필요합니다.'; redirectUrl = '/comn/user/info/modifyIndvdlInfo.do?menuSn=62'; break;
				case 'ERR07': alertMsg = '이미 진행을 완료한 설문입니다.'; break;
				default : alertMsg = '';
			}

			if(alertMsg != ''){
				bootboxAlert({ title: '확인', message: alertMsg, size: 'small',
					callback: function() {
						if(redirectUrl != ''){
							location.href = redirectUrl;
						}
					}
				});
			}
		}catch (e) {
			console.log(e);
		}
	});

	$(document).on('click keypress', '.btnPopMyInfoClose', function(e) {
		e.preventDefault();
	});

	//로그인 전 버튼 (공통)
	$(document).on('click keypress', '.btnNoUser', function(e) {
		e.preventDefault();
		let msg = $(this).data('msg');
		if(!msg) {
			msg = '로그인 후 이용가능합니다';
		}
		bootboxAlert({title: '확인', message: msg, size: 'small'});
	});

	//신고하기
	$(document).on('submit', 'form[name=pstDclrForm]', function(e) {
		e.preventDefault();
		const $self = $(this);
		bootbox.confirm({title: '확인', message: '<i class="bi bi-exclamation-triangle-fill" style="color: red;"></i> 신고 하시겠습니까?',
			callback: function(result) {
				if(result) {
                    const actionUrl = $self.attr('action');
                    const method = $self.attr('method');

					$self.ajaxSubmit({
                        url: actionUrl,
                        type: method,
                        dataType: 'json',
                        success: function (result) {
                            if (result.message) {
                                bootboxAlert({title: '확인', message: result.message, size: 'small',
                                    callback: function () {
                                        if (result.success) {
                                            const modal = bootstrap.Modal.getInstance('#popupDclrModal');
                                            modal.hide();
                                        }
                                    }
                                });
                            }
                        }
                    });
				}
			}
		});
	});

	//마이 팝업
	$(document).on('click keypress', '#btnViewMyInfo', function(e) {
		e.preventDefault();
		const $popMyInfo = $('#popMyInfo');
		$popMyInfo.addClass('on');

		$.ajax({
			type: 'get',
			url: '/comn/site/userClassUsageInfo.json',
			dataType: 'json',
			cache : false,
			success: function (result) {
				if (result.message) {
					bootboxAlert({title: '확인', message: result.message, size: 'small'});
				}
				if (result.success) {
					const deuser = result.data.userProfl;
					$popMyInfo.find('[data-my-cnt="clas"]').text(deuser.totClasCnt);
					$popMyInfo.find('[data-my-cnt="badge"]').text(deuser.badgeCnt);
					$popMyInfo.find('[data-my-cnt="aply"]').text(deuser.aplyLrnCnt);
					$popMyInfo.find('[data-my-cnt="frnd"]').text(deuser.frndCnt);
				}
			}
		});
	});
	$(document).on('click keypress', '#btnPopMyInfoClose', function(e) {
		e.preventDefault();
		$('#popMyInfo').removeClass('on');
	});

})();


/// 검색
(function() {
	//최근 검색어
	function getMySrchwrd() {
		if(global_isMber) {
			$.ajax({
				type: 'get',
				url: '/comn/site/mySrchwrdList.json',
				dataType: 'json',
				cache: false,
				success: function (result) {
					if (result.message) {
						bootboxAlert({title: '확인', message: result.message, size: 'small'});
					}
					if (result.success) {
						const srchwrdList = result.data.srchwrdList;
						let srchwrdTag = '';
						srchwrdList.forEach((item) => {
							srchwrdTag += '<li class="gs-keyword-item"><a href="/srchList.do" class="gsRecentKeywordItem">' + item.srchwrd + '</a></li>';
						});
						$('#gsRecentKeyword').html(srchwrdTag);

					}
				}
			});
		}else {
			const jsonObj = readJsonStorage('srchwrd');
			if(jsonObj !== null && jsonObj.list !== 'undefined' && jsonObj.list.length > 0) {
				let srchwrdTag = '';
				jsonObj.list.forEach( (item) => {
					srchwrdTag += '<li class="gs-keyword-item"><a href="/srchList.do" class="gsRecentKeywordItem">' + item + '</a></li>';
				});
				$('#gsRecentKeyword').html(srchwrdTag);
			}

		}
	}

	//공통검색 Click
	$(document).on('click keypress', '#btnViewClasSearch', function(e) {
		e.preventDefault();
		$('#popSearchForm').addClass('on');
		getMySrchwrd();
	});
	//공통검색 닫기
	$(document).on('click keypress', '#btnTopSearchFormClose', function(e) {
		e.preventDefault();
		$('#popSearchForm').removeClass('on');
	});
	//최근 검색어 Click
	$(document).on('click keypress', '.gsRecentKeywordItem', function(e) {
		e.preventDefault();
		const searchKeyword = $(this).text();
		$('#globalSearchKeyword').val(searchKeyword);
		$('#globalSearchForm').submit();
	});
	//최근 검색어 삭제 Click
	$(document).on('click keypress', '#btnDelGsKeyword', function(e) {
		e.preventDefault();
		if(!confirm('삭제하시겠습니까?')) {
			return false;
		}
		if(global_isMber) {
			$.ajax({
				type:'post',
				url: '/comn/site/deleteMySrchwrdList.json',
				dataType: 'json',
				success: function(result) {
					if(result.message) {
						bootboxAlert({title: '확인', message: result.message, size: 'small'});
					}
					if(result.success) {
						$('#gsRecentKeyword').html('<span class="gs-keyword-empty">최근 검색어가 없습니다.</span>');
					}

				}

			});

		}else {
			localStorage.removeItem('srchwrd');
			$('#gsRecentKeyword').html('<span class="gs-keyword-empty">최근 검색어가 없습니다.</span>');
		}

	});


	//학교급 Click
	$(document).on('click keypress', '.classTrgtBtn', function(e) {
		const $searchGradeList = $('#searchGradeList');
		const scGrade = $(this).val();
		if(scGrade === 'T01') {
			$searchGradeList.find('#check-schl-gd4').removeClass('d-none');
			$searchGradeList.find('label[for=check-schl-gd4]').removeClass('d-none');
			$searchGradeList.find('#check-schl-gd5').removeClass('d-none');
			$searchGradeList.find('label[for=check-schl-gd5]').removeClass('d-none');
			$searchGradeList.find('#check-schl-gd6').removeClass('d-none');
			$searchGradeList.find('label[for=check-schl-gd6]').removeClass('d-none');
		}else {
			$searchGradeList.find('#check-schl-gd4').addClass('d-none');
			$searchGradeList.find('#check-schl-gd4').prop('checked', false);
			$searchGradeList.find('label[for=check-schl-gd4]').addClass('d-none');
			$searchGradeList.find('#check-schl-gd5').addClass('d-none');
			$searchGradeList.find('#check-schl-gd5').prop('checked', false);
			$searchGradeList.find('label[for=check-schl-gd5]').addClass('d-none');
			$searchGradeList.find('#check-schl-gd6').addClass('d-none');
			$searchGradeList.find('#check-schl-gd6').prop('checked', false);
			$searchGradeList.find('label[for=check-schl-gd6]').addClass('d-none');
		}
	});

	/**
	* 학년 click
	*/
	$(document).on('click keypress', '.globalGradeBtn', function() {
		const value = $(this).val();
		const $globalGradeBtn = $('.globalGradeBtn');

		if(value === '0') {
			$globalGradeBtn.each((idx, item) => {
				item.checked = (item.value === value);
			});
		} else {
			$('.globalGradeBtn[value="0"]').prop('checked',false);
		}

		let checkCnt = 0;
		$globalGradeBtn.each((idx, item) => {
			if(item.checked) {
				checkCnt++;
			}
		});
		if(checkCnt === 0) {
			$('#check-schl-gd0').prop('checked', true);
		}
	});

	/**
	* 과목 click
	*/
	$(document).on('click keypress', '.globalCourseBtn', function() {
		const value = $(this).val();
		const $globalCourseBtn = $('.globalCourseBtn');

		if(value === 'ALL') {
			$globalCourseBtn.each((idx, item) => {
				item.checked = (item.value === value);
		})
		} else {
			$('.globalCourseBtn[value="ALL"]').prop('checked',false);
		}

		let checkCnt = 0;
		$globalCourseBtn.each((idx, item) => {
			if(item.checked) {
				checkCnt++;
			}
		});
		if(checkCnt === 0) {
			$('#check-schl-course1').prop('checked', true);
		}
	});

	/**
	 * 공통검색 submit
	 */
	$(document).on('submit', '#globalSearchForm', function(e) {
		const srchwrd = $('#globalSearchKeyword').val();
		if(srchwrd.length < 2) {
			e.preventDefault();
			alert('검색어는 2자 이상 입력하세요.');
		}else {
			const jsonObj = readJsonStorage('srchwrd');
			let srchwrdObj = {};
			let wrdArr = [];
			if(jsonObj !== null && jsonObj.list !== 'undefined' && jsonObj.list.length > 0) {
				wrdArr = jsonObj.list;
				if(wrdArr.length > 10) {
					wrdArr.shift();
				}
			}
			wrdArr.push(srchwrd);

			const wrdSet = new Set(wrdArr);
			const uniqueArr = [...wrdSet];

			srchwrdObj = {
				list : uniqueArr
			}
			saveJsonStorage('srchwrd',srchwrdObj);
		}
	});

	/**
	 * 공통 파일 삭제 click
	 */
	$(document).on('click press', '.globalDeleteFile', function(e) {
		e.preventDefault();
		let $this = $(this);
		const url = $this.attr("href");
		//let form = new FormData();
		//form.append('atchFileIdntfNo',$this.attr("atchfileidntfno"));
		//form.append('fileSn',$this.attr("fileSn"));

		$.ajax({
			type:'post',
			url: url,
			dataType: 'json',
			//data : form,
			processData: false,
			contentType: false,
			success: function(result) {
				if(result.message) {
					bootboxAlert({title: '확인', message: result.message, size: 'small'});
				}
				if(result.success) {
					//debugger;
					if($this.closest("tr").length > 0 ){
						$this.closest("tr").remove();
					}
				}
			}

		});
	});

	/**
	 * 수강신청 Click
	 */
	$(document).on('click keypress', '.partcptInfoWrtBtn', function(e) {
		e.preventDefault();
		const clasIdntfNo = $(this).data('id');

		const partType = $(this).data('parttype');

		if(partType === 'std') {
			if(!joinPosbl(clasIdntfNo)) {
				bootboxAlert({title:'확인',size:'small',message:'수강인원이 마감되었습니다.</br>다른 강좌를 신청해주세요.',
					callback: function() {
						location.reload();
					}
				})
			} else {
				const actionUrl = $(this).attr('href') + '#partcptInfoWrtForm';

				const searchClassCrsCd = getSearchClassCrsCdValue($(this).attr('href'));
				const modal = $(this).data('modal');
				const reJoinYn = $(this).hasClass('reJoin');

				if (reJoinYn) {
					bootbox.confirm({
						title: '확인',
						size: 'small',
						message: '신청 후 취소한 이력이 있는 수업입니다.<br/> 신청하시겠습니까?',
						callback: function (result) {
							if (result) {
								classPartCpt(actionUrl, modal, clasIdntfNo, searchClassCrsCd);
							}
						},
					});
				} else {
					classPartCpt(actionUrl, modal, clasIdntfNo, searchClassCrsCd);
				}
			}
		} else {
			const actionUrl = $(this).attr('href') + '#partcptInfoWrtForm';

			const searchClassCrsCd = getSearchClassCrsCdValue($(this).attr('href'));
			const modal = $(this).data('modal');
			const reJoinYn = $(this).hasClass('reJoin');

			if (reJoinYn) {
				bootbox.confirm({
					title: '확인',
					size: 'small',
					message: '신청 후 취소한 이력이 있는 수업입니다.<br/> 신청하시겠습니까?',
					callback: function (result) {
						if (result) {
							classPartCpt(actionUrl, modal, clasIdntfNo, searchClassCrsCd);
						}
					},
				});
			} else {
				classPartCpt(actionUrl, modal, clasIdntfNo, searchClassCrsCd);
			}
		}
	});

	function joinPosbl(classIdntfNo) {
		let fnResult = false;

		$.ajax({
			url : '/clsm/clas/adhrnc/partcptPosbl.json',
			data: {'classIdntfNo' : classIdntfNo},
			type : 'post',
			async : false,
			success : function(result) {
				if(result.message) {
					bootboxAlert({title:'확인',size:'small',message:result.message});
				} else {
					fnResult = result.data.partcptPosbl;
				}
			}
		})

		return fnResult;
	}

	function classPartCpt (actionUrl, modal, clasIdntfNo, searchClassCrsCd) {
		let url = '/clsm/clas/adhrnc/checkPartcptClassInfo.json?searchClassIdntfNoList=' + clasIdntfNo;

		if (searchClassCrsCd != null && searchClassCrsCd === 'CRS03') {
			url += '&searchClassCrsCd=' + searchClassCrsCd;
		}

		$.ajax({
			type : 'post',
			url : url ,
			dataType : 'json',
			success: function(result) {
				if(result.message) {
					if(result.redirectUrl) {
						const redirectUrl = result.redirectUrl;
						bootboxAlert({
							title: '확인', size: 'small', message: result.message,
							callback: function () {
								location.href = redirectUrl;
							}
						});
					} else {
						bootboxAlert({title: '확인', size: 'small', message: result.message});
					}
				} else {
					modalShow(actionUrl, '참가신청서작성', modal);
				}
			}
		});
	}

	function getSearchClassCrsCdValue(url) {
		const urlParams = new URLSearchParams(url.split('?')[1]);
		const searchClassCrsCd = urlParams.get('searchClassCrsCd');
		return searchClassCrsCd || null;
	}

	/**
	 * 참가신청정보 submit
	 */
	$(document).on('submit', '#partcptInfo', function(e) {
		e.preventDefault();
		bootbox.confirm({title:'확인',size:'small',message:'신청 하시겠습니까?',
			callback: function(result) {
				let signAt = true;
				let i;
				if(result) {
					i = 1;
				}
				for(i; i === 1; i++) {

					//개인정보처리지침
					if(!$('#indvdlInfoAgreAt1').prop('checked')) {
						bootboxAlert({title:'확인',size:'small',message:'개인정보처리지침에 동의를 해야 신청 가능합니다.',
							callback: function() {
								signAt = false;
							}
						});
						break;
					}

					let validate = {
						confirm: true,
						msg: ''
					};

					if(global_isStudent) {

						//수업식별번호
						if($('#classIdntfNo').val() === '') {
							validate.msg = '수업정보 오류입니다. 관리자에게 문의하세요.';
							validate.confirm = false;
						}

						//참가자명
						if ($('#adhrncNm').val() === '') {
							validate.msg = '참가자명은 필수 입력 값 입니다.';
							validate.confirm = false;
						}

						//우편번호
						if ($('#homeZip').val() === '') {
							validate.msg = '우편번호는 필수 입력 값 입니다.';
							validate.confirm = false;
						}

						//자택주소
						if ($('#homeAddr').val() === '') {
							validate.msg = '자택주소는 필수 입력 값 입니다.';
							validate.confirm = false;
						}

						//자택상세주소
						if ($('#homeDtlAddr').val() === '') {
							validate.msg = '자택상세주소는 필수 입력 값 입니다.';
							validate.confirm = false;
						}

						const telno = $('#firstTelno').val()
							+ $('#middleTelno').val()
							+ $('#lastTelno').val();
						$('#telno').val(telno); //전화번호

						const prtcrTelno = $('#prtcrFirstTelno').val()
							+ $('#prtcrMiddleTelno').val()
							+ $('#prtcrLastTelno').val();
						$('#prtcrTelno').val(prtcrTelno); //보호자전화번호

						if(telno.length !== 11) {
							validate.msg = '학생 연락처는 필수 입력 값 입니다.';
							validate.confirm = false;
						}

						const stdntSeCd = $('input[name="stdntSeCd"]:checked'); //학생구분코드
						if(stdntSeCd.length === 0) {
							validate.msg = '학생유형을 선택해주세요.';
							validate.confirm = false;
						} else {
							const stdntSeCdVal = stdntSeCd.val();

							const crsCheck = $('#crsCheck').val();
							if(crsCheck.length > 0) {
								switch (crsCheck) {
									case "CRS04":
										if(stdntSeCdVal !== 'STD02') {
											validate.msg = '신청하려는 수업은<br/>다문화학생만 수강할 수 있는 수업입니다.<br/>확인하여 주시기 바랍니다.';
											validate.confirm = false;
										}
										break;
									case "CRS05":
										if(stdntSeCdVal !== 'STD03') {
											validate.msg = '신청하려는 수업은<br/>특수학생만 수강할 수 있는 수업입니다.<br/>확인하여 주시기 바랍니다.';
											validate.confirm = false;
										}
										break;
									default:
										break;
								}
							}
						}
					}

					if(!validate.confirm) {
						bootboxAlert({title:'확인',size:'small',message:validate.msg})
						break;
					} else {
						const $form = $('#partcptInfo');
						const action = $form.attr('action');
						const method = $form.attr('method');

						$.ajax({
							type : method,
							url : action,
							data : $form.serializeArray(),
							dataType : 'json',
							success: function(result) {
								if (result.message) {
									bootboxAlert({title: '확인', message: result.message, size: 'small'});
								} else {
									if(global_isStudent) {
										bootbox.confirm({title: '확인', size: 'small', message: '수강신청이 완료되었습니다. 내신청목록으로 이동하시겠습니까?',
											callback: function (result) {
												if (result) {
													location.href = '/clsm/clas/adhrnc/atnlcAplyList.do?menuSn=116'
												} else {
													const modal = bootstrap.Modal.getInstance('#partcptInfoWrtModal');
													modal.hide();
													location.reload();
												}
											}
										})
									} else{
										bootbox.confirm({title: '확인', size: 'small', message: '신청이 완료되었습니다. 내 모니터링목록으로 이동하시겠습니까?',
											callback: function (result) {
												if (result) {
													location.href = '/clsm/clas/observ/mntrngAplyList.do?menuSn=30'
												} else {
													const modal = bootstrap.Modal.getInstance('#partcptInfoWrtModal');
													modal.hide();
													location.reload();
												}
											}
										});
									}
								}
							}
						});
					}
				}

				if(!signAt) {
					return false;
				}
			}
		});
	});

	/**
	 * 강의계획서 다운로드 click
	 */
	$(document).on('click touchend keypress', '.classDataDownloadBtn', function(e) {
		e.preventDefault();

		const planUrl = $(this).data('plan');
		const crsUrl = $(this).data('crs');

		let planA = document.createElement('a');
		planA.href = planUrl;
		planA.click();

		const wakeUpTime = Date.now() + 100;
		while (Date.now() < wakeUpTime) {}

		let crsA = document.createElement('a');
		crsA.href = crsUrl;
		crsA.click();
	})

	/**
	 * 주소 검색 popup
	 */
	function sample6_execDaumPostcode() {
		new daum.Postcode({
			oncomplete: function(data) {
				// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.

				// 각 주소의 노출 규칙에 따라 주소를 조합한다.
				// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
				var addr = ''; // 주소 변수
				var extraAddr = ''; // 참고항목 변수

				//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
				if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
					addr = data.roadAddress;
				} else { // 사용자가 지번 주소를 선택했을 경우(J)
					addr = data.jibunAddress;
				}

				// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
				if(data.userSelectedType === 'R'){
					// 법정동명이 있을 경우 추가한다. (법정리는 제외)
					// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
					if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
						extraAddr += data.bname;
					}
					// 건물명이 있고, 공동주택일 경우 추가한다.
					if(data.buildingName !== '' && data.apartment === 'Y'){
						extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
					}
					// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
					if(extraAddr !== ''){
						extraAddr = ' (' + extraAddr + ')';
					}
					// 조합된 참고항목을 해당 필드에 넣는다.
					document.getElementById("extraAddress").value = extraAddr;

				} else {
					document.getElementById("extraAddress").value = '';
				}

				// 우편번호와 주소 정보를 해당 필드에 넣는다.
				document.getElementById('homeZip').value = data.zonecode;
				document.getElementById("homeAddr").value = addr + extraAddr;
				// 커서를 상세주소 필드로 이동한다.
				document.getElementById("homeDtlAddr").focus();
			}
		}).open();
	}

	/**
	 * 미리보기 버튼 Click
	 */
	$(document).on('click keypress', '.preview-none', function(e) {
		e.preventDefault();

		bootboxAlert({title:'확인',size:'small',message:'등록된 미리보기가 없습니다.'});
	})

	/**
	 * 관심수업저장 버튼 click
	 */
	$(document).on('click keypress', '.addItrstBtn', function(e) {
		e.preventDefault();

		const $this = $(this);
		const actionUrl = $this.attr('href');

		if(global_isMber) {
			$.ajax({
				type : 'post',
				url : actionUrl,
				dataType: 'json',
				success: function(result) {
					if(result.message) {
						bootboxAlert({ title: '확인', message: result.message, size: 'small'});
					} else {
						bootboxAlert({title: '확인', size: 'small', message: '관심수업 저장이 완료되었습니다.',
							callback: function() {
								$this.removeClass('addItrstBtn');
								$this.addClass('removeItrstBtn');
								$this.attr('href', result.data.hrefAddr);
							}
						});
					}
				}
			});
		} else {
			bootboxAlert({title:'확인',size:'small',message:'로그인 후 이용가능합니다.',
				callback: function() {
					location.href = '/comn/user/login/loginUser.do';
				}
			});
		}
	});

	/**
	 * 관심수업삭제 버튼 click
	 */
	$(document).on('click keypress', '.removeItrstBtn', function(e) {
		e.preventDefault();

		const $this = $(this);
		const actionUrl = $this.attr('href');

		if(global_isMber) {
			$.ajax({
				type : 'post',
				url : actionUrl,
				dataType: 'json',
				success: function(result) {
					if(result.message) {
						bootboxAlert({ title: '확인', message: result.message, size: 'small'});
					} else {
						bootboxAlert({title: '확인', size: 'small', message: '관심수업 삭제가 완료되었습니다.',
							callback: function() {
								$this.removeClass('removeItrstBtn');
								$this.addClass('addItrstBtn');
								$this.attr('href', result.data.hrefAddr);
							}
						});
					}
				}
			});
		} else {
			bootboxAlert({title:'확인',size:'small',message:'로그인 후 이용가능합니다.',
				callback: function() {
					location.href = '/comn/user/login/loginUser.do';
				}
			});
		}
	});

	/**
	 * 미확인 메시지,알림 목록
	 */
	function ntcnList() {
		$('#pop-noti-item-box').html('');
		$('.spinner').show();

		$.ajax({
			type: 'post',
			url: '/comn/msg/info/ntcnList.json',
			success: function (result) {
				if (result.message) {
					bootboxAlert({title: '확인', message: result.message, size: 'small'});
				} else {
					const data = result.data.result;
					/*const msgCnt = result.data.uncnfrmMsgCnt;

                    if(msgCnt > 0) {
                        $('#noti-count-btn').text(msgCnt)
                                            .addClass('on');
                    }*/

					const $itemBox = $('#pop-noti-item-box');
					//$itemBox.html('');

					if(data.length > 0) {
						data.forEach((item, idx) => {
							let tag = '';
							const dsptchDt = new Date(item.dsptchDt);

							if(item.msgDsptchSeCd === 'MSG01') {
								tag = `<li class="pop-noti-item">
                                        <a href="#" class="noti-user-ico">
                                            <i class="bi bi-person"></i>
                                        </a>
                                        <a href="/comn/msg/info/msgDtl.do?prevMenuSn=58&pageIndex=1&menuSn=60&msgRcptnIdntfNo=${item.msgRcptnIdntfNo}" class="noti-link" title="메시지상세 이동" style="width:80%;">
                                            <p>
                                                <strong>${item.sndptyNm}</strong>님으로 부터 메시지 수신
                                                ${item.rcptnYn === 'N' ? '<span class="noti-new">New</span>' : ''}
                                            </p>
                                        </a>
                                        <span class="noti-dt">${dsptchDt.getMonth() + 1}/${dsptchDt.getDate()}</span>
                                    </li>`;
							} else if(item.msgDsptchSeCd === 'MSG02') {
								tag = `<li class="pop-noti-item">
                                        <a href="#" class="noti-user-ico">
                                            <i class="bi bi-person"></i>
                                        </a>
                                        <a href="/comn/msg/info/msgDtl.do?prevMenuSn=58&pageIndex=1&menuSn=60&msgRcptnIdntfNo=${item.msgRcptnIdntfNo}" class="noti-link" title="메시지상세 이동" style="width:80%;">
                                            <p>
                                                ${item.rcptnCn}
                                                ${item.rcptnYn === 'N' ? '<span class="noti-new">New</span>' : ''}
                                            </p>
                                        </a>
                                        <span class="noti-dt">${dsptchDt.getMonth() + 1}/${dsptchDt.getDate()}</span>
                                    </li>`;
							}
							$itemBox.append(tag);
						});
					} else {
						const tag = `<li class="pop-noti-item">
                                        <span class="noti-dt">수신된 메시지가 없습니다.</span>
                                    </li>`;
						$itemBox.append(tag);
					}
				}
			},
			complete: function () {
				$('.spinner').hide();
			},
		});
	}

	/**
	 * 알림목록 최신화
	 */
	$(document).on('click keypress', '#btnViewNoti', function(e) {
		e.preventDefault();

		$('#popNotiInfo').toggleClass('on');

		if(global_isMber) {
			ntcnList();
		}
	});

	/**
	 * 알림 cnt
	 */
	$(document).ready(() => {
		if (global_isMber) {
			$.ajax({
				type: 'post',
				url: '/comn/msg/info/ntcnCnt.json',
				success: function (result) {
					if (result.message) {
						bootboxAlert({title: '확인', message: result.message, size: 'small'});
					} else {
						const msgCnt = result.data.uncnfrmMsgCnt;

						if (msgCnt > 0) {
							if (msgCnt == 100) {
								$('#noti-count-btn').text(99 + "+")
									.addClass('on');
							} else {
								$('#noti-count-btn').text(msgCnt)
									.addClass('on');
							}
						}
					}
				}
			});
		}
	})

	/**
	 * 신청 전 질문
	 */
	$(document).on('click keypress', '.btnPreQstn', function (e) {
		e.preventDefault();

		const url = $(this).attr('href');
		const modal = $(this).data('modal');

		modalShow(url, '신청 전 질문', modal);
	});
})();