<style>
    /*.btncalendar {*/
    /*    cursor: pointer !important;*/
    /*}*/

    /*.picker__select--month,*/
    /*.picker__select--year {*/
    /*    height: 3em !important;*/
    /*}*/
</style>
<div class="title">新增學生</div>
<ul class="table-toolbar" style="text-align: left;">
    <li><a class="toolbar-element btn btn-default btn-create" href="/student"><i style="margin-right: 8px;"><span class="iconify" data-icon="typcn-arrow-back" data-inline="false"></span></i>返回</a></li>
</ul>
<div class="form-container">
    <form class="form-horizontal" role="form" method="post" id="myForm">
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="code">學生號碼</label></div>
            <div class="col-sm-10 text-center mas-title mas-box "><input id=code type="text" class="form-control mas-input" disabled name="code" value="<系統自動產生>" /></div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="chi_name">中文姓名*</label></div>
            <div class="col-sm-10 text-center mas-title mas-box "><input id=chi_name type="text" class="form-control mas-input" name="chi_name" value="" /></div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="eng_name">英文姓名*</label></div>
            <div class="col-sm-10 text-center mas-title mas-box "><input id=eng_name type="text" class="form-control mas-input" name="eng_name" value="" /></div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="gender">性別</label></div>
            <div class="col-sm-10 mas-box">
                <select id="gender" class="select mas-select" name="gender" select2>
                    <option value="" selected="selected">--- 請選擇性別 ---</option>
                    <?php
                    foreach ($gender as $idx => $g) {
                        echo sprintf('<option value="%s">%s</option>', $idx, $g);
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="dob">出生日期</label></div>
            <div class="col-sm-10 mas-box">
                <div class="input-group clickable" datetimepicker format="YYYY-MM-DD">
					<input class="form-control" type="text" name="dob" id="dob" autocomplete="off" />
					<span class="input-group-addon">
		                <span class="glyphicon glyphicon-calendar"></span>
		            </span>
				</div>
<!--				<div class="input-group date dob" datetimepicker>-->
<!--					<input class="form-control" size="10" name="dob" type="text" value="" readonly />-->
<!--					<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>-->
<!--				</div>-->
            </div>
        </div>
        <fieldset>
            <div class="form-group">
                <div class="col-sm-2 text-center mas-group-title">
                    <label>主要聯絡人*</label>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content1_name">姓名</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content1_name" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content1_relationship">親屬關係</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <select name="content1_relationship" class="select mas-select" select2>
                        <option value="0" selected="selected">--- 請選擇親屬關係 ---</option>
                        <?php
                        foreach ($relationship as $idx => $g) {
                            echo sprintf('<option value="%s">%s</option>', $idx, $g);
                        }
                        ?>
                    </select>
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content1_phone">聯絡電話</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content1_phone" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content1_email">電郵</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="email" name="content1_email" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
        </fieldset>
        <fieldset>
            <div class="form-group">
                <div class="col-sm-2 text-center mas-group-title">
                    <label>次要聯絡人</label>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content2_name">姓名</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content2_name" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content2_relationship">親屬關係</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <select name="content2_relationship" class="select mas-select" select2>
                        <option value="0" selected="selected">--- 請選擇親屬關係 ---</option>
                        <?php
                        foreach ($relationship as $idx => $g) {
                            echo sprintf('<option value="%s">%s</option>', $idx, $g);
                        }
                        ?>
                    </select>
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content2_phone">聯絡電話</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content2_phone" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content2_email">電郵</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="email" name="content2_email" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
        </fieldset>
        <fieldset>
            <div class="form-group">
                <div class="col-sm-2 text-center mas-group-title">
                    <label>備用聯絡人</label>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content3_name">姓名</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content3_name" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content3_relationship">親屬關係</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <select name="content3_relationship" class="select mas-select" select2>
                        <option value="0" selected="selected">--- 請選擇親屬關係 ---</option>
                        <?php
                        foreach ($relationship as $idx => $g) {
                            echo sprintf('<option value="%s">%s</option>', $idx, $g);
                        }
                        ?>
                    </select>
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
            <div class="form-group mas-col">
                <div class="col-sm-2 text-center mas-title">
                    <label for="content3_phone">聯絡電話</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="text" name="content3_phone" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
                <div class="col-sm-2 text-center mas-title">
                    <label for="content3_email">電郵</label>
                </div>
                <div class="col-sm-4 mas-box">
                    <input type="email" name="content3_email" class="form-control mas-input" placeholder="" value="">
                    <p class="help-block red hidden">Error Msg</p>
                </div>
            </div>
        </fieldset>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title">
                <label>居住地區</label>
            </div>
            <div class="col-sm-2 mas-box">
                <select class="select mas-select" name="district_id" id="residentDistrict" select2>
                    <option value="" selected="selected">--- 請選擇區域 ---</option>
                    <?php
                    foreach ($location as $loc) {
                        echo sprintf('<option value="%s">%s</option>', $loc['id'], $loc['chi_name']);
                    }
                    ?>
                </select>
                <p class="help-block red hidden">Error Msg</p>
            </div>
            <div class="col-sm-4 mas-box">
                <select class="select mas-select" name="area_id" id="residentArea" select2>
                    <option value="" selected="selected">--- 請選擇地區 ---</option>
                </select>
                <p class="help-block red hidden">Error Msg</p>
            </div>
            <div class="col-sm-4 mas-box">
                <select class="select mas-select" name="zone" id="residentZone" select2>
                    <option value="" selected="selected">--- 請選擇地點 ---</option>
                </select>
                <p class="help-block red hidden">Error Msg</p>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="address">住址</label></div>
            <div class="col-sm-10 text-center mas-title mas-box "><input id=address type="text" class="form-control mas-input" name="address" value="" placeholder="輸入住址" /></div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="school_district_id">學校所在地區</label></div>
            <div class="col-sm-10 mas-box">
                <select id="school_district_id" class="select mas-select" name="school_district_id" select2>
                    <option value="" selected="selected">--- 請選擇學校所在地區 ---</option>
                    <?php
                    foreach ($school_district as $district) {
                        echo sprintf('<option value="%s">%s</option>', $district['id'], $district['chi_name']);
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="school_id">就讀學校</label></div>
            <div class="col-sm-10 mas-box">
                <select id="school_id" class="select mas-select" name="school_id" select2>
                    <option value="" selected="selected">--- 請選擇就讀學校 ---</option>
                </select>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="grade">就讀年級</label></div>
            <div class="col-sm-10 mas-box">
                <select id="grade" class="select mas-select" name="grade" select2>
                    <option value="" selected="selected">--- 請選擇就讀年級 ---</option>
                    <?php
                    foreach ($student_grade as $grade) {
                        echo sprintf('<option value="%s">%s</option>', $grade['id'], $grade['name']);
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="source">來源</label></div>
            <div class="col-sm-10 text-center mas-title mas-box ">
                <select class="select mas-select" name="source" select2>
                    <option value="" selected="selected">--- 請選擇來源 ---</option>
                    <?php
                    foreach ($student_source as $source) {
                        echo sprintf('<option value="%s">%s</option>', $source['id'], $source['name']);
                    }
                    ?>
                </select>
            </div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="recommended_by">推薦人</label></div>
            <div class="col-sm-10 text-center mas-title mas-box "><input id=recommended_by type="text" class="form-control mas-input" name="recommended_by" value="" /></div>
        </div>
        <div class="form-group mas-col">
            <div class="col-sm-2 text-center mas-title"><label for="remark">備註</label></div>
            <div class="col-sm-10 mas-box"><textarea id="remark" class="form-control mas-textarea" rows="3" name="remark"></textarea></div>
        </div>
        <!--      <div class="form-group mas-col">
                 <div class="col-sm-2 text-center mas-title"><label for="status">狀態*</label></div>
                 <div class="col-sm-10 mas-box">
                    <select id="status" class="select mas-select" name="status" >
                       <option value="">--</option>
                       <option value="0">非活躍</option>
                       <option value="1">現任</option>
                       <option value="2">暫停</option>
                       <option value="3">退學</option>
                    </select>
                 </div>
              </div>-->
        <div class="form-footer">
            <a class="btn btn-footer reset" href="javascript:window.location.reload(true)">重設</a>
            <!--<button class="btn btn-footer submit" type="button" id='btnSubmit' name="submit">下一步</button>-->
            <input class="btn btn-footer submit" type="button" id="btnSubmit" value="提交">
        </div>
    </form>
</div>
<script>
    function getRemoteData(remote_url, data, callback, callbackFail) {
        $.ajax({
            //async: false,
            //timeout: 30000, //最長等候回應時間
            type: "GET", //提交類型
            url: remote_url, //提交地址
            data: data, //提交內容
            dataType: 'json', //返回數據類型
            success: function(data) { //請求完成並成功
                if (data.success) {
                    callback(data.data);
                } else {
                    callbackFail();
                }
            },
            error: function(data) { //請求返回錯誤信息
                callbackFail();
            },
            beforeSend: function(XHR) { //请求開始前执行
            },
            complete: function(XHR, status) { //请求完成后最终执行
            }
        });
    }

    function postRemoteData(remote_url, data, callback, callbackFail) {
        $.ajax({
            //async: false,
            //timeout: 30000, //最長等候回應時間
            type: "POST", //提交類型
            url: remote_url, //提交地址
            data: data, //提交內容
            dataType: 'json', //返回數據類型
            success: function(data) { //請求完成並成功
                if (data.success) {
                    callback(data.data);
                } else {
                    callbackFail();
                }
            },
            error: function(data) { //請求返回錯誤信息
                callbackFail();
            },
            beforeSend: function(XHR) { //请求開始前执行
            },
            complete: function(XHR, status) { //请求完成后最终执行
            }
        });
    }

    function getRemoteDataFail() {
        alert("發生錯誤");
    }

    function validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

    function validation() {
        if ($('INPUT[name="chi_name"]').val() == "") {
            alert("請輸入中文姓名");
            return false;
        }
        if (!$('INPUT[name="chi_name"]').val().toString().match(/[\u3400-\u9FBF]/)) {
            alert("中文姓名欄必須輸入中文");
            return false;
        }
        if ($('INPUT[name="eng_name"]').val() == "") {
            alert("請輸入英文姓名");
            return false;
        }
        if($('INPUT[name="dob"]').val() != ""){
            var date_of_birth = $('INPUT[name="dob"]').val();
            var CDate = new Date();
            console.log(new Date(date_of_birth).getTime());
            console.log(CDate.getTime());
            if(new Date(date_of_birth).getTime() >= CDate.getTime()){
                alert("請輸入正確的出生日期");
                return false;
            }
        }


        if ($('INPUT[name="content1_name"]').val() == "") {
            alert("請輸入主要聯絡人姓名");
            return false;
        }
        
        if ($('SELECT[name="content1_relationship"] option:checked').val() == "0") {
            alert("請選攞主要聯絡人與學生的關係");
            return false;
        }
        if ($('INPUT[name="content1_phone"]').val() == "") {
            alert("請輸入主要聯絡人電話號碼");
            return false;
        }
        if ($('INPUT[name="content1_phone"]').val().match(/^\d{8}$/)) {
            
            }else{
                alert("請輸入正確的主要聯絡人電話號碼");
            return false;
        }
    
        

        /*if ($('INPUT[name="content1_email"]').val() == "") {
            alert("請輸入主要聯絡人電郵地址");
            return false;
        }*/
		if ($('INPUT[name="content1_email"]').val() != "") {
        if (!validateEmail($('INPUT[name="content1_email"]').val())) {
            alert("請輸入主要聯絡人的正確電郵地址");
            return false;
        }
		}
        if ($('INPUT[name="content2_email"]').val() != "") {
            if (!validateEmail($('INPUT[name="content2_email"]').val())) {
                alert("請輸入次要聯絡人的正確電郵地址");
                return false;
            }
        }
        if ($('INPUT[name="content3_email"]').val() != "") {
            if (!validateEmail($('INPUT[name="content3_email"]').val())) {
                alert("請輸入備用聯絡人的正確電郵地址");
                return false;
            }
        }
        if ($('SELECT[name="area_id"] option:checked').length == 0) {
            alert("沒有居住地區記錄");
            return false;
        }
        if ($('SELECT[name="school_id"] option:checked').length == 0) {
            alert("沒有就讀學校記錄");
            return false;
        }
        return true;
    }

    function buildDistrict(district) {
        $('SELECT[name="area_id"]').empty();
        $('SELECT[name="area_id"]').append(
            $('<option>').attr({
                value: "",
                selected: "selected",
            }).text('--- 請選擇地區 ---')
        );
        district.forEach(function(row) {
            $('SELECT[name="area_id"]').append(
                $('<option>').attr({
                    value: row['id'],
                }).text(row['chi_name'])
            );
        });
    }

    function buildSchool(schools) {
        $('SELECT[name="school_id"]').empty();
        $('SELECT[name="school_id"]').append(
            $('<option>').attr({
                value: "",
                selected: "selected",
            }).text('--- 請選擇就讀學校 ---')
        );
        schools.forEach(function(row) {
            $('SELECT[name="school_id"]').append(
                $('<option>').attr({
                    value: row['id'],
                }).text(row['chi_name'])
            );
        });
    }

    function addStudent() {
        postRemoteData(
            "/api/createstudent", {
                'remark': $('TEXTAREA[name="remark"]').val(),
                'chi_name': $('INPUT[name="chi_name"]').val(),
                'eng_name': $('INPUT[name="eng_name"]').val(),
                'gender': $('SELECT[name="gender"] option:checked').val(),
                'dob': $('INPUT[name="dob"]').val(),
                'area': $('SELECT[name="area"] option:checked').val(),
                'zone': $('SELECT[name="zone"] option:checked').val(),
                'address': $('INPUT[name="address"]').val(),
                'grade': $('SELECT[name="grade"] option:checked').val(),
                'source': $('SELECT[name="source"] option:checked').val(),
                'recommended_by': $('INPUT[name="recommended_by"]').val(),
                'content1_name': $('INPUT[name="content1_name"]').val(),
                'content1_phone': $('INPUT[name="content1_phone"]').val(),
                'content1_email': $('INPUT[name="content1_email"]').val(),
                'content1_relationship': $('SELECT[name="content1_relationship"] option:checked').val(),
                'content2_name': $('INPUT[name="content2_name"]').val(),
                'content2_phone': $('INPUT[name="content2_phone"]').val(),
                'content2_email': $('INPUT[name="content2_email"]').val(),
                'content2_relationship': $('SELECT[name="content2_relationship"] option:checked').val(),
                'content3_name': $('INPUT[name="content3_name"]').val(),
                'content3_phone': $('INPUT[name="content3_phone"]').val(),
                'content3_email': $('INPUT[name="content3_email"]').val(),
                'content3_relationship': $('SELECT[name="content3_relationship"] option:checked').val(),
                'school_district_id': $('SELECT[name="school_district_id"] option:checked').val(),
                'school_id': $('SELECT[name="school_id"] option:checked').val(),
                'district_id': $('SELECT[name="district_id"] option:checked').val(),
                'area_id': $('SELECT[name="area_id"] option:checked').val(),
            },
            addStudentSuccess,
            getRemoteDataFail
        );
    }

    function addStudentSuccess(data) {
        alert("學生已新增");
        window.location.href = '/student/insert/' + data.result.student_no;
    }

    $(document).ready(function() {
        var li = $('#sidebar-menu li').filter(function(i) {
            return $(this).find('.menu-dropdown').find('.menu-text').text() === '學生';
        });
        li.addClass('active open');

        // $('.date-picker').pickadate({
        //     labelMonthNext: 'Go to the next month',
        //     labelMonthPrev: 'Go to the previous month',
        //     labelMonthSelect: 'Pick a month from the dropdown',
        //     labelYearSelect: 'Pick a year from the dropdown',
        //     selectMonths: true,
        //     selectYears: true,
        //     format: 'yyyy-mm-dd',
        // });
        // $('.btncalendar').css('cursor', 'default').pickadate({
        //     labelMonthNext: 'Go to the next month',
        //     labelMonthPrev: 'Go to the previous month',
        //     labelMonthSelect: 'Pick a month from the dropdown',
        //     labelYearSelect: 'Pick a year from the dropdown',
        //     selectMonths: true,
        //     selectYears: true,
        //     format: 'yyyy-mm-dd'
        // });
        $('SELECT[name="district_id"]').on('change', function() {
            var id = $('SELECT[name="district_id"]').val();
            getRemoteData(
                "/api/location/district", {
                    location_id: id,
                },
                buildDistrict,
                getRemoteDataFail
            );
        });

        $('SELECT[name="area_id"]').on('change', function() {
            $('SELECT[name="zone"]').empty();
            $('SELECT[name="zone"]').append(
                $('<option>').attr({
                    value: "",
                    selected: "selected",
                }).text('--- 請選擇地點 ---')
            );
            var area = $('SELECT[name="area_id"] option:selected').text().split(",");
            area.forEach(function(row) {
                $('SELECT[name="zone"]').append(
                    $('<option>').attr({
                        value: row,
                    }).text(row)
                );
            });
        });

        $('SELECT[name="zone"]').on('change', function() {
            $('INPUT[name="address"]').val($('SELECT[name="district_id"] option:selected').text() + $('SELECT[name="zone"] option:selected').text());
        });

        $('SELECT[name="school_district_id"]').on('change', function() {
            var district = $('SELECT[name="school_district_id"] option:selected').text();
            getRemoteData(
                "/api/school/school", {
                    school_district: district,
                },
                buildSchool,
                getRemoteDataFail
            );
        });

        $('#btnSubmit').on('click', function() {
            if (validation()) {
                addStudent();
            }
        });
    });
</script>
