/* Minification failed. Returning unminified contents.
(49,51-59): run-time error JS1006: Expected ')': function
(49,62): run-time error JS1004: Expected ';'
(221,31): run-time error JS1004: Expected ';'
(270,2-3): run-time error JS1195: Expected expression: )
 */
$(document).ready(function () {
    //FB API (先建立好 fb 根元素後再嵌入 fb sdk)
    $('body').append('<div id="fb-root"></div>').ready(function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/zh_TW/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    window.fbAsyncInit = function () {
        FB.init({
            appId: '117546701661897',
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true,  // parse social plugins on this page
            version: 'v12.0'
        });
    };
});

$(window).on("load", function () {
    var $host = window.location.host;

    AppleID.auth.init({
        clientId: 'tw.net.ebc',
        scope: 'name email',    //權限範圍
        redirectURI: 'https://' + $host + '/User/AppleAuth',    //Apple Services ID裡設定的驗證網址,要同domain
        //因為登入為彈出視窗無法帶入RequestVerificationToken,故不加了
        //state: $('input[name=__RequestVerificationToken]').val(),   //可指定任意值，會原封不動地返回這個值，可通過它做驗證, 選填
        usePopup: true    //以彈出視窗方式顯示,選填
    });
});

//document.addEventListener('AppleIDSignInOnSuccess', (data) => {
//    //Apple ID登入成功時回傳
//    //console.log(data.detail.authorization);
//    //console.log(data.detail.user);
//});
//document.addEventListener('AppleIDSignInOnFailure', (error) => {
//    //關閉或取消視窗時回傳
//    //console.log('AppleIDSignInOnFailure:' + error.detail.error); //error.detail={error: "popup_closed_by_user"}
//});

function Captcha(id) {
    $("#" + id).attr("src", "/Scripts/captcha/get.ashx?r=" + Math.random());
    return false;
}

$('body').on("click", "input.message_btn2", async function () {
    //    regAccount = /^[A-Za-z0-9]{4,12}$/,
    //    regEmail = /^[^\s]+@[^\s]+\.[^\s]+$/;
    var $emailCheck = /^[a-zA-Z\d]([\.\-\+_]?[a-zA-Z\d])*@[a-zA-Z\d]([\-]?[a-zA-Z\d])*(\.[a-zA-Z\d]*)+$/;
    var $type = $(this).data("type");
    var $check = encodeURI(encodeURIComponent($.trim($("#ebc_check").val())));

    if ($type == "ebc" || $type == "ebc_forget") {
        if ($check.length == 0) {
            alert("請填寫驗證碼");
            $("#ebc_check").focus();
        }
        else {
            $.ajax({
                url: '/Scripts/captcha/check.ashx',
                type: "POST",
                data: { value: $check },
                success: function (result) {
                    if (result === "N") {
                        alert("驗證碼錯誤或已失效，請重新輸入");
                        Captcha('captcha');
                        $("#ebc_check").val('');
                        $("#ebc_check").focus();
                    }
                    else {
                        if ($type == "ebc") {
                            var $acc = $.trim($("#ebc_acc").val());
                            var $pwd = $.trim($("#ebc_pwd").val());

                            if ($acc.length == 0 || $pwd.length == 0) {
                                alert("請填寫帳號密碼");
                                Captcha('captcha');
                                $("#ebc_check").val('');
                            }
                            else if (!$emailCheck.test($acc)) {
                                alert("帳號為電子信箱，請確認填寫正確");
                                $("#ebc_acc").focus();
                                Captcha('captcha');
                                $("#ebc_check").val('');
                            }
                            else {
                                $.ajax({
                                    url: '/User/Login',
                                    type: "POST",
                                    data: {
                                        captcha: $check,
                                        account: encodeURI(encodeURIComponent($acc)),
                                        password: encodeURI(encodeURIComponent($pwd)),
                                        rememberme: $("#remember").prop("checked")
                                    },
                                    success: function (data) {
                                        if (data.result)
                                            window.location.reload(true);
                                        else {
                                            alert(data.message);
                                            Captcha('captcha');
                                            $("#ebc_check").val('');
                                        }
                                    },
                                    error: function (result) {
                                        alert("登入失敗，請再試一次");
                                        Captcha('captcha');
                                        $("#ebc_check").val('');
                                    }
                                });
                            }
                        }
                        else {
                            //var _email = $("#forget_email"),
                            //_check = $("#forget_captcha_input");
                            var $email = $.trim($("#forget_email").val());

                            //if ($.trim(_account.val()).length === 0 && $.trim(_email.val()).length === 0) {
                            //    alert('帳號或Email至少填一個。');
                            //    return false;
                            //}
                            //if (!regAccount.test(_account.val()) && $.trim(_account.val()).length > 0) {
                            //    alert('請輸入帳號4~12碼數字或英文');
                            //    $('#forget_acc').focus();
                            //    return false;
                            //}
                            if ($email.length == 0 && !$emailCheck.test($email)) {
                                alert("請確認電子信箱填寫正確");
                                $('#forget_email').focus();
                                Captcha('captcha');
                                $("#ebc_check").val('');
                            }
                            else {
                                $.ajax({
                                    url: '/User/Forget',
                                    type: "POST",
                                    data: {
                                        //email: encodeURI(encodeURIComponent($email)),
                                        account: encodeURI(encodeURIComponent($email)),
                                        captcha: $check
                                    },
                                    success: function (data) {
                                        if (data.message !== '') {
                                            alert(data.message);
                                        }
                                        if (data.result === 'Y') {
                                            window.location.reload(true);
                                        } else {
                                            Captcha('captcha');
                                            $("#ebc_check").val('');
                                        }
                                    },
                                    error: function (result) {
                                        alert("執行失敗，請再試一次");
                                        Captcha('captcha');
                                        $("#ebc_check").val('');
                                    }
                                });
                            }
                        }
                    }
                },
                error: function (result) {
                    alert("驗證失敗，請再試一次");
                    Captcha('captcha');
                    $("#ebc_check").val('');
                }
            });
        }
    }
    else if ($type === 'fb') {
        FB.login(function (response) {
            if (response.authResponse) {
                FB.api('/me?fields=id,name,email', function (response) {
                    if (typeof (response.email) != "undefined" && response.email != null) {
                        $.ajax({
                            url: '/User/FBLogin',
                            type: "POST",
                            data: {
                                account: encodeURI(encodeURIComponent(response.email)),
                                nickname: encodeURI(encodeURIComponent(response.name)),
                                //gender: response.gender,
                                //email: encodeURI(encodeURIComponent(response.email)),
                                //business_token: response.token_for_business,
                                rememberme: $("#remember").prop("checked")
                            },
                            success: function (data) {
                                if (data.result)
                                    window.location.reload(true);
                                else if (data.status == 2) {
                                    alert(data.message);
                                    location.href = '/Member/Register';
                                }
                                else {
                                    alert(data.message);
                                    Captcha('captcha');
                                    $("#ebc_check").val('');
                                }
                            },
                            error: function () {
                                alert("登入失敗，請再試一次");
                                Captcha('captcha');
                                $("#ebc_check").val('');
                            }
                        });
                    } else {
                        alert("登入失敗，請確認Facebook是否有Email資料");
                    }
                });
            }
            else {
                alert('Facebook授權失敗');
            }
        }, { scope: 'email' });
    }
    else if ($type === 'apple') {
        try {
            const data = await AppleID.auth.signIn();
            //var $verify = $('input[name=__RequestVerificationToken]').val();
            //var $state = data.authorization.state;
            //if ($verify === $state) {
            var $authData = data.authorization;
            var $userData = typeof data.user === 'undefined' ? {} : data.user;
            var $remember = $("#remember").prop("checked");

            $.ajax({
                url: '/User/AppleLogin',
                type: "POST",
                data: {
                    authorization: $authData,
                    user: $userData,
                    rememberme: $remember
                },
                success: function (data) {
                    if (data.result)
                        window.location.reload(true);
                    else if (data.status == 2) {
                        alert(data.message);
                        location.href = '/Member/Register';
                    }
                    else {
                        alert(data.message);
                        Captcha('captcha');
                        $("#ebc_check").val('');
                    }
                },
                error: function () {
                    alert("登入失敗，請再試一次");
                    Captcha('captcha');
                    $("#ebc_check").val('');
                }
            });
            //}
            //else {
            //    alert("授權資料驗證失敗，請再試一次");
            //    Captcha('captcha');
            //    $("#ebc_check").val('');
            //}

        } catch (error) {
            //console.log(error);//{error: "popup_closed_by_user"}
            alert("授權失敗，請稍後再試");
            Captcha('captcha');
            $("#ebc_check").val('');
        }
    }
});

function Login() {
    var $browser = browserInApp();
    $.get("/User/Login", function (data) {
        if (data) {
            if ($browser == "line" || $browser == "fbav") {
                //如果有開啟浮動登入視窗則關閉
                if ($("div.overlay-scale.open").length > 0)
                    toggleOverlay($("div.overlay-scale.open").attr('id'));
                //Line或Android FB App需另開瀏覽器
                alert("為維持良好的瀏覽體驗，將另開瀏覽器載入網頁");
                openExternalBrowser($browser);
            }
            else {
                $("#login-dialog>div.overlay-login").html('');
                $("#login-dialog>div.overlay-login").html(data);
                Captcha('captcha');
            }
        }
        else
            location.reload(true);
    });
}

function Forget() {
    $.get("/User/Forget", function (data) {
        $("#login-dialog>div.overlay-login").html('');
        $("#login-dialog>div.overlay-login").html(data);
        Captcha('captcha');
    });
};
