
    function createUser(uid, firstName, lastName){
        //this function sends an ajax call to create user, if user already isn't in our database

        $.post("/new/user.php", { 'uid': uid, 'first_name': firstName, 'last_name': lastName },
          function(data){
            //console.log(data);
          }, "html");
    }
    function loggedin(uid, firstName, lastName){
        //common function for both fbc and gfc
        //document.getElementById('mainFrame').src = '/new/home_stage.php';
        document.getElementById('mainFrame').contentWindow.location.reload();
        createUser(uid, firstName, lastName);
    }

    function loggedout(){
        //common function for both fbc and gfc
        Delete_Cookie('loggedingfc', '/', '');
        Delete_Cookie('loggedinfbc', '/', '');
        document.getElementById('mainFrame').src = '/new/home_stage.php';

        document.getElementById('logininfo').style.display      = "block";
        document.getElementById('afterlogininfo').style.display = "none";
        gfcloggedin();

        if (FB.Connect.get_status() == FB.ConnectState.connected )
            fbcloggedin();
    }

    function fbcloggedin(){
        if (isLoggedInByGfc() && !isLoggedInByFbc()) return false;
        //called after user logged in through facebook connect

        var user_box = document.getElementById('afterlogininfo');

        var api = FB.Facebook.apiClient;
        var uid = api.get_session().uid;

        api.fql_query("SELECT first_name, last_name FROM user WHERE  uid=" + uid, function(result, ex) {
            var firstName = result[0]['first_name'];
            var lastName  = result[0]['last_name'];

            user_box.innerHTML =
                "Benvenuto, <b>" + firstName + " " + lastName +  "</b><br /> "
                + 'Sei autenticato tramite Facebook Connect '
                + "<a href=\"javascript:void(0)\" onclick='loggedout(); FB.Connect.logout()'>Scollegati</a>";

            Set_Cookie( 'loggedinfbc', 1, '', '/', '', '' );
            uid     =   "fb-" + uid;
            loggedin(uid, firstName, lastName);
            user_box.style.display   =   "block";
            document.getElementById('logininfo').style.display = "none";
        });
    }

    function gfcloggedin(){
        if (isLoggedInByFbc()) return false;
        //called after user logged in through google friend connect
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest("VIEWER"), "viewer_data");
        req.send(onData);
    }
    
    function onData(data) {
        var viewer_info = document.getElementById('gfc');
        if (data.get('viewer_data').hadError()) {
            google.friendconnect.renderSignInButton({ 'id': 'gfc' });
        } else {
            Set_Cookie( 'loggedingfc', 1, '', '/', '', '' );
            var obj             =   document.getElementById('afterlogininfo');
            obj.style.display   =   "block";
            document.getElementById('logininfo').style.display = "none";

            var viewer = data.get('viewer_data').getData();
            var name   = viewer.getDisplayName().split(" ");
            var fN, lN;

            if (name.length > 2){
                fN  =   name[0] + " " + name[1];
                lN  =   name[name.length - 1];
            }
            else{
                fN  =   name[0];
                lN  =   name[name.length - 1];
            }

            var uid     =   "gf-" + viewer.getId();
            loggedin(uid, fN, lN);

            obj.innerHTML = 'Welcome, <b>' + viewer.getDisplayName() + '</b> ' +
              '<br />You\'re logged in via Google Friend Connect  ' +
              '<a href="javascript:void(0)" onclick="loggedout(); google.friendconnect.requestSignOut();">Sign out</a>';
        }
    };

    function isLoggedInByFbc(){
        //this function checks whether the user is logged in by facebook or not
        if (Get_Cookie('loggedinfbc'))
            return true;
        return false;
    }
    function isLoggedInByGfc(){
        if (Get_Cookie('loggedingfc'))
            return true;
        return false;
    }

    function Set_Cookie( name, value, expires, path, domain, secure ){
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );

        /*
            if the expires variable is set, make the correct
            expires time, the current script below will set
            it for x number of days, to make it for hours,
            delete * 24, for minutes, delete * 60 * 24
         */
        if ( expires )
        {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
            ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
            ( ( path ) ? ";path=" + path : "" ) +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ( ( secure ) ? ";secure" : "" );
    }


    function Get_Cookie( check_name ) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );


            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if ( cookie_name == check_name )
            {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if ( a_temp_cookie.length > 1 )
                {
                    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if ( !b_cookie_found )
        {
            return null;
        }
    }


    // this deletes the cookie when called
    function Delete_Cookie( name, path, domain ) {
        if ( Get_Cookie( name ) ) document.cookie = name + "=" +
            ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }


