$(function() {


    $(document).on({
        click: function() {
            if (!$('#pagearea').length) {
                $.ajax({
                    url: "/tpl/inc/modal_login.php",
                    type: 'post',
                    dataType: 'html',
                    success: function(response) {
                        $('#info-modal').find('.modal-inner').html(response);
                        $('#info-modal').modal('show');
                    },
                    error: function(request) {

                    }
                });
            }
        }
    }, '.memberlogin');

    $(document).on({
        click: function() {
            if (!$('#pagearea').length) {
                $.ajax({
                    url: "/inc/login_auth.php",
                    type: 'post',
                    data: $('#login-form').serialize() + "&act=login",
                    dataType: 'script',
                    success: function() {

                    },
                    error: function(request) {

                    }
                });
            }
        }
    }, '.webacc-login');

    $(document).on({
        keypress: function() {
            if ($('.error-msg').text().length) {
                $('.error-msg').text('');
            }
        }
    }, '.login-block input');



    $(document).on({
        click: function() {
            if (!$('#pagearea').length) {
                $.ajax({
                    url: "/inc/login_auth.php",
                    type: 'post',
                    data: "act=logout",
                    dataType: 'script',
                    success: function() {

                    },
                    error: function(request) {

                    }
                });
            }
        }
    }, '.logout');


    $(document).on({
        keyup: function() {
            var passLength = 0;
            $('#infoform .pass-set input[type=password]').each(function() {
                passLength += $(this).val().length;
            });


            if (passLength > 0) {
                $('#infoform .pass-set input[type=password]').attr('required', 'true');
            } else {
                $('#infoform .pass-set input[type=password]').removeAttr('required');
                $('#infoform .pass-set').find('.form-group').removeClass('has-error has-danger');
                $('#infoform .pass-set').find('.list-unstyled').remove();
            }

        }


    }, '#infoform .pass-set input[type=password]');



    $('#infoform').on('submit', function(e) {
        // e.preventDefault(); e.stopPropagation();


    });

    $(document).on({
        click: function() {
            if (!$('#pagearea').length) {
                $.ajax({
                    url: "/tpl/inc/modal_resetpass.php",
                    type: 'post',
                    //data: $('#login-form').serialize()+"&act=login",
                    dataType: 'html',
                    success: function(response) {
                        $('#info-modal').find('.modal-inner').html(response);
                        $('#resetpass-form').validator();
                        //$('#info-modal').modal('show');	
                    },
                    error: function(request) {

                    }
                });

            }
        }
    }, '.reset-pass');

    $(document).on({
        submit: function(e) {
            e.preventDefault();
            e.stopPropagation();
            var eventForm = $('#resetpass-form');
            if (!$(eventForm).find('.form-group.has-error').length) {
                $.ajax({
                    url: "/inc/user/register_handler.php",
                    type: 'post',
                    data: $('#resetpass-form').serialize() + "&opr=sendResetMail",
                    dataType: 'script',
                    success: function(response) {

                    },
                    error: function(request) {

                    }
                });

            }
        }

    }, '#resetpass-form');


    $(document).on({
        submit: function(e) {
            e.preventDefault();
            e.stopPropagation();
            var eventForm = $('#reset-form');
            if (!$(eventForm).find('.form-group.has-error').length) {
                $.ajax({
                    url: "/inc/user/register_handler.php",
                    type: 'post',
                    data: $('#reset-form').serialize() + "&opr=resetpass",
                    dataType: 'script',
                    success: function() {},
                    error: function(request) {}
                });
            }
        }
    }, '#reset-form');


    ////////////////////////////// login func/////////////////////////////////


    $(document).on('click', '.googleAccLogin', function() {

        $('.social-login-wrap').data('logintype', 'accLogin');
        $('.social-login-wrap').data('loginsort', 'google');
        handleGoogleSignIn();
    });

    $(document).on('click', '.googleAccLogout', function() {
        handleGoogleSignOut();
    });




    // $(document).on('click', '.facebookAccLogin', function() {

    //     $('.social-login-wrap').data('logintype', 'accLogin');
    //     $('.social-login-wrap').data('loginsort', 'facebook');
    //     fbLogin();
    // });

    // $(document).on('click', '.facebookAccLoginPhp', function() {
    //     $(location).attr("href", $(this).data('url'));
    //     // fbLoginWin = window.open($(this).data('url'), 'Facebook 帳號登入', config = 'height=600,width=600')
    //     // $('.social-login-wrap').data('logintype', 'accLogin');
    //     // $('.social-login-wrap').data('loginsort', 'facebook');
    // });




}); ///document.ready



function handleGoogleClientLoad() {
    gapi.load('client:auth2', initGoogleClient);
}

handleGoogleClientLoad();

function initGoogleClient() {
    // Initialize the client with API key and People API, and initialize OAuth with an
    // OAuth 2.0 client ID and scopes (space delimited string) to request access.
    gapi.client.init({
        apiKey: 'AIzaSyClLZA0OKsVtKpEDG1vDE_MEH-9rMJbWKs',
        discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
        clientId: '179817918715-obmffm13rsgk8gkch63kv0fsjmvs2p22.apps.googleusercontent.com',
        scope: 'profile'
    }).then(function() {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateGoogleSigninStatus);

        // Handle the initial sign-in state.
        updateGoogleSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    });
}

