// DinoWorks Common Script 2023-09-12

window.addEventListener('load', function() {
  preventLinkDefault();
  setGNB();

  setCheckInput();      // 체크요소 마우스 사용시 포커스 제거
  formHelp();           // 입력폼 도움말
  setSelectBox();       // select 첫번째 선택시 컬러조정(비활성화)

  setDatePicker({
    container: '#wrapper',
    language: 'ko',
    readonly: true
  });
}, false);


// 링크처리 (# 튐 방지)
function preventLinkDefault() {
  document.addEventListener('click', function(e) {
    let lastNode = e.currentTarget;  // #document (html 요소)
    let currentNode = e.target;      // click 된 가장 하단의 요소
    // console.log('lastnode : ', lastNode, 'currentnode', currentNode);

    while (currentNode !== null && currentNode !== lastNode) {  // body 까지 올라가면 null로 반환
      // console.log('currentnode now : ', currentNode);
      if (currentNode.matches('a[href="#"]') === true) {
        e.preventDefault();
        break;
      }
      currentNode = currentNode.parentNode;
    }
  }, false);
}


// GNB (모바일용 / 접근성(키보드/포커스) 기능 추가)
function setGNB() {
  const btnMenu = document.querySelector('#header a.menu');
  const btnClose = document.querySelector('#gnb a.close');
  const gnb = document.querySelector('#gnb');

  if (gnb === null) return false;    // header-short 인 경우 GNB 없음

  btnMenu.addEventListener('click', function() {
    gnb.removeEventListener('transitionend', removeGNB);
    gnb.classList.add('show');
    setTimeout(() => {
      gnb.classList.add('open');
      btnClose.focus();
    }, 50);
  }, false);

  btnClose.addEventListener('click', function() {
    gnb.classList.remove('open');
    gnb.addEventListener('transitionend', removeGNB, {once: true});
    btnMenu.focus();
  }, false);

  gnb.addEventListener('focusout', function() {
    gnb.classList.remove('open');
    gnb.addEventListener('transitionend', removeGNB, {once: true});
  }, false);

  gnb.addEventListener('focusin', function() {
    gnb.removeEventListener('transitionend', removeGNB);
    gnb.classList.add('show');
    gnb.classList.add('open');
  }, false);

  function removeGNB() {
    gnb.classList.remove('show');
  }
}

// 메시지 팝업창
function displayPopup(options, returnBtn) {
  const type = (options !== undefined && options.type !== undefined) ? options.type : 'success';
  const title = (options !== undefined && options.title !== undefined) ? options.title : '제목없음';
  const content = (options !== undefined && options.content !== undefined) ? options.content : '내용없음';
  const btnTexts = (options !== undefined && options.buttons !== undefined) ? options.buttons : ['취소', '확인'];
  let templateButton = '';
  const template1 = `
    <div id="layer-mask"></div>
    <div class="layer-popup ${type}" tabindex="0">
      <p class="icon"><span></span></p>
      <p class="title">${title}</p>
      <p class="content">${content}</p>
      <p class="button"><a href="#" class="btn small blue-line close">닫기</a></p>
    </div>
  `;

  // 버튼 1개 / 2개
  if (btnTexts.length === 2) {
    templateButton = `<a href="#" class="btn small blue-line close">${btnTexts[0]}</a><a href="#" class="btn small blue close">${btnTexts[1]}</a>`;
  } else {
    templateButton = `<a href="#" class="btn small blue-line close">${btnTexts[0]}</a>`;
  }
  const template2 = `
    <div id="layer-mask"></div>
    <div class="layer-popup ${type}" tabindex="0">
      <p class="title">${title}</p>
      <p class="content">${content}</p>
      <p class="button">${templateButton}</p>
    </div>
  `;

  if (type === 'confirm') {
    document.querySelector('body').insertAdjacentHTML('beforeend', template2);
  } else {
    document.querySelector('body').insertAdjacentHTML('beforeend', template1);
  }
  document.querySelector('div.layer-popup').focus();

  document.querySelectorAll('div.layer-popup a.close').forEach(function(closeBtn) {
    closeBtn.addEventListener('click', closePopup, false);
  });
  document.querySelector('#layer-mask').addEventListener('click', closePopup, false);

  function closePopup() {
    const popup = document.querySelector('div.layer-popup');
    const mask = document.querySelector('#layer-mask');
    returnBtn.focus();
    popup.remove();
    mask.remove();
  }
}

