$(function (){
  tableSort();
})

$(document).on('click', '#savePasswordBtn', function (){
  if(passwordCheck()){
    const formData = new FormData($("#modifyPasswordForm")[0]);
    $.ajax({
      type : 'PUT',
      data : formData,
      url : "/info/passwordModify",
      processData: false,
      contentType: false,
      success : function(result) {
        if(result==="OK"){
          alert("수정되었습니다.");
          $("#passwordModifyModal").find(".btn-close").click();
        }else if(result==="passwordNotMatch"){
          alert("현재 비밀번호가 맞지 않습니다.");
        }
      },
      error : function(xhr, status) {

      }
    })
  }
})


function passwordCheck(){
  let returnFlag = true;
  const password = $("#password");
  const modifyPassword =$("#modifyPassword");
  const passwordConfirm = $("#passwordConfirm");
  if(!password.val()){
    alert("비밀번호를 입력해주세요.");
    returnFlag = false;
  }
  if(!modifyPassword.val()){
    alert("새 비밀번호를 입력해주세요.");
    returnFlag = false;
  }
  if(!passwordConfirm.val()){
    alert("비밀번호 확인을 입력해주세요.");
    returnFlag = false;
  }
  if(returnFlag){
    const passwordReg = /^(?=.*[a-zA-z])(?=.*[0-9])(?=.*[$`~!@$!%*#^?&\\(\\)\-_=+]).{8,16}$/;
    if(!passwordReg.test(modifyPassword.val())){
      alert("비밀번호 조건이 맞지 않습니다.")
      returnFlag = false;
    }else{
      if(modifyPassword.val() !== passwordConfirm.val()){
        alert("비밀번호가 같지 않습니다.");
        returnFlag = false;
      }
    }
  }
  return returnFlag;

}

function tableSort(){
  $("#categorySelectBody").find("tbody").each(function (idx, tbody){
    let lastCategorySeq = 0
    $(tbody).find(".depth2Td").each(function (idx, td){
      lastCategorySeq = removeInnerText(td, lastCategorySeq);
    })
    $(tbody).find(".depth3Td").each(function (idx, td){
      lastCategorySeq = removeInnerText(td, lastCategorySeq);
    })
  })
}

function removeInnerText(td, lastCategorySeq){
  const categorySeq = Number($(td).attr("data-categoryseq"));
  if(lastCategorySeq !== categorySeq){
    lastCategorySeq = categorySeq;
  }else{
    td.innerText = ''
  }
  return lastCategorySeq;
}