<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ include file="/jsp/common/include/localemessage.jsp" %>

<c:set var="locale" value="<%= localeMessage.getLocale() %>"/>

<script language="javascript" src="<c:url value="/js/jquery-1.12.1.min.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jquery-ui.js"/>"></script>
<%-- <script language="javascript" src="<c:url value="/js/jquery-ui.min.js"/>"></script> --%>
<script language="javascript" src="<c:url value="/js/grid.locale-${locale}.js"/>" charset="utf-8"></script>
<script language="javascript" src="<c:url value="/js/prefixfree.min.js"/>"></script>

<script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
            jQuery.browser.msie = true;
            jQuery.browser.version = RegExp.$1;
        }
    })();
</script>


<script language="javascript" src="<c:url value="/js/jquery.jqGrid.min.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jquery.form.min.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jquery.contextMenu.js"/>"></script>
<script language="javascript" src="<c:url value="/js/custom.js"/>"></script>
<script language="javascript" src="<c:url value="/js/common-${locale}.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jquery.inputmask.bundle.min.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jquery.searchabledropdown-1.0.8.min.js"/>"></script>
<%-- <script language="javascript" src="<c:url value="/js/jquery.searchable-1.1.0.min.js"/>"></script> --%>
<script language="javascript" src="<c:url value="/js/jexcel.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jsuites.js"/>"></script>
<script language="javascript" src="<c:url value="/js/jsuites.webcomponents.js"/>"></script>
<script language="javascript" src="<c:url value="/js/custom.component.js"/>"></script>
<script language="javascript" src="<c:url value="/js/Nwagon.js"/>"></script>
<script language="javascript" src="<c:url value="/js/vkbeautify.js"/>"></script>
<script language="javascript" src="<c:url value="/js/select2.min.js"/>"></script>

<script src="<c:url value="/addon/codemirror/lib/codemirror.js"/>"></script>
<script src="<c:url value="/addon/codemirror/mode/javascript/javascript.js"/>"></script>
<script src="<c:url value="/addon/codemirror/mode/xml/xml.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/edit/matchbrackets.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/edit/closebrackets.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/comment/comment.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/comment/continuecomment.js"/>"></script>

<script src="<c:url value="/addon/codemirror/lint/jsonlint.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/lint/lint.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/lint/javascript-lint.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/lint/html-lint.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/lint/json-lint.js"/>"></script>
<script src="<c:url value="/addon/codemirror/addon/lint/css-lint.js"/>"></script>

<script src="<c:url value="/addon/summernote/summernote-lite.min.js"/>"></script>
<script src="<c:url value="/addon/summernote/summernote-cleaner.js"/>"></script>
<script src="<c:url value="/addon/summernote/lang/summernote-ko-KR.js"/>"></script>

