<%
/**
 * <pre>
 * @Class Name : insertMemberInfoForm.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>
<html>
<head>
<title>${pageTitle} <spring:message code="title.create" /></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javaScript" language="javascript" defer="defer">
function signUp(){
	var p = document.getElementById('password'); 
	var p_cf = document.getElementById('passwordConfirm'); 
	
	if(p.value != p_cf.value)
	{
		 alert("비밀번호가 일치하지 않습니다. 확인해 주세요.");
		 p_cf.focus();
		 return false;
	}
		
	if($("#mobileCertYn").val()!="Y")
	{
		alert("휴대전화 인증이 필요합니다.");
		return false;
	}
	if($("#emailCertYn").val()!="Y")
    {
        alert("이메일 인증이 필요합니다.");
        return false;
    }
	
	if($("#zipCode").val()=="" || $("#address").val()=="")
    {
        alert("주소를 입력해주세요.");
        return false;
    }
	if(!checkBirthday())
	{
	    alert("생년월일이 형식에 맞지 않습니다. 확인해주세요.");	
	}

	if(confirm("회원가입하시겠습니까?")){
		$("#birthday").val($("#birth_yy").val()+$("#birth_mm").val()+$("#birth_dd").val());
		
		<%
	    //연락받을 이메일 입력
	    %>
		$("#loginUserId").val($("#email").val());
		document.joinForm.action="${pageContext.request.contextPath}/member/insertMemberInfo.do";
        return true;
     }else{
         return false;
     }
}

$(document).ready(function() {
	$("input:radio[name='gender']:radio[value='${loginVO.snsGender}']").prop('checked', true);
	
	var birthday="${loginVO.snsBirthday}";
	
	if(!birthday == "")
	{
		var birth_yy =birthday.substr(0,4);
	    var birth_mm =birthday.substr(4,2);
	    var birth_dd =birthday.substr(6,2);
	    
	    if(birth_dd.substr(0,1) == "0")
        {
            birth_dd = birth_dd.substr(1,1)         
        }
        
	    $("#birth_yy").val(birth_yy)
	    $("#birth_mm").val(birth_mm).prop("selected", true);
	    $("#birth_dd").val(birth_dd)
	}
	
	
	<%
	//핸드폰 번호가 변하는것 실시간 감지
	%>
	$("#mobileNo").on("propertychange change keyup paste input", function() {
		if($("#snsMobileNo").val() == $("#mobileNo").val())
		{
			$("#mobileCertYn").val("Y");
			$("#mobileCertSendBtn").css("display","none");
			$("#mobileCertForm").css("display","none");			
		}else{
			$("#mobileCertYn").val("N");
	        $("#mobileCertSendBtn").css("display","block");
		}
	});
   <%
    //아이디가 변하는것 실시간 감지
    %>
    $("#email").on("propertychange change keyup paste input", function() {
    	if($("#snsUserId").val() == $("#email").val())
        {
            $("#emailCertYn").val("Y");
            $("#emailCertSendBtn").css("display","none");
            $("#emailCertForm").css("display","none");
            
        }else{
            $("#emailCertYn").val("N");
            $("#emailCertSendBtn").css("display","block");
        }
    });
})
<%
//이메일 인증
%>
function emailCert(){
    

    var regExp = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;

    if(!regExp.test($("#email").val()) || $("#email").val()==""){
        
        alert("형식에 맞지 않는 이메일입니다.");
        return false;
    }
    
    $.ajax({
        url : "${pageContext.request.contextPath}/member/emailCertNum.ajax",
        type : "POST",
        async: false,
        data : {"email" : $("#email").val()},
        success : function(result){
            alert(result.msg);
            
            if(result.emailCertYn=="Y")
           	{
            	$("#emailCertYn").val("N");
            	$("#emailCertForm").css("display","block")
           	}
            if(result.emailCertYn=="N")
           	{
                $("#emailCertYn").val("N");
                $("#emailCertForm").css("display","none")
           	}
        },error : function(){
        }
    })
}

<%
//이메일 인증번호 확인
%>
function certEmailCheck(){
  <%
  //ajax 사용자가 입력한 번호를 보내 RESTfull server에서 확인 success or fail 반환 (3분이내인지도)
  %>
  $.ajax({
      url : "${pageContext.request.contextPath}/member/emailCertNumChk.ajax",
      type : "POST",
      data : {"emailVrfctNo" : $("#emailVrfctNo").val(),
              "email" : $("#email").val()},
      async: false,
      success : function(result){
          if(result=="true")
          {
              alert("인증되었습니다.");
              $("#emailCertYn").val("Y");
          }else
          {
              alert("인증번호가 일치하지않습니다.");
          }
        }
      ,error : function(){
      }
  })
}

<%
//핸드폰 인증번호 받기
%>
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 : "${pageContext.request.contextPath}/member/mobileCertNum.ajax",
        type : "POST",
        async: false,
        data : {"mobileNo" : $("#mobileNo").val()},
        success : function(result){
            alert("인증번호가 발송됐습니다.");
            $("#mobileCertYn").val("N");
            $("#mobileCertForm").css("display","block")
        },error : function(){
        }
    })
}

<%
//핸드폰 인증번호 확인
%>
function certMobileCheck(){
    <%
    //ajax 사용자가 입력한 번호를 보내 RESTfull server에서 확인 success or fail 반환 (3분이내인지도)
    %>
    $.ajax({
        url : "${pageContext.request.contextPath}/member/mobileCertNumChk.ajax",
        type : "POST",
        data : {"mobileVrfctNo" : $("#mobileVrfctNo").val(),
                "mobileNo" : $("#mobileNo").val()},
        async: false,
        success : function(result){
        	if(result=="true")
        	{
	            alert("인증되었습니다.");
	            $("#mobileCertYn").val("Y");
	            document.joinForm.action="${pageContext.request.contextPath}/member/selectAlreadySignUpMobilePopup.do";
	            fn_layerPopFormSubmit("joinForm",false);
        	}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="joinForm" name="joinForm" method="post" onsubmit="return signUp()">
            <table>
                <tr>
                    <td id="title">이메일</td>
                    <td>
                        <input type="email" id="email" name="email" maxlength="30" required value="<c:out value="${loginVO.snsUserId}"/>"  ><button type="button" id="emailCertSendBtn" name="emailCertSendBtn" style="text-align:left;display:none;" class="btn-warning" onclick="emailCert()" required>인증번호 받기</button>
                        <div id="emailCertForm" style="display:none;"><br><input type='text' id='emailVrfctNo' name='emailVrfctNo'> <button type='button' style='text-align:left;' class='btn-warning' onclick='certEmailCheck()' >인증번호 확인</button></div>
                    </td> 
                </tr>
                <tr>
                   <td id="title">이름</td>
                   <td>
                       <input type="text" id="name" name="name" minlength="2" maxlength="20" value="<c:out value="${loginVO.snsName}"/>"  required >
                   </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" >1</option>
                            <option value="02" >2</option>
                            <option value="03" >3</option>
                            <option value="04" >4</option>
                            <option value="05" >5</option>
                            <option value="06" >6</option>
                            <option value="07" >7</option>
                            <option value="08" >8</option>
                            <option value="09" >9</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" readonly><button type="button" style="text-align:left;" class="btn-warning" onclick="sample6_execDaumPostcode()">주소검색</button><br>
                       <input type="text" id="address" name="address" readonly><input type="text" id="addressDetail" name="addressDetail"  >

                    </td>
                </tr>
                <tr>
                    <td id="title">휴대전화</td>
                    <td id="Cert">
                        <input type="text" id="mobileNo" name="mobileNo" value="<c:out value="${loginVO.snsMobileNo}"/>" required ><button type="button" id="mobileCertSendBtn" name="mobileCertSendBtn" style="text-align:left;display:none;" class="btn-warning" onclick="mobileCert()" required>인증번호 받기</button>
                        <div id="mobileCertForm" style="display:none;"><br><input type='text' id='mobileVrfctNo' name='mobileVrfctNo'> <button type='button' style='text-align:left;' class='btn-warning' onclick='certMobileCheck()' >인증번호 확인</button></div>
                    </td>
                </tr>
            </table>
            <br>
            <input type="hidden" id="birthday" name="birthday" >
            <input type="hidden" id="mobileCertYn" name="mobileCertYn" value="Y">
            <input type="hidden" id="emailCertYn" name="emailCertYn" value="Y">
            <input type="hidden" id="loginUserId" name="loginUserId" >
            <input type="hidden" id="snsMobileNo" name="snsMobileNo" value="<c:out value="${loginVO.snsMobileNo}"/>">
            <input type="hidden" id="snsUserId" name="snsUserId" value="<c:out value="${loginVO.snsUserId}"/>">
            
            <input type="submit" value="가입"/>
        </form>
    </div>
</body>

<script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
    function sample6_execDaumPostcode() {
        new daum.Postcode({
            oncomplete: function(data) {
                // 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.

                // 각 주소의 노출 규칙에 따라 주소를 조합한다.
                // 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
                var addr = ''; // 주소 변수
                var extraAddr = ''; // 참고항목 변수

                //사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
                if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
                    addr = data.roadAddress;
                } else { // 사용자가 지번 주소를 선택했을 경우(J)
                    addr = data.jibunAddress;
                }

                // 우편번호와 주소 정보를 해당 필드에 넣는다.
                document.getElementById('zipCode').value = data.zonecode;
                document.getElementById("address").value = addr;
                // 커서를 상세주소 필드로 이동한다.
                document.getElementById("addressDetail").focus();
            }
        }).open();
    }
</script>
</html>