// 레이어 팝업창 
function showLayerPopup(selector, returnBtn) {
  const popup = document.querySelector(selector);
  const closeBtns = popup.querySelectorAll('a.close');
  const mask = '<div id="layer-mask"></div>';

  popup.insertAdjacentHTML('beforebegin', mask);
  popup.classList.add('on');
  popup.setAttribute('tabindex', 0);
  popup.focus();

  closeBtns.forEach(function(closeBtn) {
    closeBtn.addEventListener('click', function() {
      closePopup();
    }, {once: true});
  });
  document.querySelector('#layer-mask').addEventListener('click', closePopup, false);

  function closePopup() {
    const popup = document.querySelector(selector);
    const mask = document.querySelector('#layer-mask');
    returnBtn.focus();
    popup.classList.remove('on');
    if (mask !== null) mask.remove();
  }
}

// header 단계 표시 UI
function setHeaderStage(digit) {
  const stage = Math.floor(digit);
  const portion = digit - stage;

  document.querySelectorAll('#header-stage ul > li').forEach(function(list, i) {
    if (i < stage) {
      list.classList.add('full');
      list.classList.add('on');
    } else if (i === stage && portion > 0) {
      list.classList.add('on');
      list.querySelector('span.bar span').style.width = (portion * 100) + '%';
    }
  });
}




// --------------------------------------
//     [Form 관련 기능]
// --------------------------------------

// input 요소 오류메세지 표시
function displayFormError(selector, message) {
  const form = document.querySelector(selector);
  const container = form.closest('div.form-box');

  if (form === null) {
    alert(`[${selector}] 요소가 존재하지 않습니다.`);
    return false;
  }
  if (container === null) {
    alert(`[${selector}] 부모요소 (div.form-box)가 존재하지 않습니다.`);
    return false;
  }

  container.classList.add('error');
  if (container.querySelector('span.message') !== null) container.querySelector('span.message').remove();
  container.insertAdjacentHTML('beforeend', `<span class="message">${message}</span>`)
}

// input 요소 오류메세지 제거
function resetFormError(selector) {
  const form = document.querySelector(selector);
  const container = form.closest('div.form-box');

  if (form === null) {
    alert(`[${selector}] 요소가 존재하지 않습니다.`);
    return false;
  }
  if (container === null) {
    alert(`[${selector}] 부모요소 (div.form-box)가 존재하지 않습니다.`);
    return false;
  }

  container.classList.remove('error');
  if (container.querySelector('span.message') !== null) container.querySelector('span.message').remove();
}

// 버튼 활성화
function enableButton(selector) {
  const btn = document.querySelector(selector);

  if (btn === null) {
    alert(`[${selector}] 버튼이 존재하지 않습니다.`);
    return false;
  }
  btn.classList.remove('disabled');
}

// 버튼 비활성화
function disableButton(selector) {
  const btn = document.querySelector(selector);

  if (btn === null) {
    alert(`[${selector}] 버튼이 존재하지 않습니다.`);
    return false;
  }
  btn.classList.add('disabled');
}

// 요소 숨기기 표시하기
function setFormVisibility(selector, typeOption) {
  const type = (typeOption === undefined) ? 'toggle' : typeOption;
  const formLists = document.querySelectorAll(selector);

  if (formLists !== null) {
    formLists.forEach(function(formList) {
      if (type === 'toggle') {
        formList.classList.toggle('hidden');
      } else if (type === 'show') {
        formList.classList.remove('hidden');
      } else if (type === 'hide') {
        formList.classList.add('hidden');
      }
    });
  }
}

// 체크요소 마우스 사용시 포커스 제거
function setCheckInput() {
  const checkInputLabels = document.querySelectorAll('input[type="radio"] + label, input[type="checkbox"] + label');
  checkInputLabels.forEach(function(checkInputLabel) {
    checkInputLabel.addEventListener('click', function() {
      this.previousElementSibling.classList.add('mousedown');
    });
    checkInputLabel.previousElementSibling.addEventListener('focusout', function() {
      this.classList.remove('mousedown');
    });
  });
}

// 입력폼 도움말 (공통적용)
function formHelp() {
  const helps = document.querySelectorAll('span.help');
  const helpBtns = document.querySelectorAll('span.help a');
  const helpLayer = document.querySelector('div.layer-help');
  const closeBtn  = (helpLayer !== null) ? helpLayer.querySelector('a.close') : null;
  let content = '';

  helpBtns.forEach(function(btn) {
    btn.addEventListener('click', function(e) {
      e.stopPropagation();
      e.preventDefault();
      if (btn.parentElement.classList.contains('on') === true) {
        closeHelp(btn);
      } else {
        openHelp(btn);
      }
    }, false);
  });

  document.addEventListener('click', function() {
    helps.forEach(function(help) {
      closeHelp(help.querySelector('a'));
      // help.classList.remove('on');
    }); 
  }, false);

  function openHelp(btn) {
    btn.parentElement.classList.add('on');

    // mobile용 동작
    /*
    content = btn.nextElementSibling.innerHTML;
    helpLayer.querySelector('div.content').innerHTML = content;
    helpLayer.classList.add('on');
    helpLayer.insertAdjacentHTML('beforebegin', '<div id="layer-mask" class="mobile"></div>');
    document.querySelector('#layer-mask').addEventListener('click', function() {
      closeBtn.click();
    }, false);
    */
  }

  function closeHelp(btn) {
    btn.parentElement.classList.remove('on');
    // if (document.querySelector('#layer-mask') !== null) document.querySelector('#layer-mask').remove();
    if ((helpLayer !== null)) helpLayer.classList.remove('on');
  }
}


