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 _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;
_size[0]  = 48;
_size[1]  = 48;
_size[2]  = 32;
_size[3]  = 24;
_size[4]  = 24;
_size[5]  = 24;
_size[6]  = 24;
_size[7]  = 24;
_size[8]  = 24;
_size[9]  = 24;
_size[10] = 24;

/* 전역변수 초기화 */
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
) {
    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.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 (let ii = 0; ii < xCrdnArr.length; ii++) {
        linePath.push(new kakao.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 kakao
        .maps
        .Polyline({
            path: linePath,
            strokeWeight: strokeWeight,
            strokeColor: cmtrGradColor,
            strokeOpacity: 1,
            strokeStyle: 'solid',
            zIndex: 2

        });

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

    kakao
        .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;
            if (_iwContent) {
                _iwContent.remove();
            }
            let str = '<div class="mapPop traffic_' + cmtr_grad_cd + '">';
            if (_RoadFlag) {
                str = '<div class="mapPop traffic_' + cmtr_grad_cd + ' off">';
            }
            _iwContent = $(str
                + '<div class="head"><span class="title">' + road_nm + '</span><span class="traff'
                + 'ic">' + 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>');
            $('.main-container').append(_iwContent);

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

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

    function polyclick(mouseEvent) {
//		_CustomOverlayFlag = true;
//		if(_CustomOverlayClick != null){
//			_CustomOverlayClick.setMap(null);
//			//_CustomOverlayFlag = false;
//		}
//		//alert("ROAD_ID: "+road_id);
//		var latlng = mouseEvent.latLng;
//		var iwContent = '<div class="mapPop traffic_' + cmtr_grad_cd + '">';
//		iwContent += '<div class="head"><span class="title">' + road_nm + '</span><span class="traffic">' + cmtrGradText + '</span></div>';
//		iwContent += '<div class="cont">';
//		iwContent += '<dl>';
//		iwContent += '<dt>[ ' + strt_nm_node + ' ] 부터<br/>[ ' + end_nm_node + ' ] 까지</dt>';
//		/*iwContent += '<input id="roadid" value="'+road_id+'">';*/
//		iwContent += '<dd>소요시간 : 약 ' + trvl_hh + ' 분<br/>평균속도 : ' + sped + ' km/h</dd>';
//		iwContent += '</dl></div>';
//
//		// 인포윈도우를 생성하고 지도에 표시합니다
//		_CustomOverlayClick = new kakao.maps.CustomOverlay({
//			map: _Map,
//			position: latlng,
//			content: iwContent,
//			zIndex : 20,
//			xAnchor: 0.5,
//			yAnchor: 1.1
//		});
//         if (_iwContent ) {
//             _iwContent.remove();
//         }
//         if (!cmtr_grad_cd) {
//             _iwContent.remove();
//         }
//         else {
//             _iwContent = $('<div class="mapPop traffic_' + cmtr_grad_cd + '">'
//                 + '<div class="head"><span class="title">' + road_nm + '</span><span class="traff'
//                 + 'ic">' + 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>');
//             $('.main-container').append(_iwContent);
//         }
        //클립보드 복사
        /*var copyText = document.getElementById("roadid");
          copyText.select();
          document.execCommand("Copy");*/

    }

}

_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;

    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 : "새창열림", 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(this.y_crdn, this.x_crdn);
        var iwContent = '<div style="padding:7px;color:#666;background-color:#fff;border:1px solid #bbb">' + this.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) {
        if (_cctvPopupObj && _popUp) {
            if (obj.cctv_mngm_nmbr === _cctvPopupObj.cctv_mngm_nmbr) {
                _popUp.close();
                _popUp = null;
                obj.click = false;
                obj.cctvMarker.setImage(obj.normalImage);
                return
            }
            else {
                _cctvPopupObj.click = false;
                _cctvPopupObj.cctvMarker.setImage(obj.normalImage);
                if (_interval) {
                    clearInterval(_interval);
                    _interval = null
                }
            }
        }

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

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

        //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 if (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
            //         window.open(url, 'popupCctvM');
            //     }
        }
        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;
                }
            }, 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
        {

            //videojs("video").pause();
            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;
    var imageSrc = '/images/vms/VMS-20.png', // 마커이미지의 주소입니다
        imageSize = new kakao
            .maps
            .Size(_size[_Level], _size[_Level]), // 마커이미지의 크기입니다
        imageOption = {
            offset: new kakao.maps.Point(12, 0),
            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);
    this.click = false;
    // 마커를 생성합니다
    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);

            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' +
                '">' + vms_nm + '</div>'; // 인포윈도우에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다

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

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

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

