<%
/**
 * <pre>
 * @Class Name : putMyInfo.jsp
 * 
 * @Description : 내 정보 수정
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 7. 12.    JSYOO       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP JSYOO
 * @since 2021. 7. 12.
 * @version 1.0
 *
 */
 %>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="validator" uri="http://www.springmodules.org/tags/commons-validator" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>Insert title here</title>
<script type="text/javaScript" language="javascript" defer="defer">
$(document).ready(function() {
    <%
    //핸드폰 번호가 변하는것 실시간 감지
    %>
    $("#mobileNo").on("propertychange change keyup paste input", function() {
        $("#mobileCertYn").val("N");
    });
    $("input:radio[name='gender']:radio[value='${loginVO.gender}']").prop("checked",true);
    
    var birthday='${loginVO.birthday}';
    
    $("#birth_yy").val(birthday.substr(0,4));
    $("#birth_mm").val(birthday.substr(4,2));
    $("#birth_dd").val(birthday.substr(6,2));
    alert("22222 <c:out value="${loginVO.address}" escapeXml="false"/>");
})

function update(){
    var p = document.getElementById('password'); 
    var p_cf = document.getElementById('passwordConfirm'); 
    
    if(p.value != p_cf.value)
    {
         alert("비밀번호가 일치하지 않습니다. 확인해 주세요.");
         p_cf.focus();
         return false;
    }
    if(!checkBirthday())
    {
        alert("생년월일이 형식에 맞지 않습니다. 확인해주세요.");    
        return false;
    }
    if($("#mobileCertYn").val()!="Y")
    {
        alert("휴대전화 인증이 필요합니다.");
        return false;
    }
    
    if($("#zipCode").val()=="" || $("#address").val()=="" || $("#addressDetail").val()=="")
    {
        alert("주소를 입력해주세요.");
        return false;
    }

    if(confirm("정보를 수정하시겠습니까?")){
        $("#birthday").val($("#birth_yy").val()+$("#birth_mm").val()+$("#birth_dd").val());
        
        var queryString = $("form[name=updateForm]").serialize() ;

        $.ajax({
            url : "${pageContext.request.contextPath}/userInfo/updateMyInfo.ajax",
            type : "POST",
            async: false,
            data : queryString,
            success : function(result){
                alert("정보를 수정하였습니다.");
                //인증번호 확인창
                location.replace("${pageContext.request.contextPath}/userInfo/getMyInfo.do");
            },error : function(){
            	alert("정보 수정에 실패하였습니다.");
                            	
            }
        })
        return false;
     }else{
         return false;
     }
}

<%
//핸드폰 인증번호 받기
%>
function mobileCert(){
    

    $("#mobileNo").val($("#mobileNo").val().replace(/-/gi,""));
    var regExp = /^\d{3}\d{3,4}\d{4}$/;
    
    if(!regExp.test($("#mobileNo").val()) || $("#mobileNo").val()==""){
        
        alert("형식에 맞지 않는 번호입니다.");
        return false;
    }
    
    $.ajax({
        url : "/nlib/member/mobileCertNum.ajax",
        type : "POST",
        async: false,
        data : {"mobileNo" : $("#mobileNo").val()},
        success : function(result){
            alert("인증번호가 발송됐습니다.");
            //인증번호 확인창
            $("#mobileCertForm").css("display","block")
            
        },error : function(){
        }
    })
}

<%
//핸드폰 인증번호 확인
%>
function certNumCheck(){
    <%
    //ajax 사용자가 입력한 번호를 보내 RESTfull server에서 확인 success or fail 반환 (3분이내인지도)
    %>
    $.ajax({
        url : "/nlib/member/mobileCertNumChk.ajax",
        type : "POST",
        data : {"mobileCertNum" : $("#mobileCertNum").val(),
                "mobileNo" : $("#mobileNo").val()},
        async: false,
        success : function(result){
            if(result=="true")
            {
                alert("인증되었습니다.");
                $("#mobileCertYn").val("Y");
            }else{
                alert("인증번호가 일치하지않습니다.");
            }
        },error : function(){
        }
    })
}

document.addEventListener('keydown', function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
    }
}, true);
    
function checkBirthday() {
    var birthday;
    var yy = $("#birth_yy").val();
    var mm = $("#birth_mm option:selected").val();
    var dd = $("#birth_dd").val();
    var lang = "ko_KR";

    var oyy = $("#birth_yy");
    var omm = $("#birth_mm");
    var odd = $("#birth_dd");

    if (mm.length == 1) {
        mm = "0" + mm;
    }
    if (dd.length == 1) {
        dd = "0" + dd;
    }

    birthday = yy + mm + dd;
    if (!isValidDate(birthday)) {
        return false;
    }

    var age = calcAge(birthday);
    if (age < 0) {
        return false;
    } else if (yy < 1900) {
        return false;
    } else {
        return true;
    }
}

function isValidDate(param) {
    try {
        param = param.replace(/-/g, '');

        // 자리수가 맞지않을때
        if (isNaN(param) || param.length != 8) {
            return false;
        }

        var year = Number(param.substring(0, 4));
        var month = Number(param.substring(4, 6));
        var day = Number(param.substring(6, 8));

        if (month < 1 || month > 12) {
            return false;
        }

        var maxDaysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        var maxDay = maxDaysInMonth[month - 1];

        // 윤년 체크
        if (month == 2 && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)) {
            maxDay = 29;
        }

        if (day <= 0 || day > maxDay) {
            return false;
        }
        return true;

    } catch (err) {
        return false;
    }
    ;
}