<script language="javascript">

    function buttonControl() {
        if (arguments.length == 0) {
            $("img[level], button[level]").hide();
            if ("${rmsMenuAuth}" == "W") {
                $("img[level='W']").show();
                $("img[level='R']").show();
                $("button[level='W']").show();
                $("button[level='R']").show();
            } else if ("${rmsMenuAuth}" == "R") {
                $("img[level='R']").show();
                $("button[level='R']").show();
            }
        } else if (arguments.length == 1) {
            var status = arguments[0];
            if (arguments[0]) {
                status = 'DETAIL';
            } else {
                status = 'NEW';
            }

            if (arguments[0] == 'DETAIL') {
                status = 'DETAIL';
            } else if (arguments[0] == 'NEW') {
                status = 'NEW';
            } else if (arguments[0] == 'TEMP') {
                status = 'TEMP';
            }

            $("img[level]").hide();
            $("button[level]").hide();
            if ("${rmsMenuAuth}" == "W") {
                $("img[level='W'][status*=" + status + "]").show();
                $("img[level='R'][status*=" + status + "]").show();
                $("button[level='W'][status*=" + status + "]").show();
                $("button[level='R'][status*=" + status + "]").show();
            } else if ("${rmsMenuAuth}" == "R") {
                $("img[level='R'][status*=" + status + "]").show();
                $("button[level='R'][status*=" + status + "]").show();
            }
        }
    }

    /*
    function buttonControl(){
        if (arguments.length == 0){
            $("img[level]").hide();
            if ("${rmsMenuAuth}" =="W"){
			$("img[level='W']").show();
			$("img[level='R']").show();
		}else if ("${rmsMenuAuth}" =="R"){
			$("img[level='R']").show();
			$("tr[level='W']").hide();
		}
	} else if (arguments.length == 1){
		var isStatus = false;
		if (isBoolean(arguments[0])){
			isStatus = arguments[0];
		}else{
			if (arguments[0] != "" && arguments[0] !="null"){
				isStatus = true;
			}else{
				isStatus = false;
			}
		}
		var sel = "";
		if (isStatus){
			//detail
			sel = "DETAIL";
		}else{
			//new
			sel = "NEW";
			$("#btn_modify").attr('src',"<c:url value='/img/btn_regist.png'/>");
		}	
		$("img[level]").hide();
		if ("${rmsMenuAuth}" =="W"){
			$("img[level='W'][status*="+sel+"]").show();
			$("img[level='R'][status*="+sel+"]").show();
		}else if ("${rmsMenuAuth}" =="R"){
			$("img[level='R'][status*="+sel+"]").show();
			$("tr[level='W']").hide();
		}		
	}
}
*/

    function getSearchUrlForReturn() {
        var array = [];
        <c:forEach var="pageParameter" items="${param}"><c:if test="${fn:startsWith(pageParameter.key,'search')}">
        array.push('<c:out value="${pageParameter.key}" />' + "=" + '<c:out value="${pageParameter.value}" />'.replace(/%23/g, '#'));
        </c:if>
        </c:forEach>
        <c:forEach var="pageParameter" items="${param}"><c:if test="${fn:startsWith(pageParameter.key,'like')}">
        array.push('<c:out value="${pageParameter.key}" />' + "=" + '<c:out value="${pageParameter.value}" />'.replace(/%23/g, '#'));
        </c:if></c:forEach>
        return array.join("&");
    }

    function getSearchUrlForReturnArray() {
        var array = [];
        <c:forEach var="pageParameter" items="${param}"><c:if test="${fn:startsWith(pageParameter.key,'search')}">
        array.push('<c:out value="${pageParameter.key}" />' + "=" + '<c:out value="${pageParameter.value}" />'.replace(/%23/g, '#'));
        </c:if>
        </c:forEach>
        <c:forEach var="pageParameter" items="${param}"><c:if test="${fn:startsWith(pageParameter.key,'like')}">
        array.push('<c:out value="${pageParameter.key}" />' + "=" + '<c:out value="${pageParameter.value}" />'.replace(/%23/g, '#'));
        </c:if></c:forEach>
        return array;
    }

    function getReturnUrlForReturn(search) {
        var returnUrl = '${param.returnUrl}';
        returnUrl = returnUrl + '?cmd=' + 'LIST';
        returnUrl = returnUrl + '&page=' + '${param.page}';
        returnUrl = returnUrl + '&menuId=' + '${param.menuId}';
        returnUrl = returnUrl + '&sortName=' + '${param.sortName}';
        returnUrl = returnUrl + '&sortOrder=' + '${param.sortOrder}';
        //검색조건
        returnUrl = returnUrl + '&' + getSearchUrlForReturn();
        return returnUrl;
    }

    function getReloadUrl(cmd) {
        var returnUrl = '${param.returnUrl}';
        returnUrl = returnUrl + '?cmd=' + cmd;
        returnUrl = returnUrl + '&page=' + '${param.pages}';
        returnUrl = returnUrl + '&menuId=' + '${param.menuId}';
        //검색조건
        returnUrl = returnUrl + '&' + getSearchUrlForReturn();
        return returnUrl;
    }

    function putSelectFromParam() {
        var array = [];
        <c:forEach var="pageParameter" items="${param}">
        <c:if test="${fn:startsWith(pageParameter.key,'search')}">
        var name = "${pageParameter.key}";
        var value = "${pageParameter.value}"

        $("select[name=" + name + "]").val(value);
        $("input[name=" + name + "]").val(value);
        </c:if>
        </c:forEach>

    }

    function getMenuId() {
        return '${param.menuId}';
    }

    var $ = jQuery.noConflict();
    $(document).keydown(function (e) {
        var element = e.target.nodeName.toLowerCase();
        if (element != 'input' && element != 'textarea') {
            if (e.keyCode === 8) {
                return false;
            }
        }
    })

    function camelToSnake(str) {
        return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
    }

    function snakeToCamel(str) {
        return str.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
    }


    /**
     * JS 메시지 변수 사용시 포멧팅을 위해 추가 다음과 같이 사용 가능
     * 인터페이스 삭제시 배포시스템에서도 삭제가 될 수 있습니다. {0}를 삭제하시겠습니까?".formatLocale($("#infId").val())
     *
     * 사용 예>
     * 기존 JS 메시지
     *   인터페이스 삭제시 배포시스템에서도 삭제가 될 수 있습니다.\n" + $("#infId").val() + "를 삭제하시겠습니까?
     * format 함수 사용한 JS 메시지
     *   인터페이스 삭제시 배포시스템에서도 삭제가 될 수 있습니다.\n {0}를 삭제하시겠습니까?".formatLocale($("#infId").val())
     * Java Locale(ResourceBundle)과 함께 사용한 예시
     *   localeMessage.getString("interface.message.confirmDeleteInterfaceWithDeployedSystem" ) %>".formatLocale($("#infId").val());
     */
    String.prototype.formatLocale = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };

    formatLocale = function (format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };

    function prettyJson(jsonText) {
        if (!jsonText) {
            return jsonText;
        }

        var prettyJson = new Array();
        var depth = 0;
        var currChar;
        var prevChar;
        var doubleQuoteIn = false;

        for (var i = 0; i < jsonText.length; i++) {
            currChar = jsonText.charAt(i);

            if (currChar == '\"') {
                if (prevChar != '\\') {
                    doubleQuoteIn = !doubleQuoteIn;
                }
            }

            switch (currChar) {
                case '{':
                    prettyJson.push(currChar);
                    if (!doubleQuoteIn) {
                        prettyJson.push('\n');
                        insertTab(prettyJson, ++depth);
                    }
                    break;
                case '}':
                    if (!doubleQuoteIn) {
                        prettyJson.push('\n');
                        insertTab(prettyJson, --depth);
                    }
                    prettyJson.push(currChar);
                    break;
                case ',':
                    prettyJson.push(currChar);
                    if (!doubleQuoteIn) {
                        prettyJson.push('\n');
                        insertTab(prettyJson, depth);
                    }
                    break;
                default:
                    prettyJson.push(currChar);
                    break;
            }

            prevChar = currChar;
        }
        return prettyJson.join('');
    }

    const TAB = '    ';

    function insertTab(prettyJson, depth) {
        for (var i = 0; i < depth; i++) {
            prettyJson.push(TAB);
        }
    }

    async function downloadFiles(url, body) {
        url += "&serviceType=" + sessionStorage["serviceType"]
        let headers;
        if (body instanceof FormData || body instanceof URLSearchParams) {
            headers = {};
        } else {
            headers = {
                'Content-Type': 'application/json',
            };
        }
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: headers,
                body: body
            });
            if (!response.ok) throw new Error('Server responded with an error!');

            const blob = await response.blob();
            const contentDisposition = response.headers.get('Content-Disposition');
            let filename = "downloaded_file"; // 기본 파일 이름
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                if (filenameMatch.length > 1) {
                    filename = filenameMatch[1];
                    filename = decodeURI(filename);
                }
            }
            const downloadUrl = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = filename; // 압축 파일 이름, 서버에서 설정 가능
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(downloadUrl);
        } catch (error) {
            console.error('Download failed:', error);
        }
    }
</script>
