<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

	<form:form commandName="useRequestVO" name="frm" method="POST" action="/map/insertReq" id="insertFrm">
	<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
		<div class="section_title">
			<!-- <p>현장 지원 시스템</p> -->
		</div>
		<div class="section_content">
			<input type="hidden" id="layers" name="layers"/>
			<input type="hidden" id="places" name="places"/>
			
			<table class="detail_table">
				<thead>
					<tr><th colspan="5" style="text-align: center;">지도 사용 요청</th></tr>
				</thead>
				<tbody>
					<tr>
						<th colspan="2">작업명</th>
						<td><input type="text" class="form-control" id="title" name="title" autocomplete="off"/></td>
					</tr>
					<tr>
						<th colspan="2">기간</th>
						<td>
							<input type="text" class="form-control input-datepicker" readonly id="startDate" name= "s_date" onchange="dateChange('start');">  ~ 
							<input type="text" class="form-control input-datepicker" readonly id="endDate" name="e_date" onchange="dateChange('end');">
						</td>
					</tr>
					<tr>
						<th colspan="2">장소</th>
						<td id="area_select_td">
							<div>
								<select id="city" name="city" onchange="changeAreaList(this.value, this.name)" class="form-control input-area-select">
									<option value="0">::시/도::</option>
									<c:forEach var="item" items="${cityList}" varStatus="status">
										<option value="${item.code}"><c:out value="${item.area}"/></option>
									</c:forEach>
								</select>
								<select id="county" name="county" onchange="changeAreaList(this.value, this.name);" class="form-control input-area-select">
									<option value="0">::선택::</option>
								</select>
								<select id="town" name="town" class="form-control input-area-select">
									<option value="0">::선택::</option>
								</select>
								<span class="btn btn-outline-primary" onclick="addAreaBtn();">추가</span>
							</div>
							<div id="addedArea" class="addedArea">
							</div>
						</td>
					</tr>
					<tr>
						<th rowspan="3">레이어</th>
						<th><label>지하시설물</label></th>
						<td>
			        		<c:forEach var="item" items="${layersVO}" varStatus="status">
			        			<c:if test="${item.code eq  'facility'}">
			        				<label class="layer-label"><input type="checkbox" name="${item.code}" id="${item.code}" value="${item.layer}"/> ${item.name} </label>
			        			</c:if>
							</c:forEach>
						</td>
					</tr>
					<tr>
						<th><label>지하구조물</label></th>
						<td>
				            <c:forEach var="item" items="${layersVO}" varStatus="status">
			        			<c:if test="${item.code eq  'structure'}">
			        				<label class="layer-label"><input type="checkbox" name="${item.code}" id="${item.code}" value="${item.layer}"/> ${item.name} </label>
			        			</c:if>
							</c:forEach>
						</td>
					</tr>
					<tr>
						<th><label>지반</label></th>
						<td>
				            <c:forEach var="item" items="${layersVO}" varStatus="status">
			        			<c:if test="${item.code eq  'ground'}">
			        				<label class="layer-label"><input type="checkbox" name="${item.code}" id="${item.code}" value="${item.layer}"/> ${item.name} </label>
			        			</c:if>
							</c:forEach>
						</td>
					</tr>
					<tr>
						<th colspan="2">요청 내용</th>
						<td><textarea class="form-control" rows="3" style="resize:none;" name=user_msg></textarea></td>
					</tr>
				</tbody>
			</table>
			<div class="section_btn">
				<p class="search_p1">
					<input class="btn btn-primary" type="button" value="목록" onclick="location.href='/map/request'" />
				</p>
				<p class="search_p2">
					<input class="btn btn-success" type="button" value="요청" onclick="insertReqBtn(); return false;" />
				</p>
			</div>
		</div>
	</form:form>
	
	<script type="text/javascript">
		var areaAddCount = 0;
		/*
		* 지역 추가
		*/
		function addAreaBtn(){
			var addedAreaWrapCnt = $(".addedAreaWrap").length;
			
			if(addedAreaWrapCnt < 3){
				if($("#city").val() != "0"){
					areaAddCount++;
					var selectAreaCode = null;
					var selectAreaName = null;
					if($("#town").val() == "0"){
						selectArea = $("#county").val();
						selectAreaName = $("#city option:selected").text() +" "+ $("#county option:selected").text();
						if($("#county").val() == "0"){
							selectArea = $("#city").val();	
							selectAreaName = $("#city option:selected").text();
						}
					}else{
						selectArea = $("#town").val();	
						selectAreaName = $("#city option:selected").text()+" "+$("#county option:selected").text()+" "+$("#town option:selected").text();
					}
					var  overLapArea = false;
					$("input[name=selectArea]").each(function(){
						if($(this).val() == selectArea){
							overLapArea = true;
						}
					});
					if(overLapArea){
						alert('이미 등록된 장소 입니다.');
						return false;
					}else{
						var tag = '';
						tag += '<span id="addedAreaWrap'+areaAddCount+'" class="addedAreaWrap">';
						tag += selectAreaName;
						tag += '<span class="glyphicon glyphicon-remove point-cursor" onclick="removeAreaBtn('+areaAddCount+');"></span>';
						tag += '<input type="hidden" name="selectArea" value="'+selectArea+'" />';
						tag += '</span>';
						$("#addedArea").append(tag);
					}
				}else{
					alert('지역을 선택해주세요.');
				}
			}else{
				alert('더 이상 추가 하실 수 없습니다.');
			}
		}
		
		/*
		* 지역 변경
		*/
		function changeAreaList(code, area){
			var target = null
			if(area == "city"){
				target = $("#county");
			}else{
				target = $("#town");
			}
			resetSelectBox(area);
			if(code != 0){
				$.ajax({
					url : "<c:url value='/selectAreaList' />",
					type : "GET",
					dataType : "json",
					data:{
						"code" : code,
						"area" : area
					},
					success : function(data){
						if(data){
							if(area == "city"){
								for(var idx in data){
									target.append("<option value='"+data[idx].code+"'>"+data[idx].area+"</option>");
								}	
							}else{
								for(var idx in data){
									target.append("<option value='"+data[idx].code+"'>"+data[idx].area+"</option>");
								}
							}
						}
					}
				});
			}
		}
		
		/*
		* 지역 삭제
		* removeNum : 삭제할 태그 번호
		*/
		function removeAreaBtn(removeNum){
			$("#addedAreaWrap"+removeNum).remove();
		}
	
		function resetSelectBox(area){
			var baseOption = "<option value='0'>::전체::</option>";
			if(area == "county"){
				$("#town").empty();
				$("#town").append(baseOption);
			}else if(area == "city"){
				$("#county").empty();
				$("#town").empty();
				$("#county").append(baseOption);
				$("#town").append(baseOption);
			}
		}
		
		/*
		* 날짜 변경
		* state : 시작 또는 종료 
		*/
		function dateChange(state){
			var startDate = $("#startDate").val();
			var endDate = $("#endDate").val();
			if(endDate != "" && startDate > endDate){
				if(state == "start"){
					$("#endDate").val(startDate);	
				}else{
					$("#startDate").val(endDate);	
				}
			}
		}
		
		/*
		*	지역 유효성 검사
		*/
		function areaCheck(){
			var selectArr = [];
			$("input[name=selectArea]").each(function(){
				selectArr.push($(this).val());
			});
			$("#places").val(selectArr);
			
			if($("#places").val() == ""){
				return false;
			}else{
				return true;
			}
		}
		
		/*
		*	레이어 유효성 검사
		*/
		function layersCheck(){
			var checkArr = [];     // 배열 초기화
			$('input:checkbox[name="facility"]:checked').each(function(index, item) {
				checkArr.push($(item).val());
			});
			$('input:checkbox[name="structure"]:checked').each(function(index, item) {
				checkArr.push($(item).val()); 
			});
			$('input:checkbox[name="ground"]:checked').each(function(index, item) {
				checkArr.push($(item).val()); 
			});
			
		    $('#layers').val(checkArr);
		    
		    if($('#layers').val() == ""){
		    	return false;
		    }else{
		    	return true;
		    }
		}
		
		function insertReqBtn(){	
			if($("#title").val() == ""){
				alert('작업명을 입력해주세요.');
				$("#title").focus();
				return;
			}else if($("#startDate").val() == ""){
				alert('시작 기간을 입력해주세요.');
				$("#startDate").focus();
				return;
			}else if($("#endDate").val() == ""){
				alert('종료 기간을 입력해주세요.');
				$("#endDate").focus();
				return;
			}else if(!areaCheck()){
				alert('지역을 추가해주세요.');
				return;
			}else if(!layersCheck()){
				alert('레이어를 선택해주세요.');
				return;
			}else{
				$("#insertFrm").submit();
			} 
		}
		
		$(function(){ 
			$("#startDate").datepicker({
				dateFormat: 'yy-mm-dd',
	        	monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	        	monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	        	dayNames: ['일', '월', '화', '수', '목', '금', '토'],
	        	dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
	        	dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
	        	yearSuffix: '년',
	        	showMonthAfterYear:true,
				changeYear : true,
	        	changeMonth : true
		   });
			
			$("#endDate").datepicker({
				dateFormat: 'yy-mm-dd',
	        	monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	        	monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	        	dayNames: ['일', '월', '화', '수', '목', '금', '토'],
	        	dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
	        	dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
	        	yearSuffix: '년',
	        	showMonthAfterYear:true,
				changeYear : true,
	        	changeMonth : true
		   });
			
			//전체선택 체크박스 클릭 
			$("input[type=checkbox]").click(function() {
				var id = this.id;
				
				if(id.indexOf("facility") != -1){
					if(id == "facility_all"){
						if($("#facility_all").prop("checked")) { 
							$("input[name=facility]").prop("checked", true); 
						} else { 
							$("input[name=facility]").prop("checked", false); 
						}	
					}else{
						$("#facility_all").prop("checked", false);
						if($(this).prop("checked")) { 
							$(this).prop("checked", true);
						}else{
							$(this).prop("checked", false);	
						}
					}
				}else if(id.indexOf("structure") != -1){
					if(id == "structure_all"){
						if($("#structure_all").prop("checked")) { 
							$("input[name=structure]").prop("checked", true); 
						} else { 
							$("input[name=structure]").prop("checked", false); 
						}	
					}else{
						$("#structure_all").prop("checked", false); 
						
						if($(this).prop("checked")) { 
							$(this).prop("checked", true);
						}else{
							$(this).prop("checked", false);	
						}
					}
				}else if(id.indexOf("ground") != -1){
					if(id == "ground_all"){
						if($("#ground_all").prop("checked")) { 
							$("input[name=ground]").prop("checked", true); 
						} else { 
							$("input[name=ground]").prop("checked", false); 
						}	
					}else{
						$("#ground_all").prop("checked", false); 
						if($(this).prop("checked")) { 
							$(this).prop("checked", true);
						}else{
							$(this).prop("checked", false);	
						}
					}
				}
			});
		});

	</script>
