<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> 
<%@ page session="false" %>
<!doctype html>
<html lang="ko">
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"/>
	<meta name="Description" content="사이트설명" />
	<meta name="Keywords" content="키워드" />
	
	<%@ include file="/WEB-INF/views/common.jsp" %>
	
	<link rel="stylesheet" type="text/css" href="${contextRoot }/css/common.css" />
	<link rel="stylesheet" type="text/css" href="${contextRoot }/css/main.css" />
	<link rel="stylesheet" type="text/css" href="${contextRoot }/css/popupLayout.css" />
	<link rel="icon"       type="text/css" href="data:;base64,iVBORw0KGgo=" />
	
	<title>SIGINFO_MAP</title>
</head>
<body>
<input type="hidden" name="min_x" id="min_x" value=""/>
<input type="hidden" name="min_y" id="min_y" value=""/>
<input type="hidden" name="max_x" id="max_x" value=""/>
<input type="hidden" name="max_y" id="max_y" value=""/>
	<div id="wrap">
		<!-- header -->
		<header id="header2">
			<span>지역 : </span>
				<select class="select w80" id="centerList" onchange="getIntNo(this.value,true)">
					<option value="">선택</option>
					<c:forEach var="items" items="${centerList }">
					<option value="${items.REGION_CD }">${items.REGION_NM }</option>
					</c:forEach>
				</select>
			<span>교차로 : </span>
				<select class="select w250" id="intList" name="intList" onchange="selectInt(this.value)">
					<option value="">선택</option>
				</select>
		</header>
		<!-- header -->

		<!-- section -->
		<section id="contents">
		<article>
			<div class="map_wrap" id="map"></div>
			<img src="/images/loading.gif" class="showLoading" />
			<img src="/images/dataLoading.jpg" class="dataLoading" />
  		</article>

  		<article>		
		<div class="tab_type1">
			<ul>
				<li><a href="javascript:updateSigInfo()"  class="on" id="updateSigId" title="교차로 관리">교차로 관리</a></li>
				<li><a href="javascript:updatePhaseInfo()" id="updatePhaseId" title="현시정보 관리">현시 관리</a></li>
				<li><a href="javascript:updateLinkInfo()"  id="updateLinkId" title="링크정보 관리">링크 관리</a></li>
				<li><a href="javascript:intPhaseUpload()"  id="uploadId" title="업로드">업로드</a></li>
			</ul>
			<div class="clear"></div>
		</div>
		<div class="addSigDiv c_p1">
			<h2 id="sigMoveHead">상단메뉴의 지역과 제어기를 선택하여 주세요.</h2>
			<div class="table_cover" onclick="javascript:alert('상단메뉴의 지역과 제어기를 선택하여 주세요.');"></div>
			<table class="table_type3">
				<colgroup>
					<col width="10%">
					<col width="22%">
					<col width="10%">
					<col width="22%">
					<col width="10%">
					<col width="22%">
				</colgroup>
				<tbody>
					<tr>
						<th>네트워크유형</th>
						<td>
							<select id="addNetworkType" class="select w150" onchange="disabledFnc(this.value)" >
								<option value="0">유선</option>
								<option value="1">무선</option>
								<option value="2">유무선</option>
							</select>
						</td>
						<th>모뎀IP</th>
						<td colspan="3">
							<input type="text" id="addModemIp" value="" <c:if test="${networkType == 0 }" >disabled="true"</c:if> />
						</td>
					</tr>
					<tr>
						<th>지역센터</th>
						<td>
							<select id="addRegionCd" onChange="getSigungu(this.value)" class="select w150">
								<option value="">선택</option>
								<c:forEach var="item" items="${centerList }">
								<option value="${item.REGION_CD }">${item.REGION_NM }</option>
								</c:forEach>
							</select>
						</td>
						<th>시군구</th>
						<td colspan="3">
							<select id="addSigunguCd" class="select w150">
								<option value="">선택</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>교차로명</th>
						<td><input type="text" id="addIntNm"></td>
						<th>교차로번호</th>
						<td><input type="text" id="addIntNo"></td>
						<th>연동번호</th>
						<td><input type="text" id="addMainIntNo" class="w40"> ※ 0: 메인제어기 번호</td>
					</tr>
					<tr>
						<th>제어기 유형</th>
						<td>
							<select class="select w150" id="addIntLcType">
								<option value="1">2004년형</option>
								<option value="2">2010년형</option>
							</select>
						</td>
						<th>동기화유형</th>
						<td>
							<select id="addIntLampType" class="select w150">
								<option value="3">3색등화기</option>
								<option value="4">4색등화기</option>
							</select>
						</td>
						<th>주현시</th>
						<td>
							<select id="addIntMainphase" class="select w150">
								<c:forEach begin="0" end="7" var="i">
								<option value="${i }">${i }</option>
								</c:forEach>
							</select>
						</td>
					</tr>
					<tr>
						<th>그룹번호</th>
						<td><input type="text" id="addGrpNo"></td>
						<th>X좌표</th>
						<td><input type="text" class="w145" id="addXCoord"></td>
						<th>Y좌표</th>
						<td><input type="text" class="w145" id="addYCoord"></td>
					</tr>
				</tbody>
			</table>
			<ul class="addsig_bottom_btns">
				<li><a href="javascript:addSigdata()"    class="btn" id="addSigdata">추가</a></li>
				<li><a href="javascript:updateSigdata()" class="btn" id="updateSigdata">수정</a></li>
				<li><a href="javascript:deleteSigdata()" class="btn" id="deleteSigdata">삭제</a></li>
				<li><a href="javascript:saveSigdata()"   class="btn" id="saveSigdata">저장</a></li>
			</ul>
		</div>
		<div class="updatePhaseAdd">
			<div class="updatePhaseDiv"></div>
			<span class="updateMapNo">
				<label for="updateMapNo">맵번호  : </label>
				<select id="updateMapNo" onchange="phaseOnMap(this.value)"></select>
			</span>
			<div class="phaseInfoCon">
				<table class="table_type2">
					<thead>
						<tr>
							<th>현시</th>
							<th class="puA_1">1</th>
							<th class="puA_2">2</th>
							<th class="puA_3">3</th>
							<th class="puA_4">4</th>
							<th class="puA_5">5</th>
							<th class="puA_6">6</th>
							<th class="puA_7">7</th>
							<th class="puA_8">8</th>
						</tr>
					</thead>
					<tbody id="updatePhaseInfoList1"></tbody>
					<tbody id="updatePhaseInfoList2"></tbody>
				</table>
			</div>
			<div class="linkInfoCon">
				<table class="table_type2">
					<thead>
						<tr>
							<th>현시</th>
							<th>구분</th>
							<th class="puA_1">1</th>
							<th class="puA_2">2</th>
							<th class="puA_3">3</th>
							<th class="puA_4">4</th>
							<th class="puA_5">5</th>
							<th class="puA_6">6</th>
							<th class="puA_7">7</th>
							<th class="puA_8">8</th>
						</tr>
					</thead>
					<tbody id="updateLinkInfoList1"></tbody>
					<tbody id="updateLinkInfoList2"></tbody>
				</table>
			</div>
		</div>
		<div class="uploadDiv">
			<form id="uploadForm" method="post" enctype="Multipart/form-data">
			<h2>파일 업로드</h2>
			<table class="table_type4">
				<colgroup>
					<col width="20%">
				</colgroup>
				<tbody>
					<tr>
						<th>지역센터</th>
						<td>
							<select class="select w80" id="uploadRegionCd" name="uploadRegionCd">
								<c:forEach var="item" items="${centerList }">
								<option value="${item.REGION_CD }">${item.REGION_NM }</option>
								</c:forEach>
							</select>
						</td>
					</tr>
					<tr>
						<th>TB_INT</th>
						<td>
							<input type="file" class="w370 file" name="intInfoUpload" id="intInfoUpload">
							<input type="hidden" name="intInfoFileType" id="intInfoFileType" />
							<a class="btn2" href="javascript:intInfoUploadFnc()" data-show-upload="false" data-show-caption="true" id="intInfoUploadBtn">업로드</a>
						</td>
					</tr>
					<tr>
						<th>TB_INT_PHASE</th>
						<td>
							<input type="file" name="phaseInfoUpload" id="phaseInfoUpload" class="w370 file">
							<input type="hidden" name="phaseInfoFileType" id="phaseInfoFileType" />
							<a class="btn2" href="javascript:phaseInfoUploadFnc()" data-show-upload="false" data-show-caption="true" id="phaseInfoUploadBtn">업로드</a>
						</td>
					</tr>
				</tbody>
			</table>
			</form>
			<iframe src="/getExcelUploadFrame.do" id="excelUpload" class="excelUpload"></iframe>
		</div>
		</article>
		</section>
	</div>

