$(function() {
    FB.init({
        appId: '164471020241079',
        status: true,
        cookie: true,
        xfbml: true
    });



    setTimeout(function() {
        FB.api('/me', function(response) {
            if (response) {
                $.ajax({
                    url: "/fbconnect/fbconnect.ashx",
                    cache: false,
                    dataType: "html",
                    data: { fbid: response.id },
                    success: function(responsedata) {
                        if (responsedata.length > 0) {
                            $("#aspLogPanel").hide();
                            $("#fbLogPanel").html(responsedata).show();
                        } else {
                            $("#aspLogPanel").show();
                            $("#fbLogPanel").hide();
                        }
                    }
                })
            }
        });
    }, 1000);


    function facebookLogOut() {
       
        /*
        Faccio controllo se è anche loggato su facebook altrimenti la function(response)
        non funziona e si esce
        */
        var logout = false;
        FB.getLoginStatus(function(response) {
            if (response.session) {
                // logged in and connected user, someone you know
                FB.logout(function(response) {
                    if (response) {
                        logOutSito();
                        logout = true
                    }
                });

            } else {
                logOutSito();
                logout = true;
            }
        });
        //nel caso non lo abbia fatto precedentemente

        if (logout == false) {
            logOutSito();
        }

        /*
        Mds 18/11/2010 commentato e inserito il controllo se è loggato su facebook
        perchè andava in errore
        */
        //		FB.logout(function(response) {
        //			if (response) {
        //				$.ajax({
        //					url: "/fbconnect/fbconnect.ashx",
        //					cache: false,
        //					dataType: "html",
        //					data: {logout: 1},
        //					success: function(responsedata){
        //						location.href="/"
        //					}
        //				})
        //			}
        //		});
    }

    function logOutSito() {
        $.ajax({
            url: "/fbconnect/fbconnect.ashx",
            cache: false,
            dataType: "html",
            data: { logout: 1 },
            success: function(responsedata) {
                // 2010.11.25 Deve fare il refresh della pagina corrente e non andare in home
                // location.href = "/";
                window.location.reload();
            }
        })

    }

    $("#fblogout").live("click", function() {

        facebookLogOut()
    })

});