// display 속성 변경 (none / block or inline-block)
function setVisibilityCheck() {
  const forms = document.querySelectorAll('[data-selector]');
  console.log('first : ', forms);
  forms.forEach(function(form) {
    const tagType = form.tagName.toLocaleLowerCase();
    let eventTag = null;
    const selector = form.getAttribute('data-selector');
    const targets = document.querySelectorAll(selector);

    // 이벤트 정의
    if (tagType === 'option') {
      eventTag = form.closest('select');
      eventTag.addEventListener('change', function() {
        checkVisibility();
      }, false);
    } else if (tagType === 'input') {
      eventTag = document.querySelectorAll(`[name=${form.getAttribute('name')}]`);
      eventTag.forEach(function(tag) {
        tag.addEventListener('change', function() {
          checkVisibility();
        });
      });
    }
  });

  hideAll();
  checkVisibility();

  function checkVisibility() {
    hideAll();
    forms.forEach(function(form) {
      const tagType = form.tagName.toLocaleLowerCase();
      const selector = form.getAttribute('data-selector');
      if ((tagType === 'option' && form.selected === true) || (tagType === 'input' && form.checked === true)) {
        document.querySelectorAll(selector).forEach(function(target) {
          target.classList.remove('hidden');
        });
      }
    });
    hideHiddenElement();  // 숨겨진 요소와 관련된 요소 정리 (선택정보 초기화)
  }

  function hideAll() {
    forms.forEach(function(form) {
      const selector = form.getAttribute('data-selector');
      document.querySelectorAll(selector).forEach(function(target) {
        target.classList.add('hidden');
      });
    });
  }

  function hideHiddenElement() {
    let forms =  document.querySelectorAll('.hidden [data-selector]');
    /*
    let forms = [];
    document.querySelectorAll('[data-selector]').forEach(function(form) {
      if (form.closest('.hidden') === null) forms.push(form);
    });
    console.log('checkvisibility(not hidden) : ', forms);
    */
    forms.forEach(function(form) {
      const tagType = form.tagName.toLocaleLowerCase();
      const selector = form.getAttribute('data-selector');
      if (tagType === 'option') {
        form.seleced = false;
      } else if (tagType === 'input') {
        form.checked = false;
      }
      document.querySelectorAll(selector).forEach(function(target) {
        target.classList.add('hidden');
      });
    });
  }

}



/*
function setVisibilityCheck() {
  const forms = document.querySelectorAll('[data-selector]');
  forms.forEach(function(form) {
    const tagType = form.tagName.toLocaleLowerCase();
    let eventTag = null;
    const selector = form.getAttribute('data-selector');
    const targets = document.querySelectorAll(selector);

    if (tagType === 'option') {
      eventTag = form.closest('select');
      setVisibilitySelect();
      eventTag.addEventListener('change', function() {
        setVisibilitySelect();
      }, false);
    } else if (tagType === 'input') {
      eventTag = document.querySelectorAll(`[name=${form.getAttribute('name')}]`);
      setVisibilityInput()
      eventTag.forEach(function(tag) {
        tag.addEventListener('change', function() {
          setVisibilityInput();
        });
      });
    }

    function setVisibilitySelect() {
      hideElements();
      eventTag.querySelectorAll('option').forEach(function(option) {
        if (option.selected === true && option === form) {
          showElements();
        }
      });
    }

    function setVisibilityInput() {
      hideElements();
      eventTag.forEach(function(input) {
        if (input.checked === true && input === form) {
          showElements();
        }
      });
    }

    function showElements() {
      const targets = document.querySelectorAll(selector);
      targets.forEach(function(target, i) {
        target.classList.remove('hidden');
      });
    }

    function hideElements() {
      const targets = document.querySelectorAll(selector);
      targets.forEach(function(target, i) {
        target.classList.add('hidden');
        target.querySelectorAll('[data-selector]').forEach(function(element) {
          const selector = element.getAttribute('data-selector');
          document.querySelectorAll(selector).forEach(function(elHidden) {
            elHidden.classList.add('hidden');
          });
        });

      });
    }
  });
}
*/


