(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/all.js#xfbml=1&appId=" + FB_APP_ID;
  //  console.log(js.src);
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

window.fbAsyncInit = function() {
   //  console.log("inside fb init");
    FB.init({
        appId      : FB_APP_ID,
        cookie     : true,
        xfbml      : true,
        oauth      : true
    });
    
    $('#fbBtn').click(function() {
       // console.log("inside fb button");
           FB.login(function(response) {
        //        console.log("inside fb response"+response);
            if (response.authResponse) {
                var accesstoken =   response.authResponse.accessToken;
                loginSuccess(accesstoken);
            }
        }, {
            scope: 'email,public_profile'
        });
    });
};

function loginSuccess(accesstoken)
{
    //console.log("inside loginSuccess");
    //alert("jsdfsdk");exit;
    /** Function to update DB ***/
    FB.api('/me?fields=id,first_name,last_name,email', function(response) {
        $.ajax({
            url: mainUrl + "index/fblogin",
            type: "GET",
            data:{
                user_fbid: response.id,
                user_fbname: response.name,
                user_fname: response.first_name,
                user_middle_name: response.middle_name, 
                user_lname: response.last_name,
                user_email: response.email,
                user_uname: response.username,
                user_location: response.location,
                user_dob: response.birthday,
                user_gender: response.gender,
                access_token:accesstoken
            },
            cache: false,
            success: function (html) {
                //console.log(html);
                if(html == 1) {
                    window.location.href = mainUrl + "index/fbloginredir";
                } else if(html == 2) {
                    alert('User not Approved');
                } else if(html == 3) {
                    alert('User does not exist');
                } else {                    
                    alert('Sorry, an error occurred. Please try again later');
                }
            }
        });
    });
/** Function to update DB Ends ***/
}