//todo : Where to load VMS Image

    function vmsClickEvt(obj) {
        console.log($('#vmsListM'));
        if ($('#vmsListM').length > 0) { //모바일 vms리스트 싱크
            $('#vmsListM option:contains(' + vms_nm + ')').prop('selected', true);
        }
        if (_beforeClickVms) {
            _beforeClickVms.vmsMarker.setImage(_beforeClickVms.normalImage);
            _beforeClickVms.click = false;
        }
        _beforeClickVms = obj;
        obj.vmsMarker.setImage(obj.clickImage);
        obj.click = true;
        clearInterval(vmsImgInterval);

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

        var width = 230;
        var height = 80;
        var phaseImg = '';
        var iwContent;
        $.ajax({
            type: "POST",
            url: '/common/getVmsPhaseImg.do',
            data: 'vmsCtlrNmbr=' + vms_ctlr_nmbr,
            success: function (data) {

                if (data && data.length > 0) {
                    data.forEach((vmsObj, idx)=>{
                        if (!vmsObj.vms_dspl_msg_imag) {
                            phaseImg += '<p class="nodata" alt="시스템 점검중입니다.">시스템 점검중입니다.</p>';
                        }
                        else {
                            let display = idx === 0 ? "block" : "none";
                            let title = vmsObj.title;
                            if (title === null) title = '교통/홍보 메시지';
                            if (vmsObj.phas_img_width)  width = vmsObj.phas_img_width + 10;
                            if (vmsObj.phas_img_height) height =vmsObj.phas_img_height + 40;
                            if (vmsObj.vms_dspl_msg_imag) {
                                phaseImg += `<p class="vmsPic" style="display:${display}">
                    				<img src="data:image/png;base64, ${vmsObj.vms_dspl_msg_imag}" alt="${title}" />
                    			</p>`;
                            }
                        }
                    })
                }
                else {
                    phaseImg = '<p class="nodata">시스템 점검중입니다.</p>';
                }

            },
            complete: function () {
                var latlng = new kakao.maps.LatLng(Number(y_crdn), Number(x_crdn));

                iwContent = '<div class="map_popup_vms" style="width:' + width + 'px; height:' + height + 'px;"><dl><dt><p>' + vms_nm + '</p>'+
                    '<p class="vmsMenu"><a href="javascript:prevVms('+vms_ctlr_nmbr+')"> <img src="/images/vms/prev.png" alt="이전"/></a>' +
                    '<a href="javascript:nextVms('+vms_ctlr_nmbr+')"> <img src="/images/vms/next.png"  alt="다음"/>    </a>' +
                    '<a href="javascript:pauseVms('+vms_ctlr_nmbr+')"><img src="/images/vms/pause.png" alt="멈춤/재생"/></a>' +
                    '<a href="javascript:closeVms('+vms_ctlr_nmbr+')"><img src="/images/vms/xbtn.png"  alt="닫기"/></a></p>'+
                    '</dt><dd>' + phaseImg + '</dd></dl></div>';

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

                vmsImgInterval = setInterval("rotateImg('" + vms_ctlr_nmbr + "')", 3000);
                ////////////////////여기
                $('#vmsClose').focus();

                rotateImg = function (divId) {
                    var displayIndex;
                    var picArr = $(".vmsPic");

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

                    if (displayIndex == picArr.length - 1) {
                        picArr
                            .eq(displayIndex)
                            .css('display', 'none');
                        picArr
                            .eq(0)
                            .css('display', 'block');
                    } else {
                        picArr
                            .eq(displayIndex)
                            .css('display', 'none');
                        picArr
                            .eq(displayIndex + 1)
                            .css('display', 'block');
                    }
                }

                prevVms = function (vmsNo) {
                    var displayIndex = 0;
                    var prevIndex = 0;

                    var picArr = $(".vmsPic");

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

                    prevIndex = displayIndex - 1;

                    if (displayIndex < 0) {
                        prevIndex = picArr.length-1;
                    }

                    picArr
                        .eq(displayIndex)
                        .css('display', 'none');
                    picArr
                        .eq(prevIndex)
                        .css('display', 'block');
                }
                nextVms = function (vmsNo) {
                    var displayIndex = 0;
                    var nextIndex = 0;

                    var picArr = $(".vmsPic");

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

                    nextIndex = displayIndex + 1;

                    if (nextIndex >= picArr.length) {
                        nextIndex = 0;
                    }

                    picArr
                        .eq(displayIndex)
                        .css('display', 'none');
                    picArr
                        .eq(nextIndex)
                        .css('display', 'block');
                }
                pauseVms = function (vmsNo) {
                    if (vmsImgInterval == null) {
                        vmsImgInterval = setInterval("rotateImg('" + vms_ctlr_nmbr + "')", 3000);
                    }
                    else {
                        clearInterval(vmsImgInterval);
                        vmsImgInterval = null;
                    }
                }

                closeVms = function (vmsNo) {
                    _VmsInfoWindow.setMap(null);
                    if(_VmsFlag){
                        $('#'+vmsNo).focus();
                    }else{
                        $('#vmsMapMenu').focus();
                    }
                    if (_beforeClickVms){
                        _beforeClickVms.vmsMarker.setImage(_beforeClickVms.normalImage);
                        _beforeClickVms.click = false;
                    }
                }
            },
            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, 0),
            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>'; // 인포윈도우에 표출될 내용으로 HTML 문자열이나 document element가 가능합니다

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

    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">';
        iwContent += '<div class="head" ><span class="title ellip">' + incd_titl + '</span>';
        iwContent += '<a id="incdClose" href="javascript:incdCloseInfo(\''+incd_ocrr_id+'\')"><img src="/images/bt_close.gif"  alt="닫기" title="닫기" ></a></div>';
        iwContent += '<div class="cont">';
        iwContent += '<dl>';
        iwContent += '<dd>위치 : ' + road_name + '</dd>';
        if(incd_expl.length > 25){
            iwContent += '<dd>설명 : ' + incd_expl.substr(0,25) + '<br>'+incd_expl.substr(25,incd_expl.length)+'</dd>';
        }else{
            iwContent += '<dd>설명 : ' + incd_expl + '</dd>';
        }
        iwContent += '<dd>기간 : ' + incd_strt_dt + ' 부터 <p>' + incd_end_prar_dt + ' 까지</p></dd>';
        iwContent += '</dl></div>';
        _IncdInfoWindow = new kakao.maps.CustomOverlay({
            //map: _Map,
            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);



    }

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

}

_ParkingInfoObj = function (
    park_id,
    park_nm,
    park_type_cd,
    park_fee,
    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){
        var imageSrc = '/images/map_icon_pin.png', // 마커이미지의 주소입니다
            imageSize = new kakao
                .maps
                .Size(24, 24), // 마커이미지의 크기입니다
            imageOption = {
                offset: new kakao.maps.Point(12, 0),
                alt: park_nm + " - 주차장마커"
            }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.
    }else if(comm_type ==1){
        var imageSrc = '/images/map_icon_pin2.png', // 마커이미지의 주소입니다
            imageSize = new kakao
                .maps
                .Size(24, 24), // 마커이미지의 크기입니다
            imageOption = {
                offset: new kakao.maps.Point(12, 0),
                alt: park_nm + " - 주차장마커"
            }; // 마커이미지의 옵션입니다. 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정합니다.
    }

    // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
    var 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);

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

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

    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);
            }
            if(comm_type ==1){
                parkingClickEvt(comm_type);
            }else{
                parkingClickEvt();
            }
        });


    function parkingClickEvt(comm) {

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

        var typeCd = park_type_cd == 1
            ? '노상'
            : park_type_cd == 2
                ? '노외'
                : '부설';
        var fee = park_fee == null
            ? '정보없음'
            : park_fee == 1
                ? '유료'
                : '무료';
        content += '<div class="popupHeader" style="z-index:99;">';
        content += '<div class="popOnHeader">&nbsp;&nbsp;'+park_nm+'</div>';
        content += '<a href="javascript:parkingPopClose(\''+park_id+'\')" id="parkingClose" class="bt_popClose" title="닫기"></a>';
        content += '<h1 style="display:block;"><span>' + park_nm + '</span></h1></div>';
        content += '<div class="popupContent">';
        content += '<div class="parkingInfoTB">';

        content += '<table>';
        //content += '<caption>주차장 정보</caption>';
        content += '<tbody>';

        content += '<tr><th><div class="parkInfo">주차장 정보</div></th>';
        if(comm == 1){
            content += '<td style="border-bottom: none;"><div class="detailInfo">상세 정보</div></td>';
        }



        //str += '<li class="' + el.park_id + '"><a href="javascript:showParkingInfo(\'' + el.park_id +'\',\''+ el.park_nm +'\')" id="'+el.park_id+'" title="' + el.park_nm + '" 	>' + el.park_nm + '</a></li>';



        content += '</tr>';

        content += '<tr><th><label>주차면 수</label></th>';
        content += '<td>' + park_num + ' 대</td>';
        content += '</tr>';
        content += '<tr><th><label>구분</label></th>';
        content += '<td>' + typeCd + '</td>'
        content += '</tr>';
        content += '<tr>';
        content += '<th><label>기본요금</label></th>';
        content += '<td>' + fee + '</td>';
        content += '</tr>';
        content += '<th><label>주소</label></th>';
        content += '<td>' + addr + '</td></tr>';
        content += '</tbody></table></div></div>';
        /*		content += '<div class="popupHeader" style="z-index:99;">';
		content += '<span>'+ park_nm +'</span>';
		content += '<a href="javascript:parkingPopClose()" class="bt_popClose" title="닫기" tabindex="-1"></a></div>';
		content += '<div class="popupContent">';
		content += '<div class="parkingInfoTB">';
		content += 	'<table><tbody><tr>';
		content += '<th><label>주차면 수</label></th>';
		content += 	'<td>'+ park_num +' 대</td>';
		content += 	'</tr>';
		content += 	'<tr>';
		content += 	'<th><label>장애인 주차</label></th>';
		content += 	'<td>'+ park_hndc_num +' 대</td>';
		content += 	'</tr>';
		content += 	'<tr><th><label>구분</label></th>';
		content += 	'<td>'+ typeCd + '</td>'
		content += 	'</tr>';
		content += 	'<tr>';
		content += 	'<th><label>기본요금</label></th>';
		content += 	'<td>'+ fee +'</td>';
		content += 	'</tr>';
		content += 	'<tr><th><label>추가요금</label></th><td class="chargeSize"><table><tbody><tr>';
		content += 	'<td>소형 : -</td></tr><tr><td>최대 : -</td>';
		content += 	'</tr><tr><td>대형 : -</td></tr>';
		content += 	'<tr><td>최대 : -</td></tr>';
		content += 	'</tbody></table></td></tr>';
		content += 	'<tr>';
		content += 	'<th><label>주소</label></th>';
		content += 	'<td>'+ addr +'</td></tr>';
		content += 	'<tr><th><label>연락처</label></th>';
		content += 	'<td>-</td></tr>'; 
		content += 	'</tbody></table></div></div>';*/
        _ParkingInfoWindow = new kakao.maps.InfoWindow({position: latlng, content: content, zindex: 15});
        _Map.setCenter(latlng);
        _ParkingInfoWindow.setMap(_Map);

        $(".detailInfo").on('click', function(){
//        	 let listVal ="<tr onClick="+"location.href='/boards/userView?name="+ii.name+"' style='cursor:pointer'>"+

            window.open("/parking/parkingPop.do?id="+park_id,"parkingInfo","width=1500,height=650,top=100,right=500");

        })

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

        if (typeof $(park_id).offset() != 'undefined') {
            parrkingInfoStr(
                park_id,
                park_nm,
                park_type_cd,
                park_fee,
                park_num,
                addr,
                x_crdn,
                y_crdn,
                rmrk,
                comm_type
            );
        }
    }

    this.parkingClickEvt = parkingClickEvt;

    parkingPopClose = function (id) {
        _ParkingInfoWindow.close();
        if(_ParkingFlag){
            $('#'+id).focus();
        }else{
            $('#parkingMapMenu').focus();
        }


    }
}

