<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<c:set var="now" value="<%=new java.util.Date()%>" />
<c:set var="nowDate"><fmt:formatDate value="${now}" pattern="yyyy-MM-dd" /></c:set>
<!doctype html>
<html lang="ko">
<head>
    <%@ include file="/WEB-INF/jsp/common.jsp" %>
    <sec:authorize access="hasAuthority('B')">
        <script>
            alert("기반정보 관리자 계정입니다. 다른 계정으로 로그인하십시요")
            location.href=('/logout.do')
        </script>
    </sec:authorize>
    <sec:authorize access="!isAuthenticated()">
        <script>
            alert("로그인 정보가 없습니다. 로그인해주세요")
            location.href=('/logout.do')
        </script>
    </sec:authorize>
    <meta name="_csrf" content="${_csrf.token}">
    <meta name="_csrf_header" content="${_csrf.headerName}">
    <meta http-equiv="X-UA-Compatible" content="IE=10; IE=9; IE=8; IE=7; IE=EDGE">
    <meta name="Description" content="신호관제">
    <meta name="Keywords" content="신호관제">
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <link rel="stylesheet" type="text/css" href="/css/themes/default/style.css?v=2">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.14.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="/css/style.css?v=${now}">
    <link rel="stylesheet" type="text/css" href="/css/tree.css?v=${now}" />

    <link rel="icon" type="text/css" href="data:;base64,iVBORw0KGgo=">

    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js?v=2"></script>
    <script src="/js/common/moment.js?v=2"></script>
    <script src="/js/common/hashmap.js?v=2"></script>
    <script src="/js/common/common-all.js?v=2"></script>
    <script src="/js/common/common.js?v=2"></script>
    <script src="/js/common/jstree.min.js?v=2"></script>
    <script src="/js/map_new.js?v=2"></script>
    <script src="/js/class.js"></script>
    <script src="/js/signal_new.js?v=2"></script>

    <script src="/js/cvib.js?v=2"></script>
    <script src="/js/signalInfo.js"></script>
    <script src="/js/tree.js?v=2"></script>

    <title>CVIM_MAP</title>
