var button;
var userInfo;

window.fbAsyncInit = function() {
    FB.init({ appId: '213401402064491', 
        status: true, 
        cookie: true,
        xfbml: true,
        oauth: true});

   function updateButton(response) {
        button       =   document.getElementById('fb-auth');
        userInfo     =   document.getElementById('user-info');

        if (response.authResponse) {
            fqlQuery( false ); // refresh session_data
//            alert('#');
            //user is already logged in and connected
            fb_showLoader(true);
            FB.api('/me', function(response) {
                fb_showLoader(false);
                
                // check user fb_uid
                var query       =  FB.Data.query('select uid from user where uid={0}', response.id);
                query.wait(function(rows) {
                    fb_redirect(rows, false);
                 });
            });
        } else {
            $('#facebook_btn').show();
            //user is not connected to your app or logged out
            button.onclick = function() {
                fb_showLoader(true);
                FB.login(function(response) {
                    if (response.authResponse) {
                        FB.api('/me', function(info) {
                            login(response, info);
                        });	   
                    } else { //user cancelled login or did not grant authorization
                        fb_showLoader(false);
                    }
                }, {scope:'email,user_birthday,user_about_me'});  	
            }
        }
    }

    // run once with current status and whenever the status changes
    FB.getLoginStatus(updateButton);
    FB.Event.subscribe('auth.statusChange', updateButton);	
};
(function() {
    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 fb_redirect(rows, redirect) {
//    alert(redirect);
    $.post("ajax_fb_uid.php", {
        uid: rows[0].uid
        },
        function(data) {
            if ( data == '1' ) { // if fb_uid is already in db
                $('#fb-auth').click(function() {
                    self.location.href="index.php?login=true&fb_login=true";
                });
                if ( redirect ) {
                    self.location.href="index.php?login=true&fb_login=true";
                }
            }
            else {
                $('#facebook_btn').addClass('facebook_btn_register');
                $('#fb-auth').click(function() {
                    self.location.href="index.php?spshow=register";
                });
                if ( redirect ) {
                    self.location.href="index.php?spshow=register";
                }
            }
            $('#facebook_btn').show();
        }
    );
}

function login(response, info){
    if (response.authResponse) {
        var accessToken                                 =   response.authResponse.accessToken;
//        userInfo.innerHTML                             = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
//                                                         + "<br /> Your Access Token: " + accessToken;
        fb_showLoader(false);
        fqlQuery( true );
    }
}

function fqlQuery( redirect ){ // get all fb-data and save it with ajax into our session 
    fb_showLoader(true);
    FB.api('/me', function(response) {
        fb_showLoader(false);
        //http://developers.facebook.com/docs/reference/fql/user/
        var query       =  FB.Data.query('select uid, first_name, last_name, sex, birthday_date, email, hometown_location from user where uid={0}', response.id);
        query.wait(function(rows) {
            $.post("ajax_fb.php", { 
                uid: rows[0].uid,
                first_name: rows[0].first_name, 
                last_name: rows[0].last_name, 
                sex: (rows[0].sex!= undefined ? rows[0].sex : ""), 
                image: rows[0].pic_small,
                birthday_date: rows[0].birthday_date,
                email: rows[0].email,
                hometown_location: rows[0].hometown_location
                }, 
                function(data) { // redirect to register-page
//                    alert(data);
//                   self.location.href="index.php?spshow=register";
                    fb_redirect(rows, redirect);
                }
            );
         });
    });
}

function fb_showLoader(status){
    if (status)
        document.getElementById('loader').style.display = 'block';
    else
        document.getElementById('loader').style.display = 'none';
}