<script src="${contextRoot }/js/common/hashmap.js" type="text/javascript" ></script>
<script src="${contextRoot }/js/common/common-all.js" type="text/javascript" ></script>
<script src="${contextRoot }/js/common/common.js" type="text/javascript" ></script>
<script src="${contextRoot }/js/signal.js" type="text/javascript" ></script>
<script src="${contextRoot }/js/cvib.js" type="text/javascript" ></script>
<script type="text/javascript">

var regionCd = '';
var intNo    = '';

var customOverlay    = null;
var addCircle        = null;
var _AddSigdataFlag  = false; 
var _CenterListId    = null;
var addClickListener = null;
var _CenterMarker    = null;
var _BackCircleFlag  = true;
var _CheckAddSigFlag;

var upTab01Id = false;
var upTab02Id = false;
var upTab03Id = false;
var upTab04Id = false;

_RegionCd     = '${regionCd}';
_IntNo        = '${intNo}';
_IntNm        = '${intNm}';
_XCoord       = ('${xCoord}' == '') ? '127.0626736' : '${xCoord}';
_YCoord       = ('${yCoord}' == '') ? '37.4972515' : '${yCoord}';
_GroupNo      = '${groupNo}';
_MainIntNo    = '${mainIntNo}';
_SigunguCd    = '${sigunguCd}';
_IntLcType    = '${intLcType}';
_IntLampType  = '${intLampType}';
_IntMainphase = '${intMainPhase}';
_NetworkType  = '${networkType}';
_ModemIp      = '${modemIp}';

