let mapRequestModal;

$(function(){
  viewPaging();
  $(".r_date").each(function(){
    var r_date = $(this).text();
    var nowDate = new Date();
    var r_date = new Date(r_date);
    var getDay = 	getFormatDate(r_date);
    var nowDay = getFormatDate(nowDate);

    if(getDay === nowDay){
      $(this).html(getFormatTime(r_date));
    }else{
      $(this).html(getDay);
    }
  });
  mapRequestModal = new bootstrap.Modal(document.getElementById('mapRequestModal'));
});

$(document).on('click', '#mapRequestModalBtn', function (){
  mapRequestModalOpen('/map/reqWrite');
})
$(document).on('click', '.title-td', function (){
  mapRequestModalOpen('/map/request/'+$(this).attr("data-idx"));
})
function mapRequestModalOpen(url){
  $.ajax({
    url: url,
    type: 'GET',
    dataType:"html",
    success: function(html){
      $("#mapRequestModalBody").empty().append(html);
      mapRequestModal.show();
    },
    error:function(){
      mapRequestModalBody
    }
  });
}
/* 날짜포맷 yyyy-MM-dd 변환 */
function getFormatDate(date){
  var year = date.getFullYear();
  var month = (1 + date.getMonth());
  month = month >= 10 ? month : '0' + month;
  var day = date.getDate();
  day = day >= 10 ? day : '0' + day;
  return year + '-' + month + '-' + day;
}

function getFormatTime(date){
  var hours = date.getHours();
  var minutes = date.getMinutes();
  return hours + ':' + minutes;
}

function viewPaging(){
  for (step = start; step < end; step++) {
    if(step == now){
      $("#paging").append("<strong>"+step+"</strong>");
    }else{
      $("#paging").append("<a href='userPermissionList.do?&page="+ step +"'>"+step+"</a>");
    }
  }
}

function fn_link_page(pageNo) {
  document.searchForm.pageIndex.value = pageNo;
  document.searchForm.action = '/map/request';
  document.searchForm.submit();
}

/*
		* 지역 추가
		*/
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 : '/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().append(baseOption);
  }else if(area === "city"){
    $("#county").empty().append(baseOption);
    $("#town").empty().append(baseOption);
  }
}

/*
* 날짜 변경
* state : 시작 또는 종료
*/
function dateChange(state){
  var startDate = $("#startDate");
  var endDate = $("#endDate");
  if(endDate.val() !== "" && startDate.val() > endDate.val()){
    if(state === "start"){
      endDate.val(startDate.val());
    }else{
      startDate.val(endDate.val());
    }
  }
}

/*
*	지역 유효성 검사
*/
function areaCheck(){
  var selectArr = [];
  $("input[name=selectArea]").each(function(){
    selectArr.push($(this).val());
  });
  const places = $("#places");
  places.val(selectArr);

  return places.val() !== "";
}

/*
*	레이어 유효성 검사
*/
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());
  });
  const layers = $('#layers');
  layers.val(checkArr);

  return layers.val() !== "";
}

function insertReqBtn(){
  const endDate = $("#endDate");
  const startDate = $("#startDate");
  const title = $("#title");
  if(title.val() === ""){
    alert('작업명을 입력해주세요.');
    title.focus();
  }else if(startDate.val() === ""){
    alert('시작 기간을 입력해주세요.');
    startDate.focus();
  }else if(endDate.val() === ""){
    alert('종료 기간을 입력해주세요.');
    endDate.focus();
  }else if(!areaCheck()){
    alert('지역을 추가해주세요.');
  }else if(!layersCheck()){
    alert('레이어를 선택해주세요.');
  }else{
    $("#insertFrm").submit();
  }
}

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