</head>
<body>
    <div class="wrap">
        <input type="hidden" name="min_x" id="min_x" value="">
        <input type="hidden" name="min_y" id="min_y" value="">
        <input type="hidden" name="max_x" id="max_x" value="">
        <input type="hidden" name="max_y" id="max_y" value="">
        <input type="hidden" name="regionCd" id="regionCd" value="">
        <input type="hidden" name="regionId" id="regionId" value="">
        <input type="hidden" name="intNo" id="intNo" value="">
        <input type="hidden" name="intNm" id="intNm" value="">
        <input type="hidden" name="intLcType" id="intLcType" value="">
        <input type="hidden" name="intLampType" id="intLampType" value="">
        <input type="hidden" name="groupNo" id="groupNo" value="">
        <input type="hidden" name="mainIntNo" id="mainIntNo" value="">
        <input type="hidden" name="treeXCoord" id="treeXCoord" value="">
        <input type="hidden" name="treeYCoord" id="treeYCoord" value="">
        <input type="hidden" name="XCoord" id="XCoord" value="126.978087">
        <input type="hidden" name="YCoord" id="YCoord" value="37.560684">
        <input type="hidden" name="sigunguCd" id="sigunguCd" value="">
        <input type="hidden" name="intMainphase" id="intMainphase" value="">
        <input type="hidden" name="networkType" id="networkType" value="">
        <input type="hidden" name="modemIp" id="modemIp" value="">

        <header class="topArea">
            <h1 class="logo"><a href="#"><span class="hidden">한국도로교통공단</span></a></h1>
            <ul class="nav">
                <li class="ic ic_log" onclick="popupOpen()"><span>장애이력</span></li>
                <li class="ic ic_logout" onclick="location.href='/logout.do'"><span>로그아웃</span></li>
            </ul>
        </header>
        <main class="container">
            <!-- 좌측 LNB 시작 -->
            <div class="LnbArea">
                <ul class="tab">
                    <li class="ic ic_cross active">
                        <span>교차로</span>
                    </li>
                    <li class="ic ic_signGroup">
                        <span>긴급차량우선신호</span>
                    </li>
                </ul>

                <div id="tabCont01" class="tabContainer">
                    <div class="searchBox">
                        <div class="inpBox"><input autocomplete="off" type="text" id="searchText" onkeyup="searchTree(event)" placeholder="검색어를 입력하세요"></div>
                        <button type="button" class="ic ic_search" onclick="searchTree()"><span class="hidden">검색</span></button>
                    </div>
                    <div class="tree-box">
                        <div id="intTree"></div>
                    </div>
                </div>
                <div id="tabCont02" class="tabContainer" style="display: none;">
                    <section class="section_01">
                        <h2 style="display: flex; justify-content: space-between;">긴급차량우선신호 서비스 현황 <span class="evp_tot_cnt" style="color: var(--red30); font-size: 12px;"></span></h2>
                        <div class="gridArea" style="height: calc(100% - 38px);">
                            <table class="tableBody">
                                <caption>테이블 내용 요약</caption>
                                <colgroup>
                                    <col width="35%">
                                    <col width="65%">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th>발행시각</th>
                                        <th>서비스</th>
                                    </tr>
                                </thead>
                                <!--//tableHead end -->
                                <tbody class="evp-table">
                                    <tr>
                                       <td colspan="3" class="empty-evp">조회된 내용이 없습니다.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <!--//gridArea end -->
                    </section>

                    <section class="section_02" style="overflow: hidden; border-top: 1px solid var(--gray40);">
                        <h2>긴급차량우선신호 서비스 이력</h2>

                        <div class="formArea">
                            <div class="formItem block">
                                <div class="form">
                                    <div class="selectBox" style="width: 100%;">
                                        <select id="region" name="region">
                                            <option value="ALL" selected>전체</option>
                                            <c:if test="${fn:length(center) != 0}">
                                                <c:forEach var="item" items="${center}">
                                                    <option value="${item.centerId}">${item.centerNm}</option>
                                                </c:forEach>
                                            </c:if>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="formItem block">
                                <div class="form">
                                    <div class="inpBox datePicker">
                                        <input type="text" id="startDate" value="${nowDate}">
                                    </div>
                                    <div class="inpBox flex-1">
                                        <input type="time" id="startTime" name="" value="00:00">
                                    </div>
                                </div>
                            </div>
                            <div class="formItem block">
                                <div class="form">
                                    <div class="inpBox datePicker">
                                        <input type="text" id="endDate" value="${nowDate}">
                                    </div>

                                    <div class="inpBox flex-1">
                                        <input type="time" id="endTime" name="" value="23:59">
                                    </div>
                                </div>
                            </div>
                            <div class="history-btn" onclick="searchHistoryData()">검색</div>
                        </div>
                        <!-- gridArea -->
                        <div class="gridArea" style="overflow: auto; height: calc(100% - 228px); flex:none;">
                            <table class="tableBody">
                                <caption>테이블 내용 요약</caption>
                                <colgroup>
                                    <col width="35%">
                                    <col width="65%">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th>발생시각</th>
                                        <th>서비스</th>
                                    </tr>
                                </thead>
                                <tbody class="history-table"></tbody>
                            </table>
                            <div class="empty-history">조회된 내용이 없습니다.</div>
                            <div class="history-loading"><img src="/css/themes/classic/throbber.gif" alt="로딩 이미지"></div>
                        </div>
                        <!--//gridArea end -->
                    </section>
                    <div class="play-box">
                        <div>
                            <div>시뮬레이션 재생/멈춤</div>
                            <img id="play" onclick="playSimulation()" src="/images/play.png" alt="시뮬레이션 재생버튼" width="24px">
                            <img id="pause" onclick="pauseSimulation()" src="/images/pause.png" alt="시뮬레이션 멈춤버튼" width="24px">
                            <img id="stop" onclick="stopSimulation()" src="/images/stop.png" alt="시뮬레이션 초기화버튼" width="24px">
                        </div>
                    </div>
                </div>

                <button class="btnFold"><span class="hidden">접기</span></button>
            </div>
            <!-- 좌측 LNB 끝 -->

            <!-- 지도 및 컨텐츠 영역 시작 -->
            <div class="contents">
                <div class="mapArea">
                    <div class="fncButton">
                        <button class="btn medium search_tooltip" id="location" title="위치검색"><i class="ic ic_location"></i>위치검색</button>
                        <button class="btn medium search_tooltip" id="coordinates" title="좌표검색"><i class="ic ic_axis"></i>좌표검색</button>
                        <button class="btn medium map_tooltip" id="road" title="로드뷰" onclick="mapTools(this)"><i class="ic ic_load"></i>로드뷰</button>
                        <button class="btn medium map_tooltip" id="distance" title="거리재기" onclick="mapTools(this)"><i class="ic ic_distance"></i>거리</button>
                        <button class="btn medium map_tooltip" id="polygon" title="면적재기" onclick="mapTools(this)"><i class="ic ic_area"></i>면적</button>
                        <button class="btn medium mylocation" onclick="getMyLocation()" title="현재위치"><i class="ic ic_finder"></i></button>
                        <button class="btn medium refresh" onclick="refreshNodeList()" title="새로고침"><i class="ic ic_refresh"></i></button>
                    </div>
                    <div class="location_box" id="menu_wrap">
                        <div class="location_search">
                            키워드 :
                            <input id="keyword" type="text" size="15" maxlength="50" autocomplete="off" value="" onkeyup="searchPlaces(event)">
                            <button type="submit" class="searchBtn" onclick="searchPlaces()">검색하기</button>
                        </div>
                        <div id="placesList"></div>
                        <div id="pagination"></div>
                    </div>
                    <div class="coordBox coordinates_box">
                        <div class="coord-unit">
                            <div>좌표 : </div>
                            <input type="text" id="lctn_coord" name="coord" autocomplete="off" onkeyup="moveToPosition(event)">
                            <label style="display: none;" for="lctn_coord"></label>
                        </div>
                        <div class="coord-btn" onclick="moveToPosition()">이동</div>
                    </div>
                    <div id="map"></div>
                    <div id="roadview"></div>
                </div>
                <div class="infoArea">
                    <!-- gridArea -->
                    <div class="gridArea evpContainer">
                        <table class="tableBody" id="cvibBottomBodyTable">
                            <caption>테이블 내용 요약</caption>
                            <thead>
                            <tr>
                                <th>센터명</th>
                                <th>제어기 번호</th>
                                <th>교차로명</th>
                                <th>전이</th>
                                <th>감응</th>
                                <th>소등</th>
                                <th>점멸</th>
                                <th>수동</th>
                                <th>SCU통신이상</th>
                                <th>센터통신이상</th>
                                <th>모순이상</th>
                                <th>주기카운터</th>
                                <th>교차로시각</th>
                            </tr>
                            </thead>
                            <!--//tableHead end -->
                            <tbody class="bottomBody"></tbody>
                        </table>
                        <table id="evpBottomBodyTable" class="tableBody" style="display: none;">
                            <thead>
                            <tr>
                                <th style="width:12%">수집시각</th>
                                <th style="width:10%">지역명</th>
                                <th style="width:15%">서비스 ID</th>
                                <th style="width:15%">서비스명</th>
                                <th style="width:10%">긴급차량번호</th>
                                <th style="width:10%">X 좌표</th>
                                <th style="width:10%">Y 좌표</th>
                                <th style="width:9%">속도(km/h)</th>
                                <th style="width:9%">남은거리(m)</th>
                            </tr>
                            </thead>
                            <tbody id="evpBottomInfo"></tbody>
                        </table>
                    </div>
                    <!--//gridArea end -->
                    <button class="btnFold"><span class="hidden">접기</span></button>
                </div>
            </div>
            <!-- 지도 및 컨텐츠 영역 끝 -->
        </main>
    </div>
    <div id="modalOpen" class="modal-container">
        <div class="modal-contents">
            <section class="section">
                <div class="title" ondblclick="modalToggle()"><i class="iconSign Normal_on"></i><span class="modal-title"></span><span class="modal-close">x</span></div>
            </section>
            <section class="section">
                <div class="cvibDetailFrame"></div>
            </section>
        </div>
    </div>

