var _Map;
var _Level = 9;
/* 폴리라인 (소통정보) 데이터 전역변수 */
var _TrafficInfoArr = [];
var _LinkVrtx1Arr = [];
var _IfscVrtx2Arr = [];
var _IfscVrtx3Arr = [];
var _RoadVrtx4Arr = [];
var _RoadVrtx5Arr = [];
var _RoadVrtx6Arr = [];
var _RoadVrtx7Arr = [];

var _BeforePolylineBack = [];
var _BeforePolyline = [];
var _LastPolylineEvent = {};
/* 각기능별 전역변수 */
var _CctvCtlrArr = [];
var _VmsCtlrArr = [];
var _IncdOcrrArr = [];
var _ParkingInfoArr = [];
var _TaasInfoArr = [];
var _CongestInfoArr = [];
var _NoticeInfoArr = [];
var _AtrdId;

/* 지도에 바로 그릴지 판단하는 Flag */
var _TrafficFlag = true;
var _CctvFlag = true;
var _VmsFlag = true;
var _InciFlag = false;
var _RoadFlag = false;
var _ParkingFlag = true;
var _TaasFlag = true;
var _CustomOverlayFlag = false;

/* 각기능별 오버레이,인포윈도우 전역변수 */
var _CustomOverlay = null;
var _CustomOverlayClick = null;
var _CctvOverlay = null;
var _VmsOverlay = null;
var _IncdOverlay = null;
var _ParkingOverlay = null;
var _TaasOverlay = null;
var _Infowindow = null;
var _VmsInfoWindow = null;
var _IncdInfoWindow = null;
var _ParkingInfoWindow = null;
var _TaasInfoWindow = null;

// 각기능 클릭한 전역마커
var _CctvMarker = null;
var _VmsMarker = null;
var _IncdMarker = null;
var _ParkingMarker = null;
var _TaasMarker = null;

var _RoadListStr = '';

var vmsImgInterval = null;
var displaySecond = 31;
var timerInterval = null;
var _iwContent    = '';
var _popUp        = null;
var _size         = [];
var _beforeClickVms = null;
var _cctvPopupObj;
var _interval;

var _isSubMenuClick = false;
var _isSubCategoryClick = false;
var _AtrdBounds;
var _AtrdSideMarkerArr = [];
var _AtrdFrontPoly = null;
var _AtrdBackPoly = null;

_size[0]  = 48;
_size[1]  = 48;
_size[2]  = 32;
_size[3]  = 32;
_size[4]  = 24;
_size[5]  = 24;
_size[6]  = 18;
_size[7]  = 18;
_size[8]  = 18;
_size[9]  = 18;
_size[10] = 18;


var yAnchor = [
    2.8,
    2.8,
    2.3,
    2.3,
    2,
    2,
    1.7,
    1.7,
    1.7,
    1.7,
];

/* 전역변수 초기화 */
function TrafficInfoArrDelete() {

    _TrafficInfoArr = [];
    _LinkVrtx1Arr = [];
    _IfscVrtx2Arr = [];
    _IfscVrtx3Arr = [];
    _RoadVrtx4Arr = [];
    _RoadVrtx5Arr = [];
    _RoadVrtx6Arr = [];
    _RoadVrtx7Arr = [];

}

_RoadVertexObj = function (
    atrd_id,
    atrd_nm,
    drct_cd,
    road_id,
    road_nm,
    strt_nm_node,
    end_nm_node,
    sect_lngt,
    levl,
    x_crdn,
    y_crdn,
    x_crdn_min,
    x_crdn_max,
    y_crdn_min,
    y_crdn_max,
    cmtr_grad_cd,
    sped,
    trvl_hh,
    road_ord
) {
    this.atrd_id = atrd_id;
    this.atrd_nm = atrd_nm;
    this.drct_cd = drct_cd;
    this.road_id = road_id;
    this.road_nm = road_nm;
    this.strt_nm_node = strt_nm_node;
    this.end_nm_node = end_nm_node;
    this.sect_lngt = sect_lngt;
    this.levl = levl;
    this.x_crdn = x_crdn;
    this.y_crdn = y_crdn;
    this.x_crdn_min = x_crdn_min;
    this.x_crdn_max = x_crdn_max;
    this.y_crdn_min = y_crdn_min;
    this.y_crdn_max = y_crdn_max;
    this.cmtr_grad_cd = cmtr_grad_cd;
    this.trvl_hh = trvl_hh;
    this.sped = sped;
    this.road_ord = road_ord;

    this.lettersInfo = '[' + atrd_nm + '] ' + sped + ' km/h ' +
        strt_nm_node + ' &rarr; ' + end_nm_node;

    var xCrdnArr = x_crdn.split(',');
    var yCrdnArr = y_crdn.split(',');
    var linePath = new Array();

    for (var ii = 0; ii < xCrdnArr.length; ii++) {
        linePath.push(new daum.maps.LatLng(yCrdnArr[ii], xCrdnArr[ii]));
    }

    var cmtrGradColor;
    var cmtrGradText;

    if (cmtr_grad_cd == 'LTC1') {
        cmtrGradColor = '#00981e';
        cmtrGradText = '소통원활';
    } else if (cmtr_grad_cd == 'LTC2') {
        cmtrGradColor = '#fead0e';
        cmtrGradText = '서행';
    } else if (cmtr_grad_cd == 'LTC3') {
        cmtrGradColor = '#ff0000';
        cmtrGradText = '정체';
    } else {
        cmtrGradText = '정보없음';
        cmtrGradColor = '#888888';
        trvl_hh = 0;
        sped = 0;
    }

    this.cmtrGradColor = cmtrGradColor;
    this.cmtrGradText = cmtrGradText;

    var strokeWeight = 5;
    var strokeWeightBack = 7;

    if (levl == 3) {
        strokeWeight = 4;
        strokeWeightBack = 6;
    } else if (levl == 5 || levl == 4) {

        strokeWeight = 3;
        strokeWeightBack = 5;
    } else if (levl == 6 || levl == 7) {
        strokeWeight = 2;
        strokeWeightBack = 4;
    }

    // 지도에 표시할 선을 생성합니다
    this.polyline =
        new daum.maps.Polyline({
            path: linePath,
            strokeWeight: strokeWeight,
            strokeColor: cmtrGradColor,
            strokeOpacity: 1,
            strokeStyle: 'solid',
            zIndex: 2
        });

    // 백그라운드 라인
    this.polylineBack =
        new daum.maps.Polyline({
            path: linePath, // 선을 구성하는 좌표배열 입니다
            strokeWeight: strokeWeightBack, // 선의 두께 입니다
            strokeColor: '#fff', // 선의 색깔입니다
            strokeOpacity: 1, // 선의 불투명도 입니다 1에서 0 사이의 값이며 0에 가까울수록 투명합니다
            strokeStyle: 'solid',
            zIndex: 1
        });


    daum.maps.event.addListener(this.polyline, 'mouseover', function (mouseEvent) {
        if (_CustomOverlay != null)
            _CustomOverlay.setMap(null);

        //마우스오버상태에서 줌 변경시 색상변경이 필요하므로 전역에 넣어줌..

        _LastPolylineEvent['line'] = this;
        _LastPolylineEvent['cmtrGradColor'] = cmtrGradColor;
        this.setOptions({strokeColor: 'blue'});

        var latlng = mouseEvent.latLng;
        const iwContent =
            `<div class="mapPop traffic_${cmtr_grad_cd}">
					<div class="head">
						<span class="title">${road_nm}</span>
						<span class="traffic">${cmtrGradText}</span>
					</div>
					<div class="cont">
						<dl>
    						<dt>
    							[ ${strt_nm_node} ] 부터 <br/>
    							[ ${end_nm_node} ] 까지
    						</dt>
    						<dd>
    							소요시간 : 약 ${trvl_hh} 분<br/>
    							평균속도 : ${sped} km/h
							</dd>
						</dl>
					</div>
				 </div>`;

        // 인포윈도우를 생성하고 지도에 표시합니다
        _CustomOverlay =
            new daum.maps.CustomOverlay({
                map: _Map,
                position: latlng,
                content: iwContent,
                xAnchor: 0.5,
                yAnchor: 1.1,
                zIndex:20
            });
    });

    daum.maps.event.addListener(this.polyline, 'mouseout', function (mouseEvent) {
        if (_CustomOverlay != null) _CustomOverlay.setMap(null);
        this.setOptions({strokeColor: _LastPolylineEvent['cmtrGradColor']});
    });

    kakao.maps.event.addListener(this.polyline, 'click', polyclick);

    function polyclick(mouseEvent) {
        _CustomOverlayFlag = true;

        if (_CustomOverlayClick != null) _CustomOverlayClick.setMap(null);

        const latlng = mouseEvent.latLng;

        const iwContent =
            `<div class="mapPop traffic_${cmtr_grad_cd}">
				<div class="head">
					<span class="title">${road_nm}</span>
					<span class="traffic">${cmtrGradText}</span>
				</div>
				<div class="cont">
					<dl>
						<dt>
							[ ${strt_nm_node} ] 부터<br/>
							[ ${end_nm_node} ] 까지
						</dt>
						<dd>
							소요시간 : 약 ${trvl_hh} 분<br/>
							평균속도 : ${sped} km/h
						</dd>
					</dl>
				</div>
			 </div>`;
        // console.log(road_id);
        // 인포윈도우를 생성하고 지도에 표시합니다
        _CustomOverlayClick = new daum.maps.CustomOverlay({
            map: _Map,
            position: latlng,
            content: iwContent,
            zIndex : 20,
            xAnchor: 0.5,
            yAnchor: 1.1
        });
    }

}

