$(document).ready(function() {

    //var button;
    var accessToken;

    window.fbAsyncInit = function() {
        FB.init({ appId: '191660134179187',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });

        function updateButton(response) {

            if (response.authResponse) {
                //user is already logged in and connected
                FB.api('/me', function(info) {
                    // login is done
                    $('#mysimpletest').click(function() {
                       ClientAuth();
                    });
                });

            } else {
                //user is not connected to your app or logged out
                $('#mysimpletest').click(function() {
                    ClientAuth();
                });
            }
        }

        // run once with current status and whenever the status changes
        FB.getLoginStatus(updateButton);
        //FB.Event.subscribe('auth.statusChange', updateButton);
    };
    (function() {
        // Add FB Tag
        $('body').append('<div id="fb-root"></div>');
        var e = document.createElement('script');
        e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());

    function SaveClientAuth(response, info) {
        if (response.authResponse) {
            accessToken = response.authResponse.accessToken;
            $.ajax({
                type: "POST",
                url: document.location.protocol + "//www.lxrent.com/loginexecutefacebook.asp?token=" + accessToken,
                //data: dataString,
                success: function() {
                    // On Success: Redirect page
                    window.location = document.location.protocol + "//www.lxrent.com/userhome.asp";
                }
            });
        }
    }


    function ClientAuth() {
        $.blockUI({
            css: { border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5, color: '#fff'
            }
            , message: '<h1><img src="../images/fbfan.png" /> A executar o login...</h1><br/>Os servidores do Facebook podem demorar até 30 segundos a responder. Seja paciente.'
        });

        FB.login(function(response) {
            if (response.authResponse) {
                // user logged in and/or authorized
                FB.api('/me', function(info) {
                    SaveClientAuth(response, info);
                    $.unblockUI();
                });
            } else {
                $.unblockUI();

                //user cancelled login or did not grant authorization
                //accessToken = response.authResponse.accessToken;
                //ClientShare();
            }
        }, { scope: 'email,publish_stream' });
    }

    function GetFacebookUserPicture() {

        FB.api('/me', function(user) {
            if (user.id != null) {
                alert(user.id);
                var image = $('userimage');
                if (image != null) {
                    image.src = document.location.protocol + '//graph.facebook.com/' + user.id + '/picture';
                }
            } else {
                // could not get the pic 
            }
        });
    }

    function CheckFacebookUserIsAppFan() {
        FB.api({ method: 'fql.query', query: 'SELECT uid FROM page_fan WHERE uid=me() AND page_id=' + applicationID }, function(result) {
            if (result.length) {
                // is a fan
                return true;
            } else {
                // is not a fan
                return false;
            }
        });
    }

    function InviteFriendsToApp() {
        FB.ui({ method: 'apprequests',
            message: 'Lxrent - Arrende +',
            app_id: applicationID,
            //name: 'Facebook Dialogs',
            link: 'http://www.lxrent.com',
            picture: '',
            //caption: 'Reference Documentation',
            description: 'description'
            //message: 'Facebook Dialogs are easy!'         
        });
    }
});