<%--<script src="/js/common/webSocket.js"></script>--%>
<script src="/js/common/cvibStatus_new.js?v=2"></script>
<script>
    let mapEvents = null;
    let searchPlace = null;
    const searchTooltips = $('.search_tooltip');
    let _ErrorPopup = null;


    searchTooltips.on('click', function() {
        const select = $(this);
        const isThis = select.hasClass('on');
        const selected = $('.search_tooltip.on');
        const rmId = selected.attr('id');
        selected.removeClass('on');
        const rmBox = $('.' + rmId + '_box');
        rmBox.removeClass('on');
        emptyCoordMarkers();
        $('.' + rmId + '_box input').val('');
        if (rmId === 'location') {
            $('#placesList').empty();
            $('#pagination').empty();
            searchPlace.removeMarker();
        }
        if (isThis) return;

        select.addClass('on');
        $('.' + select.attr('id') + '_box').addClass('on');

    });

    function modalToggle() {
        $('#modalOpen').toggleClass('on');
    }

    function mapTools(el) {
        const id = $(el).attr('id');
        const isThis = $(el).hasClass('on');
        const selected = $('.map_tooltip.on');
        if (selected.length) {
            selected.removeClass('on');
            const selId = selected.attr('id');
            mapEvents[selId].reset();
        }
        mapEvents.coords.activation();

        if (!isThis) {
            mapEvents[id].activation();
            $(el).addClass('on');
            mapEvents.coords.reset();
        }
    }

    $(function() {
        // .LnbArea 내부의 .btnFold 버튼에 대한 클릭 이벤트
        $('.LnbArea .btnFold').on('click', function() {
            $(this).toggleClass('fold'); // 클릭된 버튼에 'fold' 클래스 토글
            $('.LnbArea').toggleClass('fold');
        });

        // .infoArea 내부의 .btnFold 버튼에 대한 클릭 이벤트
        $('.infoArea .btnFold').on('click', function() {
            $(this).toggleClass('fold'); // 클릭된 버튼에 'fold' 클래스 토글
            $('.infoArea').toggleClass('fold');
        });

        searchPlace = new SearchPlace(map);
        mapEvents = {
            distance : new DistanceLine(map),
            polygon : new Polygon(map),
            road : new RoadView(map),
            coords : new Coordinates(map),
        }
    });

    $(function() {
        var $tabs = $(".LnbArea .tab li");
        var $tabContainers = $(".LnbArea .tabContainer");

        // 탭 클릭 이벤트 핸들러
        $tabs.on("click", function() {
            // 클릭된 탭의 인덱스 가져오기
            if ($(this).hasClass('active')) return;
            let index = $(this).index();

            // 모든 탭에서 'active' 클래스 제거
            $tabs.removeClass("active");

            // 클릭된 탭에만 'active' 클래스 추가
            $(this).addClass("active");

            // 모든 탭 컨테이너 숨기기
            $tabContainers.hide();

            // 클릭된 탭의 인덱스에 해당하는 컨테이너만 보이기
            $tabContainers.eq(index).show();
            const cvibTb = $('#cvibBottomBodyTable');
            const evpTb = $('#evpBottomBodyTable');
            const isFirst = cvibTb.css('display') === 'table';
            if (isFirst) {
                cvibTb.hide();
                evpTb.css('display', 'table');
            }
            else {
                unsetEvpCurr();
                if (_historyMap && _historyMap.size) {
                    if(interval) clearInterval(interval);
                    _historyMap.forEach((obj)=> {
                        if (obj.get('draw')) {
                            obj.get('draw').clear();
                            obj.set('draw', null);
                        }
                    });
                    $('.history-table tr.on').removeClass('on');
                    $('#evpBottomInfo').empty();
                    imageOnOff('play', false);
                    imageOnOff('stop', false);
                    imageOnOff('pause', false);
                }
                evpTb.hide();
                cvibTb.css('display', 'table');
            }
        });
    });

    $(function() {
        $("#startDate, #endDate").datepicker({
            dateFormat: 'yy-mm-dd' //달력 날짜 형태
            ,showOtherMonths: true //빈 공간에 현재월의 앞뒤월의 날짜를 표시
            ,showMonthAfterYear:true // 월- 년 순서가아닌 년도 - 월 순서
            ,changeYear: true //option값 년 선택 가능
            ,changeMonth: true //option값  월 선택 가능
            ,showOn: "both" //button:버튼을 표시하고,버튼을 눌러야만 달력 표시 ^ both:버튼을 표시하고,버튼을 누르거나 input을 클릭하면 달력 표시
            ,buttonImageOnly: false //버튼 이미지만 깔끔하게 보이게함
            ,buttonText: false //버튼 호버 텍스트
            ,yearSuffix: "년" //달력의 년도 부분 뒤 텍스트
            ,monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'] //달력의 월 부분 텍스트
            ,monthNames: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'] //달력의 월 부분 Tooltip
            ,dayNamesMin: ['일','월','화','수','목','금','토'] //달력의 요일 텍스트
            ,dayNames: ['일요일','월요일','화요일','수요일','목요일','금요일','토요일'] //달력의 요일 Tooltip
            ,minDate: "-5Y" //최소 선택일자(-1D:하루전, -1M:한달전, -1Y:일년전)
            ,maxDate: "+5y" //최대 선택일자(+1D:하루후, -1M:한달후, -1Y:일년후)
        });
    });

    function getCenteredOptions(width, height) {
        const left = (screen.width - width) / 2;
        const top = (screen.height - height) / 2;
        return `width=\${width},height=\${height},left=\${left},top=\${top},scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no`;
    }

    function popupOpen() {
        const option = getCenteredOptions(750, 690);
        _ErrorPopup = window.open('/errorHistory.do', '장애이력', option);
    }

    const yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
    const yesterdayVal = yesterday.getFullYear() + '-' +
        (yesterday.getMonth() + 1).toString().padStart(2, '0') + '-' +
        yesterday.getDate().toString().padStart(2, '0');
    let _errorStatMap = new Map();
    let _errorCntMap = new Map();
    $('#fromDt').val(yesterdayVal);
    $('#toDt').val(yesterdayVal);

    function resizePop() {
        $('.modal-box').toggleClass('on');
    }

    function toggleTable(type) {
        $('.table-box table.on').removeClass('on');
        $('.pagination.on').removeClass('on');
        $('.error-' + type + '-table').addClass('on');
        $('.error-' + type).addClass('on');
    }

    function errorClose() {
        $('.error-box').hide();
        $('#errorStatistics').removeClass('on');
    }

    function modalClose() {
        let iframe = document.querySelector('#iframeModal');
        iframe.src = 'about:blank';
        iframe.remove();
        const box = $('.modal-box');
        box.hide();
        box.removeClass('on');
    }


    function searchErrorStatistics() {
        const isStat = $('#error-stat').is(':checked');
        const url = isStat ? 'getNodeStatistics.do' : 'getNodeStatusCntStat.do';
        const fromDt = $('#fromDt').val();
        const toDt = $('#toDt').val();
        let regionId = $('#region_cd').val()
        let nodeId = $('#int_no').val();

        if (!fromDt || !toDt) {
            return alert('검색 기간을 선택 해주세요.');
        }

        if (fromDt > toDt) {
            return alert('검색 시작일이 종료일보다 클 수 없습니다.');
        }

        const loading = $('.error-box .showLoading');
        const param = { fromDt, toDt, regionId, nodeId };
        loading.css('display', 'flex');
        requestService(url, param, (res)=>{
            isStat ? errorStatPaging(res) : errorCntPaging(res);
            loading.css('display', 'none');
        }, true, ()=> loading.css('display', 'none'));
    }


    function errorStatPaging(res) {
        _errorStatMap.clear();
        const rowsPerPage = 20;

        if (res && res.length) {
            let str = '';
            res.forEach((obj, idx)=>{
                if (idx % rowsPerPage === 0 && idx > 0) {
                    let selPage = idx / rowsPerPage;
                    _errorStatMap.set(selPage, str);
                    str = '';
                }

                str += `<tr>
                            <td>\${obj.regionNm}</td>
                            <td>[\${obj.nodeid}] \${obj.name}</td>
                            <td>\${obj.eventDt}</td>
                            <td>\${obj.status}</td>
                            <td>\${obj.serverid}</td>
                        </tr>`;
            });
            if (str) {
                _errorStatMap.set(Number(_errorStatMap.size) + 1, str);
            }

            let pageSize = _errorStatMap.size;

            const isNext = pageSize > 10;
            if (isNext) {
                pageSize = 10;
            }

            makePageStr(false, isNext, 1, pageSize, 1, 'stat');
        }
        else {
            makePageStr(false, false, 1, 1, 1, 'stat');
        }
    }


    function beforeErrorStat(el, type) {
        if ($(el).hasClass('unactive')) return;
        const firstPage = Number($(el).next().text());
        if (!isNaN(firstPage)) {
            const startPage = firstPage - 10;
            const endPage = firstPage - 1;
            makePageStr(startPage !== 1, true, startPage, endPage, endPage, type);
        }
    }

    function makePageStr(isBefore, isNext, start, end, active, type) {
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        let str = `<button class="prev \${isBefore ? '' : 'unactive'}" onclick="beforeErrorStat(this, '\${type}')">«</button>`;
        for (let ii = start; ii <= end; ii++) {
            str += `<button class="\${active === ii ? 'active' : ''}" onclick="showErrorStatPage(\${ii}, this, '\${type}')">\${ii}</button>`;
        }
        str += `<button class="next \${isNext ? '' : 'unactive'}" onclick="nextErroStat(this, '\${type}')">»</button>`;
        let statistics = map.get(active);
        if (!statistics) {
            statistics = '<tr class="empty-box"><td colspan="'+$('.error-box table.on thead th').length+'">표출할 정보가 없습니다.</td></tr>'
        }
        $('.error-box table.on tbody').html(statistics);
        $('.error-box .pagination.on').html(str);
    }

    function nextErroStat(el, type) {
        if ($(el).hasClass('unactive')) return;
        const beforePage = $(el).prev().text();
        let lastPage = Number(beforePage) + 10;
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        let isNext = map.size > lastPage;
        if (!isNext) {
            lastPage = map.size;
        }
        const firstPage = Number(beforePage) + 1;
        makePageStr(true, isNext, firstPage, lastPage, firstPage, type);
    }

    function showErrorStatPage(page, el, type) {
        const beforePage = $('.error-box .pagination.on .active');
        if (page === Number(beforePage.text())) return;
        beforePage.removeClass('active');
        $(el).addClass('active');
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        $('.error-box table.on tbody').html(map.get(page));
    }


    function errorCntPaging(res) {
        _errorCntMap.clear();
        const rowsPerPage = 20;

        if (res && res.length) {
            let str = '';
            res.forEach((obj, idx)=>{
                if (idx % rowsPerPage === 0 && idx > 0) {
                    let selPage = idx / rowsPerPage;
                    _errorCntMap.set(selPage, str);
                    str = '';
                }

                let dataCnt = Number(obj.dataCnt).toLocaleString();
                str += `<tr>
                            <td>\${obj.regionNm}</td>
                            <td>[\${obj.nodeid}] \${obj.name}</td>
                            <td>\${dataCnt}</td>
                            <td>\${obj.status}</td>
                        </tr>`

            });
            if (str) {
                _errorCntMap.set(Number(_errorCntMap.size) + 1, str);
            }

            let pageSize = _errorCntMap.size;

            const isNext = pageSize > 10;
            if (isNext) {
                pageSize = 10;
            }

            makePageStr(false, isNext, 1, pageSize, 1, 'cnt');
        }
        else {
            makePageStr(false, false, 1, 1, 1, 'cnt');
        }
    }

    var centerPopId = null;
    var eventPopId = null;
    var signalPopId = null;

    /**
     * 좌표 검색
     */
    function findLocation() {

        // var coordImage = "find_coord_";
        // var onOff = 'off';
        // if ($coordBox.hasClass('on')) {
        //     onOff = 'on';
        // }
        // coordImage += onOff;
        // coordImage += ".png";

        // $('#coord').attr('src', BTN_IMAGE_PATH + coordImage);
    }

    //메뉴창 숨기기

    var UserAgent = window.navigator.userAgent;
    var wideFlag = false;
    var upDownFlag = false;

    $('.wideMap').click(function () {
        const isRoadView = $('.road_on')[0];
        if (wideFlag === false) {
            // $('.wideMap img').attr('src', '/images/arrow_right.png');
            //$('.wideMap img').attr('src', '/images/drop_up.png');
            $('.wideMap').addClass('on');
            $('.iframeTreeList').hide();
            const widthVal = isRoadView ? 'calc(60% - 10px)' : 'calc(100% - 10px)';
            $('#mapWrapper').css({
                width: widthVal,
                margin: '5px 0 0 5px'
            });
            $('.iframeBottomList').css({
                width: 'calc(100% - 10px)',
                margin: '0 0 0 5px'
            });

            if (UserAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || UserAgent.match(/LG|SAMSUNG|Samsung/) != null)
                $('.mylocationMob').css('left', '25px');
            wideFlag = true;
        } else if (wideFlag === true) {

            // $('.wideMap img').attr('src', '/images/arrow_left.png');
            // $('.wideMap img').attr('src', '/images/drop_down.png');
            $('.wideMap').removeClass('on');
            $('.iframeTreeList').show();
            const widthVal = isRoadView ? 'calc(60% - 290px)' : 'calc(100% - 290px)';
            $('#mapWrapper').css({
                width: widthVal,
                margin: '5px 0 0 287px'
            });
            $('.iframeBottomList').css({
                width: 'calc(100% - 287px)',
                margin: '0 0 0 2px'
            });

            if (UserAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || UserAgent.match(/LG|SAMSUNG|Samsung/) != null)
                $('.mylocationMob').css('left', '287px');
            wideFlag = false;
        }
        map.relayout();
    });

    $('.upDownMap').click(function () {
        if (upDownFlag == false) {
            //확대
            // $('.upDownMap img').attr('src', 'images/arrow_up.png');
            // $('.upDownMap img').attr('src', 'images/drop_up.png');
            $('.upDownMap').addClass('on');
            $('.iframeBottomList').hide();
            $('#mapWrapper').css('height', 'calc(100% - 8px)');
            $('.evp_legend').css('bottom', '6px');
            if (UserAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || UserAgent.match(/LG|SAMSUNG|Samsung/) != null)
            $('.mylocationMob').css('bottom', '35px');
            upDownFlag = true;
        } else if (upDownFlag == true) {
            //축소
            // $('.upDownMap img').attr('src', 'images/arrow_down.png').slide;
            // $('.upDownMap img').attr('src', 'images/drop_down.png').slide;
            $('.upDownMap').removeClass('on');
            $('.iframeBottomList').show();
            $('#mapWrapper').css('height', 'calc(100% - 230px)');
            if (UserAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || UserAgent.match(/LG|SAMSUNG|Samsung/) != null)
            $('.mylocationMob').css('bottom', 'calc(25% + 35px)');
            $('.evp_legend').css('bottom', '228px');
            upDownFlag = false;
        }
        map.relayout();
    });

    /********************************************************************************
     * header display
     *********************************************************************************/

    var headFlag = false;
    $("#hline").click(function () {
        if (headFlag == false) {
            $('.headMenu').slideUp();
            $('.container').css('height', '100%');
            headFlag = true;
        } else {
            $('.headMenu').slideDown();
            $('.container').css('height', 'calc(100% - 66px)');
            headFlag = false;
        }

    });

    function closeTopMenu(obj) {
        mapZoomBound();
        $('#' + obj).attr("class", "road_off");
        if (obj == "center") {
            $("#center").attr("src", BTN_IMAGE_PATH + "btn_02.png");
            setTimeout(function () {
                location.reload(true);
            }, 100 * 1);
        }
        if (obj == "event") $("#event").attr("src", BTN_IMAGE_PATH + "btn_03.png");
        if (obj == "addSignal") {
            $("#addSignal").attr("src", BTN_IMAGE_PATH + "btn_05.png");
            setTimeout(function () {
                location.reload(true);
            }, 100 * 1);
        }
    }

    //모바일 인경우 현재위치버튼 변경
    if (UserAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || UserAgent.match(/LG|SAMSUNG|Samsung/) != null) {
        $('.mylocation').hide();
        $('.mylocationMob').show();
    }

    $(window).bind("beforeunload", function (e) {
        if (_CvibInfoDetailPop != null) _CvibInfoDetailPop.close();
        if (_ErrorPopup != null) _ErrorPopup.close();
    });

    function refreshNodeList() {
        requestService('refreshNodeList.do', null, (res)=>{
            if (res) {
                if (res.success) {
                    alert('리스트 목록이 새로고침 되었습니다.');
                    location.reload(true);
                }
                else if(res.errorMsg) {
                    alert('리스트 목록 새로고침 중 오류가 발생하였습니다.<br>' + res.errorMsg);
                }
            }
        }, true)
    }


    function errorHistory() {
        $('#fromDt').val(yesterdayVal);
        $('#toDt').val(yesterdayVal);
        $('#region_cd').val('전체').trigger('change');
        $('.error-box .error-cnt-table tbody').empty();
        $('.error-box .error-stat-table tbody').empty();
        $('#error-stat').click();
        $('.error-box').css('display', 'flex');
        $('#errorStatistics').addClass('on');
    }

    function goPanToInt(intNm, lng, lat) {
        if (_Level > 3) map.setLevel(1);
        map.panTo(new kakao.maps.LatLng(lat, lng));

        setTimeout(
            function () {
                getSignalInfo();
                customOverlayFnc(intNm, lng, lat);
            }, 100 * 2
        );
    }

    function moveLocation(serviceId, el) {
        if (!$('#play').hasClass('on')) {
            return;
        }


        $('#evpBottomInfo tr.on').removeClass('on');
        $(el).addClass('on');
        const map = _historyMap.get(serviceId.toString());
        const idx = $(el).index();
        if (map) {
            const obj  = map.get('obj');
            const draw = map.get('draw');

            const {cur_lat, cur_lng} = obj.event_list[idx];
            let position = getKakaoPosition(cur_lat, cur_lng);
            draw.car.moveMarker(position);
            setSigState(obj.phase_list[idx], draw);
        }

    }

    function searchPlaces(event) {
        if (!event || event.key === 'Enter') {
            searchPlace.searchPlaces();
        }
    }

    function mapClickEvent(mouseEvent) {
        const { latLng } = mouseEvent;
        mapEvent('clickEvent', latLng);
    }


    function mapEvent(event, latLng) {
        for (let key in mapEvents) {
            const tooltipObj = mapEvents[key];
            if (tooltipObj.active && tooltipObj[event]) {
                tooltipObj[event](latLng);
            }
        }
    }
</script>
</body>
</html>
