function onLoad() {
    gapi.load('auth2', function () {
        gapi.auth2.init();

        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {
            console.log(gapi.auth2.getAuthInstance().isSignedIn);
            auth2.disconnect();
        });

    });


}

function onFailure(error) {
    console.log(error);
}

function onSignIn(googleUser) {
    $("#googleBtn").attr('disabled', true);

    var profile = googleUser.getBasicProfile();
    console.log("ID: " + profile.getId()); // Don't send this directly to your server!
    console.log('Full Name: ' + profile.getName());
    console.log('Given Name: ' + profile.getGivenName());
    console.log('Family Name: ' + profile.getFamilyName());
    console.log("Image URL: " + profile.getImageUrl());
    console.log("Email: " + profile.getEmail());

    // The ID token you need to pass to your backend:
    var id_token = googleUser.getAuthResponse().id_token;
    console.log("ID Token: " + id_token);

   

    var formData = {
        id_token: id_token,
        company_serial: $('#inputSerial').val()
    }

    $.ajax({
        url: "api/google_signin",
        type: "POST",
        data: formData,
        success: function (data, textStatus, jqXHR) {
            $("#signBtn").attr('disabled', false);
            $("#googleBtn").attr('disabled', false);

            if (data.ret == "yes") {
                var auth2 = gapi.auth2.getAuthInstance();
                auth2.signOut().then(function () {
                    console.log(gapi.auth2.getAuthInstance().isSignedIn);
                    auth2.disconnect();
                    location.href = "/Board/testBoard";
                });

            } else {
                var auth2 = gapi.auth2.getAuthInstance();
                auth2.signOut().then(function () {
                    console.log(gapi.auth2.getAuthInstance().isSignedIn);
                    auth2.disconnect();
                    console.log('User signed out.');
                });
                alert(data.message);

            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $("#signBtn").attr('disabled', false);
            $("#googleBtn").attr('disabled', false);
            var auth2 = gapi.auth2.getAuthInstance();
            auth2.signOut().then(function () {
                console.log(gapi.auth2.getAuthInstance().isSignedIn);
                auth2.disconnect();
                console.log('User signed out.');
            });

            alert('网絡或伺服器发生错误，请稍后重试!');
        }
    });



    return false;
}