initUpdateMap();

function initUpdateMap() {
	var mapContainer = document.getElementById('map') // 지도를 표시할 div
	var mapOption = {
		center: new kakao.maps.LatLng(_YCoord, _XCoord)
		//level: 5
	};
	map = new kakao.maps.Map(mapContainer, mapOption); // 지도생성

	//신호현시 줌,이동 이벤트 분리
	kakao.maps.event.addListener(map, 'zoom_changed', mapZoomBound);
	kakao.maps.event.addListener(map, 'dragend', mapMoveBound);//드래그 종료시 이벤트발생
	
	//왼쪽트리메뉴에서 교차로 선택시 정보관리창에서 지역 제어기 선택...
	if(_RegionCd.length > 0)
	{
		$('#centerList option[value="'+_RegionCd+'"]').prop('selected',true);
		getIntNo(_RegionCd,false);
	}

	var bounds = map.getBounds();
	var swLatlng = bounds.getSouthWest();
	var neLatlng = bounds.getNorthEast();

	$("#min_x").val(swLatlng.getLng());
	$("#min_y").val(swLatlng.getLat());
	$("#max_x").val(neLatlng.getLng());
	$("#max_y").val(neLatlng.getLat());

	_Flag = 'addSignal';
	updateSigInfo();
}

function updateSigInfo() {
	//탑메뉴 호버 클릭 이벤트 변화..
	upTab01Id = true;
	upTab02Id = false;
	upTab03Id = false;
	upTab04Id = false;
	
	emptySignalArr(linkLineArr);
	emptySignalArr(linkPhaseLineArr);
	emptySignalArr(_SubLinkLineArr);
	
	linkLineArr      = [];
	linkPhaseLineArr = [];
	_SubLinkLineArr  = [];
	
	$('.updatePhaseAdd').hide();
	$('.linkInfoCon').hide();
	//업로드 숨김
	$('.uploadDiv').hide();
	$('.addSigDiv').show();
	
	$('#updateLinkId').removeClass('on');
	$('#uploadId').removeClass('on');
	$('#updatePhaseId').removeClass('on');
	$('#updateSigId').addClass('on');
	
	map.relayout();
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	if(addCircle != null) addCircle.mapCircle.setMap(null);
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	
	_CenterListId = 'centerInfo';
	_BackCircleFlag = true;
	
	if(_RegionCd.length > 0 && String(_IntNo).length > 0)
	{
		_RegionNm     = $('#addRegionCd option:selected').text();
		
		var intInfo = _RegionCd+'|'+_RegionNm+'|'+_IntNo+'|'+_IntNm+'|'+_XCoord+'|'+_YCoord+'|'+
					  _GroupNo+'|'+_MainIntNo+'|'+_SigunguCd+'|'+_IntLcType+'|'+_IntLampType+'|'+
					  _IntMainphase+'|'+_NetworkType+'|'+_ModemIp;
		
		//시군구리스트 입력..
		if(_RegionCd != '') getSigungu(_RegionCd);
		
		selectInt(intInfo);
		
		$('#addRegionCd').val(_RegionCd);
		$('#addIntNo').val(_IntNo);
		$('#addMainIntNo').val(_MainIntNo);
		$('#addIntNm').val(_IntNm);
		$('#addGrpNo').val(_GroupNo);
		$('#addXCoord').val(_XCoord);
		$('#addYCoord').val(_YCoord);
		$('#addIntLcType').val(_IntLcType);
		$('#addIntLampType').val(_IntLampType);
		$('#addIntMainphase').val(_IntMainphase);
		$('#addNetworkType').val(_NetworkType);
		$('#addModemIp').val(_ModemIp);
	}
	else
	{
		new getSignalInfo(_Flag);
		//mapZoomBound();
	}
	
}