_CctvCtlrObj = function (obj) {
    this.web_rtc_id     = obj.web_rtc_id;
    this.area_cd        = obj.area_cd;
    this.cctv_capt_ip   = obj.cctv_capt_ip;
    this.cctv_capt_port = obj.cctv_capt_port;
    this.cctv_chnl      = obj.cctv_chnl;
    this.cctv_ctlr_id   = obj.cctv_ctlr_id;
    this.cctv_ctlr_ip   = obj.cctv_ctlr_ip;
    this.cctv_ctlr_port = obj.cctv_ctlr_port;
    this.cctv_encd_ip   = obj.cctv_encd_ip;
    this.cctv_fibr_ip   = obj.cctv_fibr_ip;
    this.cctv_mngm_nmbr = obj.cctv_mngm_nmbr;
    this.cmnc_stts_cd   = obj.cmnc_stts_cd;
    this.del_yn         = obj.del_yn;
    this.istl_lctn_addr = obj.istl_lctn_addr;
    this.istl_lctn_nm   = obj.istl_lctn_nm;
    this.link_id        = obj.link_id;
    this.node_id        = obj.node_id;
    this.rely_port      = obj.rely_port;
    this.strm_http_addr = obj.strm_http_addr;
    this.strm_rtmp_addr = obj.strm_rtmp_addr;
    this.strm_rtsp_addr = obj.strm_rtsp_addr;
    this.strm_sesn_nm   = obj.strm_sesn_nm;
    this.strm_stor_addr = obj.strm_stor_addr;
    this.strm_svr_ip    = obj.strm_svr_ip;
    this.strm_svr_port  = obj.strm_svr_port;
    this.x_crdn         = obj.x_crdn;
    this.y_crdn         = obj.y_crdn;
    this.click          = false;
    this.cctvMarker     = null;

    let imageSrc = '/images/cctv/cctv-20.png', // 마커이미지의 주소입니다
        imageSize = new kakao.maps.Size(_size[_Level], _size[_Level]), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point(12, 0),
            alt: this.istl_lctn_nm+"- CCTV 마커"

        }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    let markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption),
        markerPosition = new kakao.maps.LatLng(this.y_crdn, this.x_crdn); // 마커가 표시될 위치입니다
    //기본 이미지
    this.normalImage = markerImage;

    //클릭 이미지
    this.clickImage  =  new kakao.maps.MarkerImage('/images/cctv/cctv-21.png', imageSize, imageOption);


    // 마커를 생성합니다
    this.cctvMarker = new kakao.maps.Marker(
        {map: _Map, position: markerPosition, image: markerImage, zindex: 10, clickable: true, title : this.istl_lctn_nm+" CCTV 영상보기", id:"IDDDD"}
    );
    this.cctvMarker.setVisible(false);
    this.cctvMarker.id = "idididid";


    kakao.maps.event.addListener(this.cctvMarker, 'mouseover', function () {
        if (_CctvOverlay != null)
            _CctvOverlay.setMap(null);

        var latlng = new kakao.maps.LatLng(obj.y_crdn, obj.x_crdn);
        var iwContent = '<div style="padding:7px;color:#666;background-color:#fff;border:1px solid #bbb">' + obj.istl_lctn_nm + '</div>'; // 인포윈도우에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다

        // 인포윈도우를 생성하고 지도에 표시합니다
        _CctvOverlay = new kakao.maps.CustomOverlay({map: _Map, position: latlng, content: iwContent, yAnchor: 1.1});
    });

    kakao.maps.event.addListener(this.cctvMarker, 'mouseout', function () {
        if (_CctvOverlay != null)
            _CctvOverlay.setMap(null);
        }
    );

    kakao.maps.event.addListener(this.cctvMarker, 'click', ()=>cctvClickEvt(this));

    function cctvClickEvt(obj) {
        let cctvList = $('#cctvList');
        if (_cctvPopupObj && _popUp) {
            _cctvPopupObj.click = false;
            _cctvPopupObj.cctvMarker.setImage(obj.normalImage);
            _popUp.close();
            _popUp = null;
            clearInterval(_interval);
            _interval = null;
            if (obj.cctv_mngm_nmbr === _cctvPopupObj.cctv_mngm_nmbr) {
                return
            }
        }

        if ($("#video").length > 0) {
            videojs("video").dispose();
        }
        clearCctvInterval();

        if (cctvList.length > 0) {
            scrollMove(obj.cctv_mngm_nmbr, '#cctvList');
        }

        //WEB_RTC_ID
        var UserAgent = navigator.userAgent;
        if (obj.web_rtc_id == null) {
            return alert('CCTV점검중 입니다.');
        }
        _cctvPopupObj = obj;
        if (UserAgent.match(/iPhone|iPad/) || UserAgent.match(/Android/)) {
            if (confirm("이동통신망(3G/4G)을 이용하여 CCTV를 보시면 별도의 데이터 통화료가 발생할 수 있습니다. 영상을 시청하시겠습니까?")) {
                //let url = window.location.protocol + "//" + window.location.host + "/traffic/popupCctvM.do?cctv_mngm_nmbr=" + cctv_mngm_nmbr
                let url = "http://" + window.location.host + "/traffic/popupCctvM.do?cctv_mngm_nmbr=" + obj.cctv_mngm_nmbr
                _popUp = window.open(url, 'popupCctvM');
                obj.click = true;
                obj.cctvMarker.setImage(obj.clickImage);
            }
        }
        else {
            //let url = window.location.protocol + "//" + window.location.host + "/traffic/popupCctv.do?cctv_mngm_nmbr=" + cctv_mngm_nmbr
            let url = "http://" + window.location.host + "/traffic/popupCctv.do?cctv_mngm_nmbr=" + obj.cctv_mngm_nmbr
            let options = 'scrollbars=no,toolbar=no,location=no,resizable=no,status=no,menubar=no,width=340, height=285, left=350, top=400';
            if (_RoadFlag) {
                options = 'scrollbars=no,toolbar=no,location=no,resizable=no,status=no,menubar=no,width=340, height=285, left=60, top=400';
            }
            _popUp = window.open(url, 'popupCctv', options);
            obj.click = true;
            obj.cctvMarker.setImage(obj.clickImage);
        }

        if (_popUp) {
            _interval = setInterval(function checkPopup() {
                if (_popUp.closed) {
                    clearInterval(_interval);
                    obj.click = false;
                    obj.cctvMarker.setImage(obj.normalImage);
                    _cctvPopupObj = null;
                    _interval = null;
                    if (cctvList.length > 0) {
                        $('.' + obj.cctv_mngm_nmbr).css('background-color', '#fff');
                    }
                }
            }, 1000);
        }
    }

    this.cctvClickEvt = cctvClickEvt;
}
cctvClose = function (cctv_num) {
    //videojs("video").dispose();
    //_Infowindow.setMap(null);
    webrtcPlayer1.Stop();
    window.close();


    if(_CctvFlag){
        $('#'+cctv_num).focus();
    }else{
        $('#cctvMapMenu').focus();
    }

}

clearCctvInterval = function() {
    displaySecond = 31;
    if(timerInterval != null) clearInterval(timerInterval);
}

showCCtvDisplayTime = function() {
    clearCctvInterval();
    timerInterval = setInterval(function () {
        displaySecond--;
        if(displaySecond >= 0)
        {
            $("#restTime").text(displaySecond);
        }
        else
        {
            webrtcPlayer1.Stop();
            clearCctvInterval();
            $("#dialog").text("CCTV 시청 시간이 만료되었습니다.\n계속 시청하시겠습니까?");
            $("#dialog").dialog({
                resizable: false,
                height:200,
                modal: false,
                //   zIndex:9000,
                title: "알림",
                beforeClose: function(event,ui){   // 창이 닫히기 직전에 호출되는 콜백함수.
                    //videojs("video").dispose();
                    //window.close();
                },
                buttons: {
                    "예": function() {
                        //videojs("video").play();
                        webrtcPlayer1.Play();
                        showCCtvDisplayTime();
                        $( this ).dialog( "close" );
                    },
                    "아니오": function() {
                        //$( this ).dialog( "close" );
                        //videojs("video").dispose();
                        webrtcPlayer1.Stop();
                        window.close();
                    }
                }
            });
        }
    }, 1000);
}

function openCCTV() {
    webrtcPlayer1.Play();
    showCCtvDisplayTime();
}

_VmsCtlrObj = function (
    vms_ctlr_nmbr,
    vms_nm,
    x_crdn,
    y_crdn,
    cmnc_stts_cd,
    cmmn_cd_kor_nm,
    phase,
    vms_dspl_msg_imag,
    phas_img_width,
    phas_img_height,
    vms_dspl_msg_txt
) {
    this.vms_ctlr_nmbr = vms_ctlr_nmbr;
    this.vms_nm = vms_nm;
    this.x_crdn = x_crdn;
    this.y_crdn = y_crdn;
    this.cmnc_stts_cd = cmnc_stts_cd;
    this.cmmn_cd_kor_nm = cmmn_cd_kor_nm;
    this.phase = phase;
    this.vms_dspl_msg_imag = vms_dspl_msg_imag;
    this.phas_img_width = phas_img_width;
    this.phas_img_height = phas_img_height;
    this.vms_dspl_msg_txt = vms_dspl_msg_txt;
    this.click = false;

    var imageSrc = '/images/vms/VMS-20.png', // 마커이미지의 주소입니다
        imageSize = new kakao.maps.Size(_size[_Level], _size[_Level]), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point(_size[_Level], _size[_Level]),
            alt: vms_nm+"- VMS 마커"
        }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption),
        markerPosition = new kakao.maps.LatLng(y_crdn, x_crdn); // 마커가 표시될 위치입니다
    this.normalImage = markerImage;
    this.clickImage  =  new kakao.maps.MarkerImage('/images/vms/VMS-21.png', imageSize, imageOption),
                        new kakao.maps.LatLng(y_crdn, x_crdn);
    // 마커를 생성합니다
    this.vmsMarker = new kakao.maps.Marker({
                        map: _Map,
                        position: markerPosition,
                        image: markerImage,
                        zindex: 10,
                        clickable: true,
                        alt: vms_nm + "VMS마커",
                        title : vms_nm +" VMS 레이어보기"
                    });

    this.vmsMarker.setVisible(false);

    kakao.maps.event.addListener(this.vmsMarker, 'mouseover', function () {
        if (_VmsOverlay != null) _VmsOverlay.setMap(null);

        const latlng = new kakao.maps.LatLng(y_crdn, x_crdn);
        var iwContent =
            `<div style="padding:7px;color:#666;background-color:#fff;border:1px solid #bbb">
        		${vms_nm}
    		</div>`;

        // 인포윈도우를 생성하고 지도에 표시합니다
        _VmsOverlay = new daum.maps.CustomOverlay({map: _Map, position: latlng, content: iwContent, xAnchor: 0.65, yAnchor: yAnchor[_Level]});
    });

    kakao.maps.event.addListener(this.vmsMarker, 'mouseout', function (mouseEvent) {
        if (_VmsOverlay != null) _VmsOverlay.setMap(null);
    });

    kakao.maps.event.addListener(this.vmsMarker, 'click', vmsClickEvt);

    // function vmsClickEvt(obj) {
    function vmsClickEvt() {
        if ($('.vmsListM').length > 0) { //모바일 vms리스트 싱크
            $('.vmsListM option:contains(' + vms_nm + ')').prop('selected', true);
        }
        clearInterval(vmsImgInterval);

        if (_VmsInfoWindow != null) _VmsInfoWindow.setMap(null);

        scrollMove(vms_ctlr_nmbr, '#vmsList');

        var imgW = 230;
        var imgH = 0;
        var phaseImg = '';
        var iwContent;
        let yAnchor = 1.15;
        $.ajax({
            type    : "POST",
            url     : '/common/getVmsPhaseImg.do',
            data    : 'vmsCtlrNmbr=' + vms_ctlr_nmbr,
            success : function (data) {
                if (data && data.length > 0) {
                    data.forEach((obj, idx)=>{
                        const {vms_dspl_msg_imag, vms_dspl_msg_txt, phas_img_width, phas_img_height} = obj;
                        if (vms_dspl_msg_imag) {
                            let display = "none";
                            if (idx === 0) display = "block";
                            imgH = phas_img_height + 40;
                            let altTxt = vms_dspl_msg_txt;
                            if (altTxt === "") altTxt = "교통/홍보 메시지";
                            phaseImg +=
                                `<p class="vmsPic" style="display:${display}; width:${phas_img_width}px; height:${phas_img_height}px; ">
                                    <img src="data:image/png;base64,${vms_dspl_msg_imag}" alt="${altTxt}"/>
                                </p>`;
                        }
                        else {
                            imgH = 50;
                            phaseImg = '<p class="nodata">데이터 없음</p>';
                            yAnchor = 1.3;
                        }
                    })
                }
                else {
                    imgH = 50;
                    phaseImg = '<p class="nodata">데이터 없음</p>';
                    yAnchor = 1.3;
                }
            },
            complete: function () {
                iwContent =
                    `<div class="map_popup_vms" style="width:auto; height: auto; min-width: 200px;">
                		<dl>
                			<dt>
                				<h3 style="position:static;color:white;">${vms_nm}</h3>
                    			<p class="vmsMenu" style="position: relative;top: -15px;">
                    				<a id="previous" href="javascript:rotateImg('before')">
                    					<img src="/images/vms/prev.png" alt="이전"/>
                					</a>
                					<a href="javascript:rotateImg('after')">
                						<img src="/images/vms/next.png" alt="다음"/>
            						</a>
            						<a href="javascript:pauseVms(${vms_ctlr_nmbr})">
            							<img id="pApImg" src="/images/vms/pause.png" alt="멈춤" style="width:15px;"/>
        							</a>
        							<a id="vmsClose" href="javascript:closeVms('${vms_ctlr_nmbr}')">
        								<img src="/images/vms/xbtn.png"  alt="닫기"/>
        							</a>
    							</p>
							</dt>
							<dd>${phaseImg}</dd>
						</dl>
					</div>`;


                let latlng = new daum.maps.LatLng(Number(y_crdn), Number(x_crdn));

                _VmsInfoWindow = new daum.maps.CustomOverlay({position: latlng, content: iwContent, zindex: 15, xAnchor: 0.55, yAnchor: yAnchor });
                _Map.setCenter(latlng);
                _VmsInfoWindow.setMap(_Map);

                vmsImgInterval = setInterval("rotateImg()", 3000);

                $('#previous').focus();

                rotateImg = function (isType) {
                    const picArr = $(".vmsPic");
                    let hideIndex;

                    picArr.each(function (index) {
                        if ($(this).css('display') == 'block') {
                            hideIndex = index;
                        }
                    });

                    let blockIdx = hideIndex === picArr.length - 1 ? 0 : hideIndex + 1;

                    if (isType) {
                        if (isType === 'before') {
                            blockIdx = hideIndex < 0 ? picArr.length-1 : hideIndex - 1;
                        }
                        else {
                            blockIdx = hideIndex + 1 >= picArr.length ? 0 : hideIndex + 1;
                        }
                    }

                    picArr.eq(hideIndex).css('display', 'none');
                    picArr.eq(blockIdx).css('display', 'block');
                }

                pauseVms = function () {
                    if (vmsImgInterval == null) {
                        vmsImgInterval = setInterval("rotateImg()", 3000);
                        $('#pApImg').attr('src','/images/vms/pause.png');
                        $('#pApImg').attr('alt','멈춤');
                    }
                    else {
                        clearInterval(vmsImgInterval);
                        vmsImgInterval = null;
                        $('#pApImg').attr('src','/images/vms/play.png');
                        $('#pApImg').attr('alt','재생');
                    }
                }

                closeVms = function (vmsNo) {
                    _VmsInfoWindow.setMap(null);
                    $("." + vmsNo).css('background-color', 'white');
                    $(".vmsListM").val("");
                    // if (_VmsFlag) {
                    //     $('#'+vmsNo).focus();
                    // }
                    // else {
                    //     $('#vmsMapMenu').focus();
                    // }
                }
            },
            error: function (e) {
                alert('getVmsPhasImg ajax error');
            }
        });
    }

    this.vmsClickEvt = vmsClickEvt;
}


_IncdOcrrObj = function (
    incd_ocrr_id,
    link_id,
    incd_strt_dt,
    incd_end_prar_dt,
    road_name,
    incd_titl,
    incd_expl,
    incd_type_code,
    cmmn_cd_kor_nm,
    x_crdn,
    y_crdn
) {
    this.incd_ocrr_id = incd_ocrr_id;
    this.incd_strt_dt = incd_strt_dt;
    this.incd_end_prar_dt = incd_end_prar_dt;
    this.road_name = road_name;
    this.incd_titl = incd_titl;
    this.incd_expl = incd_expl;
    this.cmmn_cd_kor_nm = cmmn_cd_kor_nm;
    this.x_crdn = x_crdn;
    this.y_crdn = y_crdn;

    var imageSrc = '/images/incd/INCD' + incd_type_code + '.png', // 마커이미지의 주소입니다
        imageSize = new kakao
            .maps
            .Size(24, 24), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point(12, 12),
            alt: "돌발마커  -"+incd_titl

        }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption),
        markerPosition = new kakao.maps.LatLng(y_crdn, x_crdn); // 마커가 표시될 위치입니다

    // 마커를 생성합니다
    this.incdMarker = new kakao.maps.Marker({
                        map: _Map,
                        position: markerPosition,
                        image: markerImage,
                        zindex: 10,
                        clickable: true,
                        title : "돌발 정보 레이어보기" +incd_titl
                    });
    this.incdMarker.setVisible(false);

    kakao.maps.event.addListener(this.incdMarker, 'mouseover', function () {
            if (_IncdOverlay != null)
                _IncdOverlay.setMap(null);

            var latlng = new kakao.maps.LatLng(y_crdn, x_crdn);
            var iwContent =
                `<div style="padding:7px;color:#666;background-color:#fff;border:1px solid #bbb;">
                    ${incd_titl}
                </div>`;
            // 인포윈도우를 생성하고 지도에 표시합니다
            _IncdOverlay = new kakao.maps.CustomOverlay({map: _Map, position: latlng, content: iwContent, yAnchor: 1.3});
        });

    kakao.maps.event.addListener(this.incdMarker, 'mouseout', function (mouseEvent) {
         if (_IncdOverlay != null) _IncdOverlay.setMap(null);
    });

    kakao.maps.event.addListener(this.incdMarker, 'click', incdClickEvt);

    function incdClickEvt() {
        if (_IncdInfoWindow != null) {
            _IncdInfoWindow.setMap(null);
        }
        var latlng = new kakao.maps.LatLng(y_crdn, x_crdn);
        var iwContent =
            `<div class="incdPop">
                <div class="head" >
                    <span class="title ellip">${incd_titl}</span>
                    <a id="incdClose" href="javascript:incdCloseInfo('${incd_ocrr_id}')">
                        <img src="/images/incd/bt_close.gif"  alt="닫기" title="닫기" >
                    </a>
                </div>
                <div class="cont">
                    <dl>
                        <dd style="word-break: break-all; white-space: normal;">위치 : ${road_name}</dd>
                        <dd style="word-break: break-all; white-space: normal;">설명 : ${incd_expl}</dd>
                        <dd>기간 : ${incd_strt_dt} 부터 <p style="margin-left: 39px;">${incd_end_prar_dt} 까지</p>
                    </dd>
                </dl>
            </div>`;

        _IncdInfoWindow = new kakao.maps.CustomOverlay({
            position: latlng,
            content: iwContent,
            zindex: 15,
            xAnchor: 0.5,
            yAnchor: 1.1
        });

        let location = new kakao.maps.LatLng(Number(y_crdn), Number(x_crdn));
        _Map.setCenter(location);
        _IncdInfoWindow.setMap(_Map);

        if ($('#incdList').length > 0){
            scrollMove(incd_ocrr_id, '#incdList');
        }
        if (document.querySelector('.incdListM')) {
            $('.incdListM').val(incd_ocrr_id);
        }


    }

    this.incdClickEvt = incdClickEvt;
    $('#incdClose').focus();
    incdCloseInfo = function (id) {
        _IncdInfoWindow.setMap(null);
        if(_InciFlag){
            $('#'+id).focus();
        }else{
            $('#incdMapMenu').focus();
        }
        $('.'+id).css('background-color', '#fff');
    }

}


//주차정보
function getParkingInfo() {
    $.ajax({
        type : 'post',
        url : '/common/getParkingInfo.do',
        success : function(data){
            if (data && data.length) {
                data.forEach(function (el) {
                    _ParkingInfoArr.push(new _ParkingInfoObj(
                        el.park_id,
                        el.park_nm,
                        el.park_type_cd,
                        el.park_type,
                        el.park_fee,
                        el.park_fee_type,
                        el.park_num,
                        el.addr,
                        el.x_crdn,
                        el.y_crdn,
                        el.rmrk
                    ));
                });
            }
        },
        complete: function () {
            if ($("#parkingList").length > 0) {
                showParkingInfo();
                _Map.relayout();
            }
        },
        error   : function (request, status, error) {
            console.error("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

_ParkingInfoObj = function (
    park_id,
    park_nm,
    park_type_cd,
    park_type,
    park_fee,
    park_fee_type,
    park_num,
    addr,
    x_crdn,
    y_crdn,
    rmrk,
    comm_type
) {
    this.park_id = park_id;
    this.park_nm = park_nm;
    this.park_type_cd = park_type_cd;
    this.park_fee = park_fee;
    this.park_num = park_num;
    this.addr = addr;
    this.x_crdn = x_crdn;
    this.y_crdn = y_crdn;
    this.rmrk = rmrk;
    this.comm_type = comm_type;

    // if(comm_type ==0){
    let imageSrc = '/images/parking/map_icon_pin.png', // 마커이미지의 주소입니다
        imageSize = new kakao.maps.Size((_size[_Level] +2), (_size[_Level] +2)), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point((_size[_Level] +2)/2, (_size[_Level] +2)/2),
            alt: park_nm + " - 주차장마커"
        }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    let markerImage    = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption),
        markerPosition = new kakao.maps.LatLng(x_crdn, y_crdn); // 마커가 표시될 위치입니다

    // 마커를 생성합니다
    this.parkingMarker = new kakao.maps.Marker({
        map: _Map,
        position: markerPosition,
        image: markerImage,
        zindex: 10,
        clickable: true,
        title : park_nm +" 주차장 레이어보기"
    });

    this.parkingMarker.setVisible(false);

    kakao.maps.event.addListener(this.parkingMarker, 'mouseover', function () {

        if (_ParkingOverlay != null) _ParkingOverlay.setMap(null);

        const iwPosition = new kakao.maps.LatLng(x_crdn, y_crdn), //인포윈도우 표시 위치입니다
              iwContent  = `<div style="padding:7px; color:#666; background-color:#fff; border:1px solid #bbb;">
                                ${park_nm}
                            </div>`; // 인포윈도우에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다

        _ParkingOverlay = new kakao.maps.CustomOverlay({
            map: _Map,
            position: iwPosition,
            content: iwContent,
            yAnchor: 1.3
        });
    });

    kakao.maps.event.addListener(this.parkingMarker, 'mouseout', function (mouseEvent) {
        if (_ParkingOverlay != null)
            _ParkingOverlay.setMap(null);
        }
    );

    kakao.maps.event.addListener(this.parkingMarker, 'click', function () {
        if ($('#trafficSelect').length > 0) { //모바일 주차장리스트 싱크
            $('#trafficSelect option:contains(' + park_nm + ')').prop('selected', true);
        }

        $('.list').scrollTop(155);
        if (typeof $('.' + park_id).offset() != 'undefined') {
            $('.list').animate({
                scrollTop: $('.' + park_id).offset().top
            }, 400);
        }

        parkingClickEvt();
    });


    function parkingClickEvt() {

        if (_ParkingInfoWindow != null) _ParkingInfoWindow.setMap(null);
        var latlng = new kakao.maps.LatLng(x_crdn, y_crdn);
        var content =
            `<div class="popupHeader">
                    <div class="popOnHeader">&nbsp;&nbsp;${park_nm}</div>
                        <a href="javascript:parkingPopClose('${park_id}')" id="parkingClose" class="bt_popClose" title="닫기"></a>
                        <h1 style="display:none;"><span>${park_nm}</span></h1>
                    </div>
				 	 <div class="popupContent">
				 	 	<div class="parkingInfoTB">
				 	 		<table>
				 	 			<caption style="color:#293347">주차장 정보</caption>
				 	 			<tbody>
				 	 				<tr>
				 	 					<th>
				 	 						<div class="parkInfo"style="display:none">주차장 정보</div>
			 	 						</th>
			 	 					</tr>
			 	 					<tr>
			 	 						<th>
			 	 							<div class=pkLabel>주차면 수</div>
			 							</th>
			 							<td>${park_num} 대</td>
				 	 				</tr>
				 	 				<tr>
				 	 					<th>
				 	 						<div class=pkLabel>구분</div>
			 	 						</th>
			 	 						<td>${park_type}</td>
			 						</tr>
			 						<tr>
				 						<th>
				 							<div class=pkLabel>기본요금</div>
										</th>
										<td>${park_fee_type}</td>
									</tr>	
									<tr>
				 						<th>
				 							<div class=pkLabel>주소</div>
										</th>
										<td>${addr}</td>
									</tr>
				 	 			</tbody>
			 	 			</table>
			 			</div>
					</div>`;

        _ParkingInfoWindow = new kakao.maps.InfoWindow({position: latlng, content: content, zindex: 15});
        _Map.setCenter(latlng);
        _ParkingInfoWindow.setMap(_Map);
        scrollMove(park_id, '#parkingList');
        $('#parkingClose').focus();
    }

    this.parkingClickEvt = parkingClickEvt;

    parkingPopClose = function (id) {
        _ParkingInfoWindow.close();
        if (document.querySelector("." + id) !== null) {
            $("." + id).css('background-color', 'white');
            $(".parkingListM").val("");
        }
    }
}
function showParkingInfo() {
    var str = '';
    var strM = '<option value="">주차장 선택</option>';
    if (_ParkingInfoArr.length > 0) {
        _ParkingInfoArr.forEach((obj)=>{
            if (obj.parkingMarker) {
                obj.parkingMarker.setVisible(true);
            }
            if ($('#parkingList').length > 0) {
                str += `<li class="${obj.park_id}">
                            <a href="javascript:showParkInfo('${obj.park_id}')" title="${obj.park_nm}">${obj.park_nm}</a>
                        </li>`;
                strM += `<option value="${obj.park_id}">${obj.park_nm}</option>`;
            }
        })

        if ($('#parkingList').length > 0) {
            $('#parkingList').empty().html(str);
            $('.parkingListM').empty().html(strM);
        }
    }
}

function showParkInfo(parkingId) {
    const idx = _ParkingInfoArr.findIndex((obj)=>{
        return obj.park_id === parkingId;
    });
    if (idx >=0 && _ParkingInfoArr[idx]) {
        const pObj = _ParkingInfoArr[idx];
        pObj.parkingClickEvt();
        $('.parkingListM').val(parkingId);
    }

}

function hideParkingInfo() {
    if (_ParkingInfoArr.length > 0) {
        _ParkingInfoArr.forEach((obj)=>{
            if (obj.parkingMarker) {
                obj.parkingMarker.setVisible(false);
            }
        })
    }
}

/* TAAS(위험) 데이터 객체화  */

_TaasInfoObj = function (
    safe_id,
    add_jibun,
    link_id,
    report_date,
    add_new,
    l_cd,
    m_cd,
    s_cd,
    x_crdn,
    y_crdn,
    m_cd_nm,
    l_cd_nm
) {
    this.safe_id = safe_id;
    this.add_jibun = add_jibun;
    this.link_id = link_id;
    this.report_date = report_date;
    this.add_new = add_new;
    this.l_cd = l_cd;
    this.m_cd = m_cd;
    this.s_cd = s_cd;
    this.x_crdn = x_crdn;
    this.y_crdn = y_crdn;
    this.l_cd_nm = l_cd_nm;
    this.m_cd_nm = m_cd_nm;

    var imageSrc = '/images/map_icon_taas.png', // 마커이미지의 주소입니다
        imageSize = new kakao
            .maps
            .Size(24, 24), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point(12, 0),
            alt: m_cd_nm + " " +add_jibun + " - 교통안전 마커"

        }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    var markerImage = new kakao
            .maps
            .MarkerImage(imageSrc, imageSize, imageOption),
        markerPosition = new kakao
            .maps
            .LatLng(y_crdn, x_crdn); // 마커가 표시될 위치입니다

    // 마커를 생성합니다
    this.taasMarker = new kakao.maps.Marker(
            {map: _Map, position: markerPosition, image: markerImage, zindex: 10, clickable: true,title : "교통안전 "+ m_cd_nm + " 레이어 보기"}
        );
    this
        .taasMarker
        .setVisible(false);
    // SF1 : TAAS, SF2 : 위험요소, SF3 : 보호구역 SF100 : 무단횡단, SF101 : 보행어린이, SF102 : 스쿨존,
    // SF103 : 보행노인,SF104 : 자전거, SF201 : 보행자별, SF202 : 법규위반별, SF203 : 도로환경별, SF300 :
    // 어린이보호구역, SF301, 노인보호구역, SF302 : 장애인보호구

    kakao.maps.event.addListener(this.taasMarker, 'mouseover', function () {
            if (_TaasOverlay != null)
                _TaasOverlay.setMap(null);

            var iwContent = '<div style="padding:7px;color:#666;background-color:#fff;border:1px solid #bbb' +
                    '" ">교통 안전</div>', // 인포윈도우에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다
                iwPosition = new kakao.maps.LatLng(y_crdn, x_crdn); //인포윈도우 표시 위치입니다

            _TaasOverlay =  new kakao.maps.CustomOverlay({
                                map: _Map,
                                position: iwPosition,
                                content: iwContent,
                                yAnchor: 1.1
                            });
        });

    kakao.maps.event.addListener(this.taasMarker, 'mouseout', function (mouseEvent) {
        if (_TaasOverlay != null) _TaasOverlay.setMap(null);
    });

    kakao.maps.event.addListener(this.taasMarker, 'click', function () {
        taasClickEvt();
    });

    function taasClickEvt() {

        if (_TaasInfoWindow != null)
            _TaasInfoWindow.setMap(null);
        var latlng = new kakao
            .maps
            .LatLng(y_crdn, x_crdn);
        var content = '';

        content += '<div class="popupTaas">';
        content += '<span>교통안전 정보</span>';
        //content += '<a href="javascript:taasPopClose()" id="taasClose" class="bt_popClose" title="닫기" tabIndex="-' + '1"></a>';
        content += '<a href="javascript:taasPopClose()" id="taasClose" class="bt_popClose" title="닫기"></a>';
        content += '</div>';
        content += '<div class="TaasContent">';
        content += '<div class="taasInfoTB">';
        content += '<table><caption>교통안전 정보</caption>';
        content += '<tbody>';
        content += '<tr>';
        content += '<th><label>구분</label></th>';
        content += '<td>' + l_cd_nm + '</td>';
        content += '</tr>';
        content += '<tr>';
        content += '<th><label>구분 상세</label></th>';
        content += '<td>' + m_cd_nm + '</td>';
        content += '</tr>';
        content += '<tr>';
        content += '<th><label>날짜</label></th>';
        content += '<td>' + report_date + '</td>';
        content += '</tr>';
        content += '<tr>';
        content += '<th><label>주소</label></th>';
        content += '<td>' + add_jibun + '</td>';
        content += '</tr>';
        content += '</tbody>';
        content += '</table>';
        content += '</div>';
        content += '</div>';

        _TaasInfoWindow = new kakao
            .maps
            .InfoWindow(
                {position: latlng, content: content, zindex: 15, xAnchor: 1}
            );
        $('#taasClose').focus();
        _Map.setCenter(latlng);
        _TaasInfoWindow.setMap(_Map);
    }

    this.taasClickEvt = taasClickEvt;

    taasPopClose = function () {
        _TaasInfoWindow.close();
        $('#taasMapMenu').focus();
    }
}


/*소통정보입력*/

function getVertexArr() {

    TrafficInfoArrDelete();

    $.ajax({
        type: "POST",
        contentType:"application/x-www-form-urlencoded;charset=utf-8",
        url: '/common/getRoadVertexArr.do',
        success: function (data) {
            if (data && data.length > 0) {
                data.forEach(function (el) {
                    if (el.levl == 5) {
                        _RoadVrtx5Arr.push(new _RoadVertexObj(
                            el.atrd_id,
                            el.atrd_nm,
                            el.drct_cd,
                            el.road_id,
                            el.road_nm,
                            el.strt_nm_node,
                            el.end_nm_node,
                            el.sect_lngt,
                            el.levl,
                            el.x_crdn,
                            el.y_crdn,
                            el.x_crdn_min,
                            el.x_crdn_max,
                            el.y_crdn_min,
                            el.y_crdn_max,
                            el.cmtr_grad_cd,
                            el.sped,
                            el.trvl_hh,
                            el.road_ord
                        ));
                    }
                    else if (el.levl == 6) {
                        _RoadVrtx6Arr.push(new _RoadVertexObj(
                            el.atrd_id,
                            el.atrd_nm,
                            el.drct_cd,
                            el.road_id,
                            el.road_nm,
                            el.strt_nm_node,
                            el.end_nm_node,
                            el.sect_lngt,
                            el.levl,
                            el.x_crdn,
                            el.y_crdn,
                            el.x_crdn_min,
                            el.x_crdn_max,
                            el.y_crdn_min,
                            el.y_crdn_max,
                            el.cmtr_grad_cd,
                            el.sped,
                            el.trvl_hh,
                            el.road_ord
                        ));
                    }
                });
                _TrafficInfoArr[7] = _RoadVrtx5Arr;
                _TrafficInfoArr[8] = _RoadVrtx5Arr;
                _TrafficInfoArr[9] = _RoadVrtx5Arr;
                _TrafficInfoArr[10] = _RoadVrtx5Arr;
                _TrafficInfoArr[11] = _RoadVrtx5Arr;
            }
        },
        complete: function () {
            if (_TrafficFlag === false && _Level >= 7) {
                drawVertexArr();
            }
        },
        error: function (request, status, error) {
        },
        beforeSend: function () {
            $('#loading').show();
        }
    });


    $.ajax({
        type: "post",
        url: '/common/getIfscVertexArr.do',
        success: function (data) {
            if (data && data.length > 0) {
                data.forEach(function (el) {
                    if (el.levl == 3) {
                        _IfscVrtx3Arr.push(new _RoadVertexObj(
                            el.atrd_id,
                            el.atrd_nm,
                            el.drct_cd,
                            el.road_id,
                            el.road_nm,
                            el.strt_nm_node,
                            el.end_nm_node,
                            el.sect_lngt,
                            el.levl,
                            el.x_crdn,
                            el.y_crdn,
                            el.x_crdn_min,
                            el.x_crdn_max,
                            el.y_crdn_min,
                            el.y_crdn_max,
                            el.cmtr_grad_cd,
                            el.sped,
                            el.trvl_hh
                        ));
                    } else if (el.levl == 4) {
                        _RoadVrtx4Arr.push(new _RoadVertexObj(
                            el.atrd_id,
                            el.atrd_nm,
                            el.drct_cd,
                            el.road_id,
                            el.road_nm,
                            el.strt_nm_node,
                            el.end_nm_node,
                            el.sect_lngt,
                            el.levl,
                            el.x_crdn,
                            el.y_crdn,
                            el.x_crdn_min,
                            el.x_crdn_max,
                            el.y_crdn_min,
                            el.y_crdn_max,
                            el.cmtr_grad_cd,
                            el.sped,
                            el.trvl_hh
                        ));
                    }
                });

                //레벨단위로 저장

                // _TrafficInfoArr[4] = _IfscVrtx3Arr;
                _TrafficInfoArr[5] = _IfscVrtx3Arr;
                _TrafficInfoArr[6] = _IfscVrtx3Arr;
                // _TrafficInfoArr[6] = _RoadVrtx4Arr;
            }
        },
        complete: function () {
            if (_TrafficFlag === false && _Level >= 5 && _Level <= 6) {
                drawVertexArr();
            }
            $('#loading').hide();
        },
        error: function (request, status, error) {
        },
        beforeSend: function () {
        }
    });

    $.ajax({
        type: "POST",
        url: '/common/getLinkVertexArr.do',
        success: function (data) {
            data.forEach(function (el) {
                if (el.levl == 1) {
                    _IfscVrtx2Arr.push(new _RoadVertexObj(
                        el.atrd_id,
                        el.atrd_nm,
                        el.drct_cd,
                        el.road_id,
                        el.road_nm,
                        el.strt_nm_node,
                        el.end_nm_node,
                        el.sect_lngt,
                        el.levl,
                        el.x_crdn,
                        el.y_crdn,
                        el.x_crdn_min,
                        el.x_crdn_max,
                        el.y_crdn_min,
                        el.y_crdn_max,
                        el.cmtr_grad_cd,
                        el.sped,
                        el.trvl_hh
                    ));
                }

            });
            _TrafficInfoArr[4] = _IfscVrtx2Arr;
        },
        complete: function () {
            if (_TrafficFlag === false && _Level <= 4) drawVertexArr();
        },
        error: function (request, status, error) {
        },
        beforeSend: function () {
        }
    });

}




/*소통정보 삭제*/
//커스텀 오버레이 삭제
function hideVertexArr() {
    if (_CustomOverlay != null)
        _CustomOverlay.setMap(null);

    //줌 변경시 마우스오버 색상 (파랑 -> 소통정보색상) 변경
    if (Object.keys(_LastPolylineEvent).length != 0) {
        _LastPolylineEvent['line'].setOptions(
            {strokeColor: _LastPolylineEvent['cmtrGradColor']}
        );
    }

    if (_BeforePolyline.length > 0) {
        for (var ii = 0; ii < _BeforePolyline.length; ii++) {
            _BeforePolyline[ii].setMap(null);
            _BeforePolylineBack[ii].setMap(null);
        }
    }
}
/*소통정보 그리기*/

function drawVertexArr() {
    let bounds = _Map.getBounds();
    let swLatLng = bounds.getSouthWest();
    let neLatLng = bounds.getNorthEast();

    hideVertexArr();
    let Level = _Level;
    if (_Level <= 3) {
        Level = 0;
    }

    const trafficInfo = _TrafficInfoArr[Level];
    if (trafficInfo && trafficInfo.length > 0) {
        _RoadListStr = "";
        let atrdBwdSped = 0,
            atrdBwdLngt = 0,
            roadCnt     = 0,
            atrdFwdSped = 0,
            atrdFwdLngt = 0;
        _AtrdFrontPoly = null;
        _AtrdBackPoly  = null;

        trafficInfo.forEach(function (el) {
            let xCrdnArr = el.x_crdn.split(',');
            let yCrdnArr = el.y_crdn.split(',');
            if (_AtrdId) {
                const atrdInfoArr = _AtrdId.split(",");
                const front       =  atrdInfoArr[0];
                const end         =  atrdInfoArr[1];
                if (front === el.atrd_id || end === el.atrd_id) {
                    el.polylineBack.setOptions({
                        strokeColor: '#000000', //black
                        zIndex: 4
                    });

                    el.polyline.setOptions({zIndex: 5});

                    _RoadListStr +=
                        `<li>
                            <div class="roadName">[${el.drct_cd}] ${el.atrd_nm}</div>
                            <div class="roadDetail">
                                <span>${el.strt_nm_node}</span>
                                <span class="arrow">화살표</span>
                                <span>${el.end_nm_node}</span>
                                <span>${el.sped} km/h</span>
                            </div>
                            <div class="trafficBullet">
                                <span class="${el.cmtr_grad_cd}">${el.cmtrGradText}</span>
                            </div>
                        </li>`;

                    if (front === el.atrd_id) {
                        if (!_AtrdFrontPoly) _AtrdFrontPoly = el.polyline;
                        if (el.sped > 0) {
                            roadCnt++;
                            atrdFwdSped += el.sped;
                        }
                        atrdFwdLngt += el.sect_lngt;
                    }
                    else if (end === el.atrd_id) {
                        if (!_AtrdBackPoly) _AtrdBackPoly = el.polyline;
                        if (el.sped > 0) {
                            atrdBwdSped += el.sped;
                        }
                        atrdBwdLngt += el.sect_lngt;
                    }
                }
                else {
                    el.polylineBack.setOptions({strokeColor: '#fff', zIndex: 2});
                    el.polyline.setOptions({zIndex: 3});
                }
            }
            for (let ii = 0; ii < xCrdnArr.length; ii++) {
                if (swLatLng.getLng() - 0.0015555 <= xCrdnArr[ii] &&
                    swLatLng.getLat() - 0.0015555 <= yCrdnArr[ii] &&
                    neLatLng.getLng() + 0.0015555 >= xCrdnArr[ii] &&
                    neLatLng.getLat() + 0.0015555 >= yCrdnArr[ii]) {
                    el.polylineBack.setMap(_Map);
                    el.polyline.setMap(_Map);

                    _BeforePolylineBack.push(el.polylineBack);
                    _BeforePolyline.push(el.polyline);
                }
            }
        });

        if (_RoadListStr.length > 0) {
            $('#mapOfLetters').empty().html(_RoadListStr);
            atrdFwdSped = isNumber(atrdFwdSped, roadCnt, 2);
            atrdBwdSped = isNumber(atrdBwdSped, roadCnt, 2);
            atrdFwdLngt = isNumber(atrdFwdLngt, null, 0);
            atrdBwdLngt = isNumber(atrdBwdLngt, null, 0);
            $('.upload-sped').text(atrdFwdSped);
            $('.dnload-sped').text(atrdBwdSped);
            $('.upload-lngt').text(atrdFwdLngt);
            $('.dnload-lngt').text(atrdBwdLngt);
        }
    }
}
/*vms data 가저오기*/

function getVmsCtlr() {
    $.ajax({
        type: "POST",
        url: '/common/getVmsCtlr.do',
        success: function (data) {
            if (data && data.length > 0) {
                data.forEach(function (el) {
                    _VmsCtlrArr.push(new _VmsCtlrObj(
                        el.vms_ctlr_nmbr,
                        el.vms_nm,
                        el.x_crdn,
                        el.y_crdn,
                        el.cmnc_stts_cd,
                        el.cmmn_cd_kor_nm,
                        el.phase,
                        el.vms_dspl_msg_imag,
                        el.phas_img_width,
                        el.phas_img_height,
                        el.vms_dspl_msg_txt
                    ));
                });
            }

        },
        complete: function () {
            //if(_VmsFlag==false)showVms();

            if ($('#vmsList').length > 0) showVms();
        }
        ,
        error: function (e) {
            //alert('getVmsCtlr ajax error');
        }
    });
}

function showVms() {
    var str = '';
    var strM = '';
    strM += '<option value="">VMS선택</option>';
    _VmsCtlrArr.forEach(function (el) {
        el.vmsMarker.setVisible(true);

        if ($('#vmsList').length > 0) {
            str += `<li class="${el.vms_ctlr_nmbr}">
                        <a href="javascript:showVmsInfo('${el.vms_ctlr_nmbr}', '${el.vms_nm}')"
                           id="${el.vms_ctlr_nmbr}" title="${el.vms_nm}">
                           ${el.vms_nm}
                        </a>
                    </li>`;
            strM += `<option value="${el.vms_ctlr_nmbr}">${el.vms_nm}</option>`;
        }
    });

    if ($('#vmsList').length > 0) {
        $('#vmsList').empty().html(str);
        $('.vmsListM').empty().html(strM);
    }
}

function hideVms() {
    _VmsCtlrArr.forEach(function (el) {
        el.vmsMarker.setVisible(false);
    });
}

/*cctv data 가저오기*/

function getCctvCtlr() {
    $.ajax({
        type: "POST",
        url: '/common/getCctvCtlr.do',
        success: function (data) {
            if (_CctvCtlrArr.length < 1) {
                if (data && data.length > 0) {
                    data.forEach(function (el) {
                        if (el) {
                            _CctvCtlrArr.push(new _CctvCtlrObj(el));
                        }
                    });
                }
            }
        },
        complete: function () {
            if ($('#cctvList').length > 0)
                showCctv();
        }
        ,
        error: function (e) {
            //alert('getCctvCtlr ajax error');
        }
    });
}

function hideCctv() {
    _CctvCtlrArr.forEach(function (el) {
        el
            .cctvMarker
            .setVisible(false);
    });
}

function showCctv() {
    var str = '';
    var strM = '';
    strM += '<option value="">CCTV선택</option>';
    _CctvCtlrArr.forEach(function (el) {
        el
            .cctvMarker
            .setVisible(true);
        if ($('#cctvList').length > 0) {
            str += '<li class="'+el.cctv_mngm_nmbr+'"><a href="javascript:showCctvInfo(' + el.cctv_mngm_nmbr + ',\''+el.istl_lctn_nm+'\')" id ="'+el.cctv_mngm_nmbr+'"title="' + el.istl_lctn_nm +
                '">' + el.istl_lctn_nm + '</a></li>';
            strM += '<option value="' + el.cctv_mngm_nmbr + '">' + el.istl_lctn_nm + '</option>';
        }
    });

    if ($('#cctvList').length > 0) {
        $('#cctvList').html(str);
        $('#cctvListM').html(strM);
    }
    $('#cctvList li').on('click', function (){
        for (let ii = 0; ii < $('#cctvList li').length; ii++) {
            if ($('#cctvList li')[ii] === $(this)[0]){
                continue;
            }
            $('#cctvList li').eq(ii).css('background-color', '#fff');
        }
        if ($(this).css('background-color') === 'rgb(255, 255, 255)') {
            $(this).css('background-color', '#eee');
        }
        else {
            $(this).css('background-color', '#fff');
        }
    })
}

/*돌발 data 가저오기*/
function getIncdOcrr() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: '/common/getIncdOcrr.do',
        success: function (data) {
            if (data && data.length > 0) {
                data.forEach(function (el) {
                    _IncdOcrrArr.push(new _IncdOcrrObj(
                        el.incd_ocrr_id,
                        el.link_id,
                        el.incd_strt_dt,
                        el.incd_end_prar_dt,
                        el.road_name,
                        el.incd_titl,
                        el.incd_expl,
                        el.incd_type_code,
                        el.cmmn_cd_kor_nm,
                        el.x_crdn,
                        el.y_crdn
                    ));
                });
            }
        },
        complete: function () {
            if (_InciFlag === false) showIncd();

            var mainStr = '';

            if (_IncdOcrrArr.length > 0) {
                _IncdOcrrArr.forEach(function (el) {
                    //메인화면 돌발정보 표출..
                    if ($('#incdMainList').length > 0) {
                        mainStr += '<li><span>' + el.cmmn_cd_kor_nm +
                            '</span><a href="javascript:void(0)" title="' + el.incd_titl + '">위치: ' + el.road_name +
                            '<br>사고상황 : ' + el.incd_titl + '</a></li>';
                    }
                });

            }
            if ($('#incdMainList').length > 0) {
                if (_IncdOcrrArr.length == 0)
                    mainStr += '<li><span></span><a href="javascript:void(0)" title="돌발정보가 없습니다.">돌발정보가 없습니다.<' +
                        '/a></li>';
                $('#incdMainList').empty().html(mainStr);
            }
        },
        error: function (e) {
            alert('getIncdOcrr ajax error');
        }
    });
}

function hideIncd() {
    _IncdOcrrArr.forEach(function (el) {
        el
            .incdMarker
            .setVisible(false);
    });
}

function showIncd() {

    var str = '';
    var mainStr = '';
    var strM = '';
    strM += '<option value="">돌발 목록</option>';
    if (_IncdOcrrArr.length > 0) {
        _IncdOcrrArr.forEach(function (el) {
            el.incdMarker.setVisible(true);
            if ($('#incdList').length > 0) {
                str += '<li class="'+ el.incd_ocrr_id+'"><a href="javascript:showIncdInfo(\'' + el.incd_ocrr_id + '\',\''+el.incd_titl+'\')" id="' + el.incd_ocrr_id + '" title="' +
                    el.incd_titl + '">' + el.incd_titl + '</a></li>';
                strM += '<option value="' + el.incd_ocrr_id + '">' + el.incd_titl + '</option>';
            }
            //메인화면 돌발정보 표출..
            if ($('#incdMainList').length > 0) {
                mainStr += '<li><span>' + el.cmmn_cd_kor_nm +
                    '</span><a href="javascript:void(0)" title="' + el.incd_titl + '">위치: ' + el.road_name +
                    '<br>사고상황 : ' + el.incd_titl + '</a></li>';
            }
        });
    } else {

        // str += '<li><a href="javascript:void(0)" title="돌발정보가 없습니다.">돌발정보가 없습니다.</a></li>';
        str += `<li style="justify-content: center; height:100%; background: none;">
                    <div class="no-data" style="font-size: 18px;">
                        <img src="/images/main/no_info_icon.png" width="50">돌발정보가 없습니다.
                    </div>
                </li>`;
    }

    if ($('#incdList').length > 0) {
        $('#incdList').empty().html(str);
        $('.incdListM').empty().html(strM);
    }

    if ($('#incdMainList').length > 0) {
        if (_IncdOcrrArr.length == 0) {
            mainStr += '<li><span></span><a href="javascript:void(0)" title="돌발정보가 없습니다.">돌발정보가 없습니다.</a></li>';
        }
        $('#incdMainList').empty().html(mainStr);
    }
}

