<%@ 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"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

    <form:form commandName="useRequestVO" name="frm" method="POST" action="/map/updateReq" id="updateFrm">
        <input type="hidden" name="idx" value="${useRequestVO.idx}" />
        <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" />

            <c:choose>
                <c:when test="${useRequestVO.status eq '99' }">
                    <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" value="${useRequestVO.title}" /></td>
                            </tr>
                            <tr>
                                <th colspan="2">기간</th>
                                <td>
                                    <input type="text" class="form-control input-datepicker" id="startDate" name="s_date" onchange="dateChange('start');" readonly value="${useRequestVO.s_date}"> ~
                                    <input type="text" class="form-control input-datepicker" id="endDate" name="e_date" onchange="dateChange('end');" readonly value="${useRequestVO.e_date}">
                                </td>
                            </tr>
                            <tr>
                                <th colspan="2">장소</th>
                                <td id="area_select_td">
                                    <div>
                                        <select class="form-control input-area-select" id="city" name="city" onchange="changeAreaList(this.value, this.name)">
                                            <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 class="form-control input-area-select" id="county" name="county" onchange="changeAreaList(this.value, this.name);">
                                            <option value="0">::선택::</option>
                                        </select>
                                        <select class="form-control input-area-select" id="town" name="town">
                                            <option value="0">::선택::</option>
                                        </select>
                                        <span class="glyphicon glyphicon-plus point-cursor" onclick="addAreaBtn();"></span>
                                    </div>
                                    <div id="addedArea" class="addedArea">
                                        <c:forEach var="item" items="${selectArea}" varStatus="status">
                                            <span id="addedAreaWrap${status.index}" class="addedAreaWrap">
                                                <c:out value="${item.name}" />
                                                <span class="glyphicon glyphicon-remove point-cursor" onclick="removeAreaBtn(${status.index});"></span>
                                                <input type="hidden" name="selectArea" value="${item.code}" />
                                            </span>
                                        </c:forEach>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th style="width:7%;" rowspan="3">레이어</th>
                                <th><label>지하시설물</label></th>
                                <td>
                                    <c:forEach var="item" items="${layersVO}" varStatus="status">
                                        <c:if test="${item.code eq  'facility'}">
                                            <c:set var="faciltySize" value="${faciltySize+1}" />
                                            <label class="layer-label"><input type="checkbox" name="${item.code}" id="${item.code}" value="${item.layer}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                                <c:if test="${item.layer eq item2}">
                                                    checked
                                                </c:if>
                                    </c:forEach>
                                    />${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}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                                <c:if test="${item.layer eq item2}">
                                                    checked
                                                </c:if>
                                    </c:forEach>
                                    />${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}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                               <c:if test="${item.layer eq item2}">
                                                   checked
                                               </c:if>
                                   </c:forEach>
                                   />${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">${useRequestVO.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-danger" type="button" value="취소" onclick="deleteReqBtn(); return false;" />
                            <input class="btn btn-success" type="button" value="수정" onclick="updateReqBtn(); return false;" />
                        </p>
                    </div>
                </c:when>
                <c:otherwise>
                    <table class="detail_table">
                        <thead>
                            <tr>
                                <th colspan="4" style="text-align: center;">지도 사용 요청</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <th>작업명</th>
                                <td class="title-td">${useRequestVO.title}</td>
                                <th style="width:40px;">상태</th>
                                <td class="text-center" style="width:40px;">
                                    <c:if test="${useRequestVO.status ne '99' }">
                                        <c:choose>
                                            <c:when test="${useRequestVO.status eq '0' }"><span class="label label-success">
                                                    <c:out value='사용중' /></span></c:when>
                                            <c:otherwise><span class="label label-danger">
                                                    <c:out value='사용불가' /></span></c:otherwise>
                                        </c:choose>
                                    </c:if>
                                </td>
                            </tr>
                            <tr>
                                <th>기간</th>
                                <td colspan="3">${useRequestVO.s_date} ~ ${useRequestVO.e_date}</td>
                            </tr>
                            <tr>
                                <th>장소</td>
                                <td colspan="3">
                                    <c:forEach var="item" items="${selectArea}" varStatus="status">
                                        <div id="addedBlock${status.index}">
                                            ${item.name}
                                        </div>
                                    </c:forEach>
                                </td>
                            </tr>
                            <tr>
                                <th rowspan="3">레이어</th>
                                <td colspan="3">
                                    <label>지하시설물</label>
                                    <div class="setting_content2" class="facility">
                                        <c:forEach var="item" items="${layersVO}" varStatus="status">
                                            <c:if test="${item.code eq  'facility'}">
                                                <c:set var="faciltySize" value="${faciltySize+1}" />
                                                <label>
                                                    <input type="checkbox" name="${item.code}" id="${item.code}" disabled="disabled" value="${item.layer}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                                    <c:if test="${item.layer eq item2}">
                                                        checked
                                                    </c:if>
                                        </c:forEach>
                                        />${item.name}
                                        </label>
                                        </c:if>
                                        </c:forEach>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3">
                                    <label>지하구조물</label>
                                    <div class="setting_content2" class="structure">
                                        <c:forEach var="item" items="${layersVO}" varStatus="status">
                                            <c:if test="${item.code eq  'structure'}">
                                                <label><input type="checkbox" name="${item.code}" id="${item.code}" disabled="disabled" value="${item.layer}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                                    <c:if test="${item.layer eq item2}">
                                                        checked
                                                    </c:if>
                                        </c:forEach>
                                        />${item.name}</label>
                                        </c:if>
                                        </c:forEach>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3">
                                    <label>지반</label>
                                    <div class="setting_content2" class="ground">
                                        <c:forEach var="item" items="${layersVO}" varStatus="status">
                                            <c:if test="${item.code eq  'ground'}">
                                                <label><input type="checkbox" name="${item.code}" id="${item.code}" disabled="disabled" value="${item.layer}" <c:forEach var="item2" items="${layers}" varStatus="status2">
                                                    <c:if test="${item.layer eq item2}">
                                                        checked
                                                    </c:if>
                                        </c:forEach>
                                        />${item.name}</label>
                                        </c:if>
                                        </c:forEach>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th>요청 내용</th>
                                <td colspan="3">${useRequestVO.user_msg}</td>
                            </tr>
                            <tr>
                                <th>전달 메세지</th>
                                <td colspan="3">${useRequestVO.admin_msg}</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>
                    </div>
                </c:otherwise>
            </c:choose>
        </div>
    </form:form>
	
	<script type="text/javascript">
		var areaAddCount = ${selectArea.size()};
		/*
		* 지역 추가
		*/
		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('더 이상 추가 하실 수 없습니다.');
			}
		}
		
		/*
		* 지역 삭제
		* 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);
			}
		}
			
		/*
		* 지역 변경
		*/
		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>");
								}
							}
						}
					}
				});
			}
		}
		
		/*
		* 날짜 변경
		* 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 updateReqBtn(){	
			
			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{
				$("#updateFrm").submit();
			} 
		}
		
		function deleteReqBtn(){
			if(confirm('지도사용요청을 취소하시겠습니까?')){
				$("#updateFrm").attr("action", "/map/deleteReq");
				$("#updateFrm").submit();
			}
		}
		
		$(function(){ 
			$("#startDate").datepicker({
				dateFormat: 'yy-mm-dd',
	        	prevText: '이전 달',
	        	nextText: '다음 달',
	        	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: ['일', '월', '화', '수', '목', '금', '토'],
	        	showMonthAfterYear: true,
	        	yearSuffix: '년'
		   });
			
			$("#endDate").datepicker({
				dateFormat: 'yy-mm-dd',
	        	prevText: '이전 달',
	        	nextText: '다음 달',
	        	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: ['일', '월', '화', '수', '목', '금', '토'],
	        	showMonthAfterYear: true,
	        	yearSuffix: '년'
		   });
			
			$("input[name=facility]").each(function(){
				if(this.checked){
					$("#facility_all").prop("checked", true);
				}else{
					$("#facility_all").prop("checked", false);
					return false;
				}
			});
			
			$("input[name=structure]").each(function(){
				if(this.checked){
					$("#structure_all").prop("checked", true);
				}else{
					$("#structure_all").prop("checked", false);
					return false;
				}
			});
			
			$("input[name=ground]").each(function(){
				if(this.checked){
					$("#ground_all").prop("checked", true);
				}else{
					$("#ground_all").prop("checked", false);
					return false;
				}
			});
			
			//전체선택 체크박스 클릭 
			$("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>