function updatePhaseInfo() {
	//탑메뉴 호버 클릭 이벤트 변화..
	upTab01Id = false;
	upTab02Id = true;
	upTab03Id = false;
	upTab04Id = false;
	
	emptySignalArr(linkLineArr);
	emptySignalArr(linkPhaseLineArr);
	emptySignalArr(_SubLinkLineArr);
	
	linkLineArr = [];
	linkPhaseLineArr = [];
	_SubLinkLineArr = [];
	
	//교차로관리 숨김
	$('.addSigDiv').hide();
	//업로드 숨김
	$('.uploadDiv').hide();
	//링크관리 숨김
	$('.linkInfoCon').hide();
	//현시관리 표출
	$('.updatePhaseAdd').show();
	$('.updateMapNo').show();
	$('.phaseInfoCon').show();
	
	$('#updateSigId').removeClass('on');
	$('#updateLinkId').removeClass('on');
	$('#uploadId').removeClass('on');
	$('#updatePhaseId').addClass('on');
	
	map.relayout();
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	if(addCircle != null) addCircle.mapCircle.setMap(null);
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	
	_CenterListId = 'phaseInfo';
	_BackCircleFlag = true;
	
	if(_RegionCd.length > 0 && String(_IntNo).length > 0)
	{
		var intInfo = _RegionCd+'|'+_RegionNm+'|'+_IntNo+'|'+_IntNm+'|'+_XCoord+'|'+_YCoord+'|'+
		              _GroupNo+'|'+_MainIntNo+'|'+_SigunguCd+'|'+_IntLcType+'|'+_IntLampType+'|'+
		              _IntMainphase+'|'+_NetworkType+'|'+_ModemIp;
		
		selectInt(intInfo);
	}
}

function updateLinkInfo() {
	//탑메뉴 호버 클릭 이벤트 변화..
	upTab01Id = false;
	upTab02Id = false;
	upTab03Id = true;
	upTab04Id = false;
	
	if(signalALineArr.length > 0 || signalBLineArr.length > 0)
	{
		emptySignalArr(signalALineArr);
		emptySignalArr(signalBLineArr);
		emptySignalArr(lineCenterCircleArr);
		emptySignalArr(linkLineArr);
		emptySignalArr(linkPhaseLineArr);
		emptySignalArr(_SubLinkLineArr);
		
		signalALineArr      = [];
		signalBLineArr      = [];
		lineCenterCircleArr = [];
		linkLineArr = [];
		linkPhaseLineArr = [];
		_SubLinkLineArr = [];
		
		getSignalInfo('addSignal');
	}
	//교차로관리 숨김
	$('.addSigDiv').hide();
	//업로드 숨김
	$('.uploadDiv').hide();
	//현시관리 숨김
	$('.phaseInfoCon').hide();
	//링크관리 표출
	$('.updatePhaseAdd').show();
	$('.updateMapNo').show();
	$('.linkInfoCon').show();
	
	$('#updateSigId').removeClass('on');
	$('#updatePhaseId').removeClass('on');
	$('#uploadId').removeClass('on');
	$('#updateLinkId').addClass('on');
	
	map.relayout();
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	if(addCircle != null) addCircle.mapCircle.setMap(null);
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	
	_CenterListId = 'linkInfo';
	_BackCircleFlag = true;
	
	if(_RegionCd.length > 0 && String(_IntNo).length > 0)
	{
		var intInfo = _RegionCd+'|'+_RegionNm+'|'+_IntNo+'|'+_IntNm+'|'+_XCoord+'|'+_YCoord+'|'+
		              _GroupNo+'|'+_MainIntNo+'|'+_SigunguCd+'|'+_IntLcType+'|'+_IntLampType+'|'+
		              _IntMainphase+'|'+_NetworkType+'|'+_ModemIp;
		selectInt(intInfo);
	}
}

//업로드...
function intPhaseUpload() {
	//탑메뉴 호버 클릭 이벤트 변화..
	upTab01Id = false;
	upTab02Id = false;
	upTab03Id = false;
	upTab04Id = true;
	
	emptySignalArr(linkLineArr);
	emptySignalArr(linkPhaseLineArr);
	emptySignalArr(_SubLinkLineArr);
	
	linkLineArr      = [];
	linkPhaseLineArr = [];
	_SubLinkLineArr  = [];
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	if(addCircle != null) addCircle.mapCircle.setMap(null);
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	
	_CenterListId = 'fileUpload';
	_BackCircleFlag = true;
	
	$('.addSigBottom h4').hide();
	//교차로관리 숨김
	$('.addSigDiv').hide();
	//업로드 숨김
	$('.uploadDiv').show();
	//현시관리 숨김
	$('.updatePhaseAdd').hide();

	$('#updateSigId').removeClass('on');
	$('#updateLinkId').removeClass('on');
	$('#updatePhaseId').removeClass('on');
	$('#uploadId').addClass('on');
	
	getDownloadIntNo($('#downloadRegionCd').val());
	
}