function getVisitCount(){
    $.ajax({
        type: "POST",
        url: '/common/getVisitCount.do',
        success: function (data) {
            let today = '-';
            let total = '-';
            if (data) {
                if (data.today && data.today >= 0) today = data.today.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                if (data.total && data.total >= 0) total = data.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
            $('.count').html(
                `<div>오늘의 방문자수 : <div>${ today } 명</div></div>
                <div>누적 방문자수 &nbsp;&nbsp;&nbsp;: <div>${ total } 명</div></div>`);
        },
        error: function (e) {
            alert('getVisitCount ajax error');
        }
    });
}

function setCookie(name, value, expiredays) {
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" +
        todayDate.toGMTString() + " Secure;"
}

function getCookie (name) {
    var nameOfCookie = name + "=";
    var x = 0; while (x <= document.cookie.length) {
        var y = (x + nameOfCookie.length);
        if (document.cookie.substring(x, y) == nameOfCookie) {
            if ((endOfCookie = document.cookie.indexOf(";", y)) == -1)
                endOfCookie = document.cookie.length;
            return unescape(document.cookie.substring(y, endOfCookie));
        }
        x = document.cookie.indexOf(" ", x) + 1; if (x == 0)
            break;
    }
    return "";
}

function scrollMove(id, name){
    let cnt;
    for (let ii = 0; ii < $(name+' li').length; ii++) {
        $(name+' li').eq(ii).css('background-color', '#fff');
        if ($(name + ' li')[ii] === $('.' + id)[0]) {
            cnt = ii;
        }
    }
    $('.' + id).css('background-color', '#eee');
    if ($(name+' li').length >= 15) {
        $(name).animate( { scrollTop : cnt * 47  +'px'}, 500 );
    }
}

function fileDownload(fileId, fileName, boardNo) {
    let href = "/notice/getFile.do?fileId="+ fileId + "&fileName=" + encodeURIComponent(fileName);
    if (boardNo) href += "&boardNo=" +boardNo;

    location.href = href;
}



$('body').on('click', (e)=>{
    const idName = e.target.getAttribute('id');
    if ( idName !== 'Btn1' && idName !== 'Btn2') {
        $('#Dropdown1').removeClass('show');
        $('#Dropdown2').removeClass('show');
        _isSubMenuClick = false;
        _isSubCategoryClick = false;
    }
})

function navToggleClick(){
    const _targetNav =  $('.header_inner');
    if (_targetNav.hasClass("on")) {
        _targetNav.removeClass("on");
    }
    else {
        _targetNav.addClass("on");
    }
}

function subMenuToggle() {
    if (_isSubCategoryClick) {
        $('#Dropdown2').removeClass('show');
        _isSubCategoryClick = false;
    }

    if (_isSubMenuClick) {
        $('#Dropdown1').removeClass('show');
    }
    else {
        $('#Dropdown1').addClass('show');
    }
    _isSubMenuClick = !_isSubMenuClick;
}

function subCategoryToggle() {
    if (_isSubMenuClick) {
        $('#Dropdown1').removeClass('show');
        _isSubMenuClick = false;
    }

    if (_isSubCategoryClick) {
        $('#Dropdown2').removeClass('show');
    }
    else {
        $('#Dropdown2').addClass('show');
    }
    _isSubCategoryClick = !_isSubCategoryClick;
}

function goBack(){
    history.back();
}