/* 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) {
            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
                    ));
                }
                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
                    ));
                }

            });
            _TrafficInfoArr[7] = _RoadVrtx5Arr;
            _TrafficInfoArr[8] = _RoadVrtx6Arr;
            _TrafficInfoArr[9] = _RoadVrtx6Arr;
        },
        complete: function () {
            if (_TrafficFlag == false) {
                drawVertexArr();
            }
            $('#loading').hide();

            showIncd()
        },
        error: function (request, status, error) {
        },
        beforeSend: function () {

            $('#loading').show();
        }
    });


    $.ajax({
        type: "post",
        url: '/common/getIfscVertexArr.do',
        success: function (data) {

            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[5] = _IfscVrtx3Arr;
            _TrafficInfoArr[6] = _RoadVrtx4Arr;

        },
        complete: function () {
            drawVertexArr();
        },
        error: function (request, status, error) {
        },
        beforeSend: function () {
        }
    });




    $.ajax({
        type: "POST",
        contentType:"application/x-www-form-urlencoded;charset=utf-8",
        url: '/common/getLinkVertexArr.do',
        success: function (data) {
            data.forEach(function (el) {
                if (el.levl == 2) {
                    _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 () {
            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() {
    var bounds = _Map.getBounds();
    var swLatLng = bounds.getSouthWest();
    var neLatLng = bounds.getNorthEast();

    hideVertexArr();
    if (_RoadListStr != '' && _RoadListStr.length > 0) {
        _RoadListStr = '';
        $('#mapOfLetters').empty();
    }
    var Level = _Level;
    if (_Level <= 3) {
        Level = 0;
    }

//    if (typeof _TrafficInfoArr[Level] == 'undefined') {
//    	if (Level != 0) {
//    		Level--;
//    	}
//    }
//    if (typeof _TrafficInfoArr[Level] == 'undefined') {
//    	Level = Level + 2;
//    }


    if (typeof _TrafficInfoArr[Level] != 'undefined') {
        const trafficInfo = [..._TrafficInfoArr[Level]];

        trafficInfo.sort(function(a, b){
            if (a.drct_cd > b.drct_cd) {
                return 1;
            }
            else if (a.drct_cd === b.drct_cd) {
                if (a.atrd_nm > b.atrd_nm) {
                    return 1;
                }
                if (a.atrd_nm === b.atrd_nm) {
                    if (a.strt_nm_node === b.end_nm_node) {
                       return 1;
                    }
                    else if (b.strt_nm_node === a.end_nm_node) {
                       return -1;
                    }
                }
                else {
                    return -1;
                }
            }
            else {
                return -1;
            }
        });

        //_TrafficInfoArr[Level].forEach(function (el) {
        trafficInfo.forEach(function (el) {
            if (el.atrd_id) {
                var xCrdnArr = el
                    .x_crdn
                    .split(',');
                var yCrdnArr = el
                    .y_crdn
                    .split(',');

                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);

                        //소통정보 문자 입력..

                    }
                }
            }
        });

        //_TrafficInfoArr[Level].forEach(function (el) {
        trafficInfo.forEach(function (el) {
            if (el.atrd_id) {
                if ($('.mapRoadList').length > 0) {
                    _RoadListStr += '<li>' +
                        '    <div class="road_info">' +
                        '        <div class="atrd-top">' +
                        '           <div>[' + el.drct_cd + ']' + el.atrd_nm + '</div>' +
                        '            <strong>' + el.sped + ' km/h</strong>' +
                        '       </div>' +
                        '        <div class="atrd-bottom">' +
                        '           <div class="atrd-front">' + el.strt_nm_node + '</div> ' +
                        '           <span class="arrow-icon"><img src="../common/images/arrow_icon.png" alt=""></span>' +
                        '           <div class="atrd-end">' + el.end_nm_node + '</div>' +
                        '           <strong>' + el.sped + ' km/h</strong></div>' +
                        '    </div>' +
                        '    <aside class="road-traffic">' +
                        '        <span class="traffic' + el.cmtrGradText + '">' + el.cmtrGradText + '</span>' +
                        '    </aside>' +
                        '</li>'
                }
            }
        });
        if (document.querySelector('#mapOfLetters') && _RoadListStr.length > 0) {
            $('#mapOfLetters').html(_RoadListStr);
        }
    }
}
/*vms data 가저오기*/