function intInfoUploadFnc() {
	
	var excelFile = $('#intInfoUpload').val();
	var checkType = checkFileType(excelFile);
	
	if(checkType)
	{
		$('#intInfoFileType').val(excelFile.split('.')[1]);
		var formData = new FormData($("#uploadForm")[0]);
		
	    $.ajax({
	        type : 'post',
	        url : 'intInfoUpload.do',
	        data : formData,
	        processData : false,
	        contentType : false,
	        beforeSend: function(){
	            $('.dataLoading').show();
	        },
	        complete: function(){
	            $('.dataLoading').hide();
	        },
	        success : function(data) {
	            if(data == 1) alert('열의 갯수(10개)가 맞지 않습니다.');
	            else 
	            {
	            	//서울 인경우 시군구코드를 업데이트 해준다..
	            	if($('#uploadRegionCd').val() == 'L01') updateSigunguFnc();
	            	alert("파일 업로드하였습니다.");
	            }
	            $('.dataLoading').hide();
	        },
	        error : function(error) {
	            alert("파일 업로드에 실패하였습니다.");
	            $('.dataLoading').hide();
	        }
	    });
	}
}

function phaseInfoUploadFnc() {
	
	var excelFile = $('#phaseInfoUpload').val();
	var checkType = checkFileType(excelFile);
	
	if(checkType)
	{
		$('#phaseInfoFileType').val(excelFile.split('.')[1]);
		var formData = new FormData($("#uploadForm")[0]);
		$('.dataLoading').show();
	    $.ajax({
	        type : 'post',
	        url : 'phaseInfoUpload.do',
	        data : formData,
	        processData : false,
	        contentType : false,
	        beforeSend: function(){
	            $('.dataLoading').show();
	        },
	        complete: function(){
	            $('.dataLoading').hide();
	        },
	        success : function(data) {
	        	if(data == 1) alert('열의 갯수(115개)가 맞지 않습니다.');
	            else alert("파일 업로드하였습니다.");
	        	
	        	$('.dataLoading').hide();
	        },
	        error : function(error) {
	            alert("파일 업로드에 실패하였습니다.");
	            $('.dataLoading').hide();
	        }
	    });
	}
}

function checkFileType(fileType) {
	var fileFormat = fileType.split(".")[1];
	if(fileFormat.indexOf("xls") > -1 || fileFormat.indexOf("xlsx") > -1)
	{
		return fileFormat;
	}
	else
	{
		alert('엑셀파일이 아닙니다.\nxls 또는 xlsx 파일을 선택해주세요.');
		return false;
	}
}

//탑메뉴 호버 클릭 이벤트 변화..
function selectTopMenu(id) {
	upTab01Id = false;
	upTab02Id = false;
	upTab03Id = false;
	upTab04Id = false;
	return id = true;
}

function disabledFnc(val) {
	if(val == 0)
	{
		$('#addModemIp').val('-');
		$('#addModemIp').attr('disabled',true);
	}
	else $('#addModemIp').attr('disabled',false);
}

function selectInt(val) {
	
	if(val == '')
	{
		initUpdateSignal('int');
		return;
	}
	
	$('.addSigContainer h4').hide();
	$('.table_cover').hide();
	$('.table_type3').css('opacity','1');
	$('.addsig_bottom_btns').css('opacity','1');
	
	emptySignalArr(lineCenterCircleArr);
	lineCenterCircleArr = [];
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	
	_PFlag = 'U';
	var valArr    = val.split('|');
	_RegionCd     = valArr[0];
	_RegionNm     = valArr[1];
	_IntNo        = valArr[2];
	_IntNm        = valArr[3];
	_XCoord       = valArr[4];
	_YCoord       = valArr[5];
	_GroupNo      = valArr[6];
	_MainIntNo    = valArr[7];
	_SigunguCd    = valArr[8];
	_IntLctype    = valArr[9];
	_IntLampType  = valArr[10];
	_IntMainphase = valArr[11];
	_NetworkType  = valArr[12];
	_ModemIp      = valArr[13];
	
	var regionGuCd = _RegionCd + ',' + _SigunguCd;
	
	if(_CenterListId == 'centerInfo')
	{
		if(_RegionCd.length > 0 && String(_IntNo).length > 0)
		{
			//시군구리스트 입력..
			getSigungu(_RegionCd);
			
			$('#addIntNo').val(_IntNo);
			$('#addMainIntNo').val(_MainIntNo);
			$('#addIntNm').val(_IntNm);
			$('#addGrpNo').val(_GroupNo);
			$('#addXCoord').val(_XCoord);
			$('#addYCoord').val(_YCoord);
			$('#addIntLcType').val(_IntLctype);
			$('#addIntLampType').val(_IntLampType);
			$('#addIntMainphase').val(_IntMainphase);
			$('#addNetworkType').val(_NetworkType);
			$('#addModemIp').val(_ModemIp);
			
			disabledFnc(_NetworkType);
			//교차로관리 지역센터 시군구 리스트 가저오기..
			$("#addSigunguCd").val(_SigunguCd).prop("selected", true);
			$('.addsig_bottom_btns').show();
			drawCenterMarker();
		}
	}
	else if(_CenterListId == 'phaseInfo')
	{
		_RingPhaseVal = 0;
		_UpadtePhaseLinkFlag = false;
		$('.updatePhaseDiv').empty().html('<span style="display:block;padding:10px">하단의 편집할 현시를 선택해 주세요.</span>');
		getMapNo();
		getSigInfoPhaseDetail();
	}
	else if(_CenterListId == 'linkInfo')
	{
		_RingPhaseVal = 0;
		var linkCode = null;
		
		getMapNo();
		
		if(_SigunguCd != 'undefined')
		{
			_UpadtePhaseLinkFlag = true;
			$('.updatePhaseDiv').empty().html('<span style="display:block;padding:10px">하단의 편집할 현시를 선택해 주세요.</span>');
		}
		else
		{
			linkCode = '0';
			alert('시군구코드가 없습니다.');
			return;
		}
		//초기 링크 데이터를 불러온다.
		getLinkVtx(_SigunguCd);
		getSigInfoPhaseDetail();
	}
	else if(_CenterListId == 'fileUpload') 
	{
		
	}
	
	map.setCenter(new kakao.maps.LatLng(_YCoord, _XCoord));
	if(map.getLevel() == 1) mapZoomBound();
	else map.setLevel(1);
}

function drawCenterMarker() {
	var startSrc = '/images/centerMarker.png', // 출발 마커이미지의 주소입니다
    startSize = new kakao.maps.Size(20, 20), // 출발 마커이미지의 크기입니다 
    startOption = { 
        offset: new kakao.maps.Point(10, 10) // 출발 마커이미지에서 마커의 좌표에 일치시킬 좌표를 설정합니다 (기본값은 이미지의 가운데 아래입니다)
    };
	
	// 출발 마커의 드래그 이미지를 생성합니다
	var startImage = new kakao.maps.MarkerImage(startSrc, startSize, startOption);

	// 출발 마커가 표시될 위치입니다 
	var startPosition = new kakao.maps.LatLng(_YCoord, _XCoord); 

	// 출발 마커를 생성합니다
    _CenterMarker = new kakao.maps.Marker({
	    map: map, // 출발 마커가 지도 위에 표시되도록 설정합니다
	    position: startPosition,
	    draggable: true, // 출발 마커가 드래그 가능하도록 설정합니다
	    image: startImage, // 출발 마커이미지를 설정합니다
	    zIndex: 100
	});
	
	// 출발 마커에 dragstart 이벤트를 등록합니다
	kakao.maps.event.addListener(_CenterMarker, 'dragstart', function() {
		_CenterMarker.setImage(startImage);
	});

	// 출발 마커에 dragend 이벤트를 등록합니다
	kakao.maps.event.addListener(_CenterMarker, 'dragend', function() {
		var lng = _CenterMarker.getPosition().getLng().toString();
		var lat = _CenterMarker.getPosition().getLat().toString();
		lng = lng.substring(0,10);
		lat = lat.substring(0,9);
		
		$('#addXCoord').val(lng);
		$('#addYCoord').val(lat);
		
		_YCoord = lat;
		_XCoord = lng;
	});
}

function getMapNo() {
	//이전 현시 흔적 삭제..
	phaseBackMap = new HashMap();
	emptyLastPhase();
	
	var str = '';
	for(var ii = 0; ii < 6; ii++)
	{
		var selectMapNo = '';
		if(_MapNo == ii) selectMapNo = 'selected="selected"';
		str += '<option value="'+ii+'" '+selectMapNo+'>'+ii+'</option>';
	}
	$('#updateMapNo').empty().html(str);
}

function getSigungu(regionCd) {
	var url = 'getSigunguList.do';
	var param = 'regionCd='+regionCd;
	requestService(url, param, getSigunguCallback);
}

function getSigunguCallback(data) {
	if(data.length > 0)
	{
		var option = '';
		var guSelFlag;
		option += '<option value="">선택</option>';
		for(var ii = 0; ii < data.length; ii++)
		{
			option += '<option value='+data[ii].SIGUNGU_CD+'>'+data[ii].SIGUNGU_NM+'</option>';
		}
		$('#addSigunguCd').empty().html(option);
	}
	else
	{
		$('#addSigunguCd option').remove();
	}
	$('#addSigunguCd').val(_SigunguCd).prop("selected", true);
}

function addSigdata() {
	_AddSigdataFlag = true;
	$('#sigMoveHead').empty().html('&#8251;아래 필수정보를 입력하시고 제어기위치를 지도에서 클릭하세요.');
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	
	$('#addRegionCd').val('');
	$('#addIntNo').val('');
	$('#addMainIntNo').val('');
	$('#addIntNm').val('');
	$('#addGrpNo').val('');
	$('#addXCoord').val('');
	$('#addYCoord').val('');
	
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	
    addClickListener = function(e) {
		if(addCircle != null) addCircle.mapCircle.setMap(null);
		var latLng = String(e.latLng);
		var coord = (latLng.replace('(','').replace(')','')).split(',');
		var xCoord = coord[1].trim().substr(0,10);
		var yCoord = coord[0].trim().substr(0,9);
		
		$('#addXCoord').val(xCoord);
		$('#addYCoord').val(yCoord);
		
		addCircle = new Signal(yCoord, xCoord, '', '');
	}
    
    _BackCircleFlag = true;
    map.relayout();
	kakao.maps.event.addListener(map, 'click', addClickListener);
	kakao.maps.event.addListener(map, 'rightclick', function(e) {
		addCircle.mapCircle.setMap(null);
	});
}

function updateSigdata() {
	_AddSigdataFlag = false;
	$('#sigMoveHead').empty().html('&#8251;아래 필수정보를 입력하시고 제어기위치(노란색마커)를 지도에서 조정하세요.');
	
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	if(addClickListener != null) kakao.maps.event.removeListener(map, 'click', addClickListener);
	if(addCircle != null) addCircle.mapCircle.setMap(null);
	
	if(_RegionCd.length > 0 && String(_IntNo).length > 0) 
	{
		drawCenterMarker();
		$('#addIntNo').val(_IntNo);
		$('#addMainIntNo').val(_MainIntNo);
		$('#addIntNm').val(_IntNm);
		$('#addGrpNo').val(_GroupNo);
		$('#addXCoord').val(_XCoord);
		$('#addYCoord').val(_YCoord);
	}
}

function deleteSigdata() {
	var regionGuCd = $('#addRegionCd option:selected').val();
	var regionGuCdArr =regionGuCd.split(',');
	var regionCd = regionGuCdArr[0];
	var intNo = $('#addIntNo').val();
	var mainIntNo = $('#addMainIntNo').val();
	
	if(intNo == '') {
		alert('교차로번호를 입력해 주세요.');
		$('#addIntNo').focus();
		return;
	}
	
	if(confirm('삭제하시겠습니까?') == true)
	{
		var url = 'deleteSigInfo.do';
		var param = 'regionCd='+regionCd+
		            '&intNo='+intNo+
		            '&mainIntNo='+mainIntNo;
		
		requestService(url, param, deleteSigInfoCallback);
	}
}

function deleteSigInfoCallback(data) {
	alert('삭제되었습니다.');
	if(_CenterMarker != null) _CenterMarker.setMap(null);
	mapZoomBound();
}

function saveSigdata() {
	var regionGuCd = $('#addRegionCd option:selected').val();
	var regionGuCdArr =regionGuCd.split(',');
	
	_RegionCd    = regionGuCdArr[0];
	_IntNo       = $('#addIntNo').val();
	_IntNm       = $('#addIntNm').val();
	_IntType     = 0;
	_IntLcType   = $('#addIntLcType').val();
	_IntLampType = $('#addIntLampType').val();
	_MainIntNo   = $('#addMainIntNo').val();
	_GroupNo     = $('#addGrpNo').val();
	_XCoord      = $('#addXCoord').val();
	_YCoord      = $('#addYCoord').val();
	_SigunguCd   = $('#addSigunguCd').val();
	_IntMainphase= $('#addIntMainphase').val();
	_NetworkType = $('#addNetworkType').val();
	_ModemIp     = $('#addModemIp').val();
	
	if(_RegionCd == '') {
		alert('지역코드를 입력해 주세요.');
		$('#addRegionCd').focus();
		return;
	}
	if(_IntNo == '') {
		alert('교차로번호를 입력해 주세요.');
		$('#addIntNo').focus();
		return;
	}
	if(_SigunguCd == '') {
		alert('시군구를 선택해 주세요.');
		$('#addSigunguCd').focus();
		return;
	}
	if(_MainIntNo == '') {
		alert('연등 메인제어기번호를 입력해 주세요.');
		$('#addMainIntNo').focus();
		return;
	}
	if(_IntNm == '') {
		alert('제어기명을 입력해 주세요.');
		$('#addIntNm').focus();
		return;
	}
	if(_XCoord == '') {
		alert('X좌표를 입력해 주세요.');
		$('#addXCoord').focus();
		return;
	}
	if(_YCoord == '') {
		alert('Y좌표를 입력해 주세요.');
		$('#addYCoord').focus();
		return;
	}
	
	if(_MainIntNo != 0) _IntType = 1;
	
	var urlStr = '';
	if(_AddSigdataFlag == true) //기초정보 추가
	{
		checkAddFnc(_RegionCd,_IntNo);
		urlStr = 'saveAddInt.do';
	}
	else ////기초정보 변경
	{
		urlStr = 'updateAddInt.do';
	}
	
	setTimeout(function(){
		url   = urlStr;
		var param = 'regionCd='+_RegionCd+
		            '&intNo='+_IntNo+
		            '&intNm='+_IntNm+
		            '&intType='+_IntType+
		            '&intLcType='+_IntLcType+
		            '&intLampType='+_IntLampType+
		            '&mainIntNo='+_MainIntNo+
					'&grpNo='+_GroupNo+
		            '&xCoord='+_XCoord.replace('.','')+
					'&yCoord='+_YCoord.replace('.','')+
					'&sigunguCd='+_SigunguCd+
					'&intMainphase='+_IntMainphase+
					'&intNetworkType='+_NetworkType+
					'&intModemIp='+_ModemIp;
		requestService(url, param, saveSigdataCallback);
	},100*5);
	
}

function saveSigdataCallback(data) {
	alert('저장 되었습니다.');
	getIntNo(_RegionCd,false);
	
	var intInfo = _RegionCd+'|'+_RegionNm+'|'+_IntNo+'|'+_IntNm+'|'+_XCoord+'|'+_YCoord+'|'+
    _GroupNo+'|'+_MainIntNo+'|'+_SigunguCd+'|'+_IntLcType+'|'+_IntLampType+'|'+
    _IntMainphase+'|'+_NetworkType+'|'+_ModemIp;
	
	//selectInt(intInfo);
	
	setTimeout(function() {
		$('#intList option:contains("'+_IntNm+'")').prop("selected", true);
		//mapZoomBound();
	},100,5);
	
}

function checkAddFnc(regionCd,intNo) {
	var url = 'checkAddSig.do';
	var param = 'regionCd='+regionCd+'&intNo='+intNo;
	requestService(url, param, checkAddSigCallback);
}

function checkAddSigCallback(data) {
	if(data == true)
	{
		alert('교차로번호 중복 입니다.\n교차로번호를 변경해주세요.');
		$('#addIntNo').focus();
		return;
	}
}

function updateSigunguFnc() {
	
	$.ajax({
        type : 'post',
        url : 'getIntNo.do',
        data : 'regionCd='+$('#uploadRegionCd').val(),
        beforeSend: function(){
            $('.dataLoading').show();
        },
        success : function(data) {
        	updateSigunguCallback(data);
        },
        error : function(error) {
            alert("시군구코드 업데이트에 실패하였습니다.");
        }
    });
}

function updateSigunguCallback(data) {
	var geocoder = new kakao.maps.services.Geocoder();
	var sigunguDataArr = [];
	var ii = 0;
	var dataSize = data.length;
	
	loopCallback();
	
	function loopCallback() {
		if(ii < dataSize) 
		{
			getSigunguCd();
		}
		else 
		{
			$('.dataLoading').hide();
			alert("파일을 업로드하였습니다.");
		}
		
		function getSigunguCd() {
			
			geocoder.coord2RegionCode(data[ii].X_COORD, data[ii].Y_COORD, callback);
			
			setTimeout(function() {
				ii++;
				loopCallback();
			}, 10 * 5);
		}
	}
	
	function callback(result, status) {
		if (status === kakao.maps.services.Status.OK) 
		{
			$.ajax({
		        type : 'post',
		        url : 'updateSigunguCd.do',
		        data : 'regionCd='+$('#uploadRegionCd').val()+
		               '&intNo='+data[ii].INT_NO+
		               '&sigunguCd='+result[0].code.substring(0,5),
		        success : function(data) {
		            //alert("시군구코드 업데이트를 하였습니다.");
		        },
		        error : function(error) {
		            alert("시군구코드 업데이트에 실패하였습니다.");
		        }
		    });
	    }
	}
}

$(window).bind("beforeunload", function (e) {
	opener.closeTopMenu('addSignal');
	
	if (opener.window.sessionStorage)
	{
        opener.sessionStorage.setItem('masterLng', _XCoord);
        opener.sessionStorage.setItem('masterLat', _YCoord);
    }
});

$(document).on('keydown mousedown', '#addXCoord', function() {});
$(document).on('keydown mousedown', '#addYCoord', function() {});

</script>

</body>
</html>