function calcAge(birth) {
    var date = new Date();
    var year = date.getFullYear();
    var month = (date.getMonth() + 1);
    var day = date.getDate();
    if (month < 10)
        month = '0' + month;
    if (day < 10)
        day = '0' + day;
    var monthDay = month + '' + day;

    birth = birth.replace('-', '').replace('-', '');
    var birthdayy = birth.substr(0, 4);
    var birthdaymd = birth.substr(4, 4);

    var age = monthDay < birthdaymd ? year - birthdayy - 1 : year - birthdayy;
    return age;
}
</script>
<style type="text/css">

body {

    padding-top:0px;

    margin-top:0px;

    background-color:#f5f5f5;

}



.page-header {

    padding-top:0px;

    margin-top:0px;

}



.form-horizontal .control-label.text-left{

    text-align:left;

}



.form-horizontal .form-group {

    height:50px;

}



h3 span.ok {

    color:#01A9DB;

}



label.error {

    font-family:"돋움", Dotum, "Apple SD Gothic Neo", Helvetica, Sans-serif;

    font-size:9pt;

    font-weight:600;

    padding:3px 0 0 10px;

    color:#FF0000;

    display:block;

}
</style>
</head>
<body>
<div id="wrap">
        <br><br>
        <b><font size="6" color="gray">정보수정</font></b>
        <br><br><br>
        
        <form id="updateForm" name="updateForm" method="post" onsubmit="return update()" >
            <table>
                <tr>
                    <td id="title">아이디</td>
                    <td>
                        <input type="email" id="loginUserId" name="loginUserId" maxlength="30" required readonly value=<c:out value="${loginVO.loginUserId}"/>  >
                    </td>
                </tr>
                <tr>
                   <td id="title">이름</td>
                   <td>
                       <input type="text" id="name" name="name" maxlength="20" required value=<c:out value="${loginVO.name}"/>>
                   </td>
                </tr>
                <tr>
                    <td id="title">성별</td>
                    <td>
                        <input type="radio" name="gender" value="M" required>남자
                        <input type="radio" name="gender" value="F" required>여자
                    </td>
                </tr>
                <tr>
                    <td id="title">생년월일</td>
                    <td>
                        <input type="text" id="birth_yy" name="birth_yy" maxlength="4" placeholder="년(4자)" required >
                        <select id="birth_mm" name="birth_mm" required>
                            <option value="">월</option>
                            <option value="01" >01</option>
                            <option value="02" >02</option>
                            <option value="03" >03</option>
                            <option value="04" >04</option>
                            <option value="05" >05</option>
                            <option value="06" >06</option>
                            <option value="07" >07</option>
                            <option value="08" >08</option>
                            <option value="09" >09</option>
                            <option value="10" >10</option>
                            <option value="11" >11</option>
                            <option value="12" >12</option>
                        </select>
                        <input type="text" id="birth_dd" name="birth_dd" size="2" maxlength="2" placeholder="일" size="4" required>
                    </td>
                </tr>     
                <tr>
                    <td id="title">비밀번호</td>
                    <td>
                        <input type="password" id="password" name="password" minlength="8" maxlength="16"
                        oninvalid="this.setCustomValidity('8~16자 영문 대 소문자, 숫자, 특수문자를 사용하세요.')" 
                        oninput="this.setCustomValidity('')"
                        pattern="^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,16}$" required>
                    </td>
                </tr>
                
                <tr>
                    <td id="title">비밀번호 확인</td> 
                    <td>
                        <input type="password" id="passwordConfirm" name="passwordConfirm" minlength="8" maxlength="16"  required>
                    </td>
                </tr>
                
                <tr>
                    <td id="title">주소</td>
                    <td>
                       <input type="text" id="zipCode" name="zipCode" value="<c:out value="${loginVO.zipCode}"/>" readonly  ><button type="button" style="text-align:left;" class="btn-warning" onclick="goPopup()">주소검색</button><br>
                       <input type="text" id="address" name="address" value="<c:out value="${loginVO.address}" escapeXml="false"/>" readonly />
                       <input type="text" id="addressDetail" name="addressDetail" value="<c:out value="${loginVO.addressDetail}"/>" readonly />

                    </td>
                </tr>
                <tr>
                    <td id="title">휴대전화</td>
                    <td id="Cert">
                        <input type="text" id="mobileNo" name="mobileNo" required value="<c:out value="${loginVO.mobileNo}"/>" ><button type="button" style="text-align:left;" class="btn-warning" onclick="mobileCert()" required>인증번호 받기</button>
                        <div id="mobileCertForm" style="display:none;"><br><input type='text' id='mobileCertNum' name='mobileCertNum'> <button type='button' style='text-align:left;' class='btn-warning' onclick='certNumCheck()' >인증번호 확인</button></div>
                    </td>
                </tr>
            </table>
            <br>
            <input type="hidden" id="mobileCertYn" name="mobileCertYn" value=<c:out value="Y"/>>
            <input type="hidden" id="birthday" name="birthday" >
            <input type="submit" value="수정"/>  <input type="button" onclick="javascript:location.href='${pageContext.request.contextPath}/userInfo/getMyInfo.do';" value="취소">
        </form>
    </div>
</body>
</html>