function setSelectBox() {
  const selectForms =  document.querySelectorAll('select');
  selectForms.forEach(function(select) {
    adjustColor(select);
    select.addEventListener('change', function() {
      adjustColor(select);
    }, false);
  });

  function adjustColor(node) {
    const firstOption = node.querySelector('option:first-child');
    if (firstOption.selected === true) {
      node.classList.add('not-selected');
    } else {
      node.classList.remove('not-selected');
    }
  }
}


// --------------------------------------
//     [Datepicker 관련 기능]
// --------------------------------------

function setDatePicker(options) {
  const container = (options !== undefined && options.container !== undefined) ? document.querySelector(options.container) : 'body';
  const inputs = container.querySelectorAll('input[date-format]');
  const language = (options !== undefined && options.language !== undefined) ? options.language : 'ko';
  const readonly = (options !== undefined && options.readonly !== undefined) ? options.readonly : false;
  const today = new Date();
  const now = today.toLocaleDateString().replaceAll(' ', '-').replaceAll('.', '') + ' 09:00';   // 2022-12-03 09:00

  const settings = {
    'lang': {'ko': localeKo},
    'year': {dateFormat: 'yyyy', view: 'years', timepicker: false, onlyTimepicker: false, autoClose: true, width: '70px', placeholder: '0000'},
    'month': {dateFormat: 'yyyy-MM', view: 'months', timepicker: false, onlyTimepicker: false, autoClose: true, width: '90px', placeholder: '0000-00'},
    'date': {dateFormat: 'yyyy-MM-dd', view: 'days', timepicker: false, onlyTimepicker: false, autoClose: true, width: '110px', placeholder: '0000-00-00'},
    'date-hour': {dateFormat: 'yyyy-MM-dd', timeFormat: 'HH:00', view: 'days', timepicker: true, onlyTimepicker: false, autoClose: false, width: '140px', placeholder: '0000-00-00 00:00'},
    'date-min': {dateFormat: 'yyyy-MM-dd', timeFormat: 'HH:mm', view: 'days', timepicker: true, onlyTimepicker: false, autoClose: false, width: '140px', placeholder: '0000-00-00 00:00'},
    'hour': {timeFormat: 'HH:00', view: 'days', timepicker: true, onlyTimepicker: true, autoClose: false, width: '6em', placeholder: '00:00'},
    'min': {timeFormat: 'HH:mm', view: 'days', timepicker: true, onlyTimepicker: true, autoClose: false, width: '6em', placeholder: '00:00'},
  };

  inputs.forEach(function(input, i) {
    const inputFormat = input.getAttribute('date-format');
    const container = input.closest('.dino-form-group');
    const btn = (container !== null) ? container.querySelector('a.btn') : 'null';
    if (container !== null && btn !== null) {
      btn.addEventListener('click', function() {
        // alert('date click')
        input.focus();
      }, false);
    }

    let minStep = input.getAttribute('min-step') ? input.getAttribute('min-step') : 1;
    if (inputFormat === 'date-hour' || inputFormat === 'hour') {
      minStep = 60;
    }
    if (readonly === true) {
      input.setAttribute('readonly', 'readonly');
    } else {
      input.removeAttribute('readonly');
    }
    // input.setAttribute('style', 'width: ' + settings[inputFormat].width);
    // input.setAttribute('placeholder', settings[inputFormat].placeholder);

    let button = {
      content: '오늘',
      className: 'today-button',
      onClick: (dp) => {
        let date = new Date();
        dp.selectDate(date);
        dp.setViewDate(date);
      }
    }

    new AirDatepicker(input, {
      // range: true,
      // buttons: ['today', 'clear'],
      buttons: [button, 'clear'],
      locale: settings.lang[language],
      timepicker: settings[inputFormat].timepicker,
      onlyTimepicker: settings[inputFormat].onlyTimepicker,
      minutesStep: minStep,
      autoClose: settings[inputFormat].autoClose,
      view: settings[inputFormat].view,
      minView: settings[inputFormat].view,
      dateFormat: settings[inputFormat].dateFormat,
      timeFormat: settings[inputFormat].timeFormat,
      startDate: now,
    });
  });
}



// 윈도우 팝업
function openPopup(url, name, width, height, top, left) {  // 앞의 4개 파라미터 필수, left/top 선택(없으면 0)
  if (top === undefined) top = 0;
  if (left === undefined) left = 0;
  window.open(url, name, 'toolbar = no, scrollbars = yes, resizable = no, menubar = no, status = no, titlebar = no, top = ' + top + ', left = ' + left + ', width = ' + width + ', height = ' + height);
}