function getVmsCtlr() {
    $.ajax({
        type: "POST",
        url: '/common/getVmsCtlr.do',
        success: function (data) {
            if (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><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) {
                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><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);
    }
}

/*돌발 data 가저오기*/

function getIncdOcrr() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: '/common/getIncdOcrr.do',
        success: function (data) {
            if (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 ($('#incdList').length > 0)
                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);
            }

            /* 돌발정보 롤링 */

            jQuery(function ($) {

                var timer = null;
                var itemRolling = null;
                var hoverFlag = false;

                /* 돌발 롤링 */
                $(".rolling-box").each(function () {

                    if ($("#incdMainList").length > 0) {

                        var $itemList = $(this).children("ul");
                        var itemNum = $itemList
                            .children("li")
                            .size();
                        var itemHeight = $itemList
                            .children("li")
                            .outerHeight();
                        var itemMinNum = 3; // 자동롤링이 시작되어야 하는 갯수

                        if (itemMinNum <= itemNum) {

                            $itemList
                                .find("li")
                                .prependTo($itemList);
                            $itemList.css("marginTop", "-" + itemHeight + "px");

                            itemRolling = function () {

                                $itemList
                                    .not(":animated")
                                    .animate({
                                        marginTop: parseInt($itemList.css("margin-top")) - itemHeight + "px"
                                    }, 600, "swing", function () {
                                        $itemList.css("margin-top", "-" + itemHeight + "px");
                                        $itemList
                                            .find("li")
                                            .first()
                                            .appendTo($itemList);
                                    });
                            }
                            timer = setInterval(function () {
                                itemRolling();
                                hoverFlag = false;
                            }, 2000);
                        }

                        $(this).hover(function () {

                            clearInterval(timer);
                            timer = null;
                            hoverFlag = true;
                        }, function () {
                            timer = setInterval(function () {

                                itemRolling();


                            }, 2000);
                            hoverFlag = false;
                        });

                        $(this).keyup(function () {
                            clearInterval(timer);
                            timer = null;
                            hoverFlag = true;
                        });

                        /*tab이동시 keydown이벤트 지정체정보 롤링 스타트*/
                        $('.info02 .head a').keyup(function () {
                            if (hoverFlag == true) {
                                timer = setInterval(function () {

                                    if($("#incdMainList").length > 2){
                                        itemRolling();
                                    }

                                }, 2000);
                                hoverFlag = false;
                            }
                        });

                        $('.info02 .head h3 a').keyup(function () {
                            if (hoverFlag == true) {
                                timer = setInterval(function () {
                                    itemRolling();
                                }, 2000);
                                hoverFlag = false;
                            }
                        });

                    }

                });

            });

        },
        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><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>';
    }

    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 getParkingInfo() {
    $.ajax({
        type: "POST",
        url: '/common/getParkingInfo.do',
        success: function (data) {
            if (data.length > 0) {
                data.forEach(function (el) {
                    _ParkingInfoArr.push(new _ParkingInfoObj(
                        el.park_id,
                        el.park_nm,
                        el.park_type_cd,
                        el.park_fee,
                        el.park_num,
                        el.addr,
                        el.x_crdn,
                        el.y_crdn,
                        el.rmrk,
                        el.comm_type
                    ));
                });
            }
        },
        complete: function () {
            if ($('#parkingList').length > 0)
                showParking();
        }
        ,
        error: function (e) {
            alert('getIncdOcrr ajax error');
        }
    });
}

/*주차상세정보 가저오기*/
function getParkingPopInfo() {
    $.ajax({
        type: "POST",
        url: '/common/getParkingPopInfo.do',
        success: function (data) {
            if (data.length > 0) {
                data.forEach(function (el) {
                    _ParkingInfoArr.push(new _ParkingInfoObj(
                        el.park_id,
                        el.park_nm,
                        el.park_type_cd,
                        el.park_fee,
                        el.park_num,
                        el.addr,
                        el.x_crdn,
                        el.y_crdn,
                        el.rmrk,
                        el.comm_type
                    ));
                });
            }
        },
        complete: function () {
            if ($('#parkingList').length > 0)
                showParking();
        }
        ,
        error: function (e) {
            alert('getIncdOcrr ajax error');
        }
    });
}

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

function hideParking() {
    _ParkingInfoArr.forEach(function (el) {
        el
            .parkingMarker
            .setVisible(false);
    });
}

function showParking() {

    var str = '';
    var strM = '';
    strM += '<option>주차장선택</option>';
    _ParkingInfoArr.forEach(function (el) {

        el.parkingMarker
            .setVisible(true);

        if ($('#parkingList').length > 0) {
            if(el.comm_type == 0){
                str += '<li class="' + el.park_id + '"><a href="javascript:showParkingInfo(\'' + el.park_id +'\',\''+ el.park_nm +'\')" id="'+el.park_id+'" title="' + el.park_nm + '" 	>' + el.park_nm + '</a></li>';
                strM += '<option value="' + el.park_nm + '">' + el.park_nm + '</option>';
            }else if(el.comm_type == 1){
                str += '<li class="' + el.park_id + '"><a class="comm_type" href="javascript:showParkingInfo(\'' + el.park_id +'\',\''+ el.park_nm +'\',\''+ el.comm_type +'\')" id="'+el.comm_type+'" title="' + el.park_nm + '" 	>' + el.park_nm + '</a></li>';
                strM += '<option value="' + el.park_id + '" value2="' + el.park_nm + '" value3="' + el.comm_type + '">' + el.park_nm + '</option>';
            }
        }
    });
    if ($('#parkingList').length > 0) {
        $('#trafficSelect').html(strM);
        $('#parkingList').html(str);
    }

}