function updateGoogleSigninStatus(isSignedIn) {
    if (isSignedIn) {

        makeGoogleApiCall();
    }
}

function handleGoogleSignIn(event) {
    // Ideally the button should only show up after gapi.client.init finishes, so that this
    // handler won't be called before OAuth is initialized.
    gapi.auth2.getAuthInstance().signIn();
}

function handleGoogleSignOut(event) {
    gapi.auth2.getAuthInstance().signOut();
}


function makeGoogleApiCall() {
    // Make an API call to the People API, and print the user's given name.
    gapi.client.people.people.get({
        'resourceName': 'people/me',
        'requestMask.includeField': 'person.names,person.emailAddresses,person.genders'
    }).then(function(response) {


        //var userGender = response.result.genders[0].value?'male':'';
        if (response.result.genders) {
            var userGender = response.result.genders[0].value;
        } else {
            var userGender = '';
        }

        //alert('Hello, ' + response.result.names[0].givenName+' '+ response.result.emailAddresses[0].value+' '+ userGender);
        socialLoginHandler('google', response.result.emailAddresses[0].value, response.result.names[0].givenName, userGender);
        //console.log(response.result);
    }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
    });
}


    /********************************FB************************/


// 初始化 Facebook SDK
window.fbAsyncInit = function() {
    FB.init({
        appId: '577902632718891', // 替換為你的 Facebook App ID
        cookie: true, // 啟用 cookies 以允許服務器訪問會話
        xfbml: true, // 解析社交插件
        version: 'v12.0' // 使用的 Facebook API 版本
    });

    FB.AppEvents.logPageView(); // 追踪登陸事件（可選）

    // 綁定 Facebook 登入按鈕
    $(document).on({
        click: function() {
            console.log('trigger fb login!');

            FB.login(function(response) {
                if (response.authResponse) {
                    console.log('Welcome! Fetching your information.... ');
                    FB.api('/me', {
                        fields: 'name, email'
                    }, function(response) {
                        // console.log('Good to see you, ' + response.name + '.');
                        // console.log('Email: ' + response.email);
                        // 在這裡處理登入成功的情況，例如發送資料到你的服務器
                        socialLoginHandler('facebook', response.email, response.name, '');
                    });
                } else {
                    console.log('User cancelled login or did not fully authorize.');
                }
            }, {
                scope: 'email'
            }); // 請求 email 權限
        }
    }, '.facebookAccLogin');

};

// 加載 Facebook SDK
(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/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


/**************FB login API****************/

// function fbLogin() {

//     FB.login(function(response) {
//         if (response.authResponse) {
//             getInfoAPI();
//         } else {
//             alert("登入失敗!");
//         }
//     }, {
//         scope: 'email'
//     });

// }


// window.fbAsyncInit = function() {
//     FB.init({
//         appId: '577902632718891', //App ID
//         //channelUrl : '//yourdomain.com/channel.html',//Channel File
//         status: true, //check login status
//         cookie: true, //enable cookies to allow the server to access the session
//         xfbml: true, //parse XFBML
//         version: 'v3.2'
//     });
// };

// (function(d, s, id) {
//     console.log(id);
//     var js, fjs = d.getElementsByTagName(s)[0];
//     if (d.getElementById(id)) return;
//     js = d.createElement(s);
//     js.id = id;
//     js.async = true;
//     js.src = "//connect.facebook.net/zh_TW/all.js#xfbml=1&appId=577902632718891";
//     fjs.parentNode.insertBefore(js, fjs);


// }(document, 'script', 'facebook-jssdk'));


// function getInfoAPI() {

//     FB.api('/me?fields=id,name,gender,email', function(response) {
//         socialLoginHandler('facebook', response.email, response.name, response.gender);
//     });
// }


function handleFacebookSignOut() { // facebook 登出
    try {
        if (FB.getAccessToken() != null) {
            FB.logout(function(response) {
                // user is now logged out from facebook do your post request or just redirect
                //alert('user is now logged out from facebook do your post request or just redirect');
            });
        } else {
            // user is not logged in with facebook, maybe with something else
            //alert('ser is not logged in with facebook, maybe with something else');
        }
    } catch (err) {
        // any errors just logout
        //alert('any errors just logout');
    }
}


function socialLoginHandler(sSort, sEmail, sName, sGender) {

    // if (sSort == 'facebook') {
    //     fbLoginWin.close();
    // }

    //processCover(1);
    $.ajax({
        type: "POST",
        url: "/inc/user/socialLoginHandler.php",
        data: {
            sType: 'accLogin',
            sSort: sSort,
            sEmail: sEmail,
            sName: sName,
            sGender: sGender
        },
        dataType: "script",
        success: function(responseTxt) {
            //processCover(0);	
        },
        error: function() {}
    });
}


function socialAccIndetify() {
    if (!$('#pagearea').length) {
        $.ajax({
            url: "/tpl/inc/modal_socialIndetify.php",
            type: 'post',
            //data: $('#login-form').serialize()+"&act=login",
            dataType: 'html',
            success: function(response) {
                $('#info-modal').find('.modal-inner').html(response);
                $('#info-modal').modal('show');
            },
            error: function(request) {

            }
        });

    }
}