function showParkM(){
    var id = $("#trafficSelect").val();
    var name = $("#trafficSelect > option:selected").attr("value2");
    var comm = $("#trafficSelect > option:selected").attr("value3");

    showParkingInfo(id,name,comm)
}

/* 위헙 정보  가져오기*/

function getTaasInfo() {
    $.ajax({
        type: "POST",
        url: '/common/getTaasInfo.do',
        success: function (data) {
            if (data.length > 0) {
                data.forEach(function (el) {
                    _TaasInfoArr.push(new _TaasInfoObj(
                        el.safe_id,
                        el.add_jibun,
                        el.link_id,
                        el.report_date,
                        el.add_new,
                        el.l_cd,
                        el.m_cd,
                        el.s_cd,
                        el.x_crdn,
                        el.y_crdn,
                        el.m_cd_nm,
                        el.l_cd_nm
                    ));
                });
            }
        },
        complete: function () {
            if (_TaasFlag == false)
                showTaas();
        }
        ,
        error: function (e) {
            alert('getIncdOcrr ajax error');
        }
    });
}

function hideTaas() {
    _TaasInfoArr.forEach(function (el) {
        el
            .taasMarker
            .setVisible(false);
    });
}

function showTaas() {
    _TaasInfoArr.forEach(function (el) {
        el
            .taasMarker
            .setVisible(true);
    });
}

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 "";
}