/*
 * API key, this should be initialized before any another function in this file is called.
 */
var is_initialized = false;

window.api_key="a39efde9d797cd9929179137d132572e";

var fbconnect_func = function() {  

		facebook_onload(true);
		if (typeof(fbconnect_feed_publish_auth) != 'undefined') {
			fbconnect_feed_publish_auth();
		}

	  };

$(document).ready(function(){fbconnect_func()});

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
    FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
        //FB.FBDebug.logLevel = 4;
        //FB.FBDebug.isEnabled = true;
        FB.Facebook.init(window.api_key, "/fbconnect/xd_receiver.htm");

        window.is_initialized = true;
        callback();
      });
  }
}

/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
function facebook_onload(already_logged_into_facebook) {
  // user state is either: has a session, or does not.
  // if the state has changed, detect that and reload.
  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
          var is_now_logged_into_facebook = session ? true : false;

          // if the new state is the same as the old (i.e., nothing changed)
          // then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
          refresh_page();
        });
    });
}

/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_button_onclick() {

  ensure_init(function() {
	
	set_cookie('c_fblogout', 0, 1, '/', 'forums.cnet.com.au');
	FB.Connect.requireSession(function() { window.location.reload(true); }); return false;

    });

    return false;
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page(location) {
  if(location == null){
    window.location.reload(true);
  }else{
    window.location = location;
  }
}

/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission) {
  ensure_init(function() {
    FB.Connect.showPermissionDialog(permission);
  });
}

function facebook_showPermissionDialogCallback(permission, callback) {

   ensure_init(function() {
	FB.Connect.showPermissionDialogCallback=function FB_Connect$showPermissionDialogCallback(permission, callback)
	{
	    FB.Facebook.get_sessionState().waitUntilReady(
        	Delegate.create(null,function(result)
	        {
        	    FB.IFrameUtil.CanvasUtilServer.run(true);
	            var singleton=FB.Connect._singleton;
	            var iframeDom=FB.XdComm.Server.singleton.createNamedHiddenIFrame('dialogContent','','fb_permission_iframe',null);
        	    iframeDom.style.height='173px';
	            singleton._permissionDialog=new FB.UI.PopupDialog('Allow Extended Access?',iframeDom,true,false);
            
        	    iframeDom.src=FBIntern.Utility.getFacebookUrl('www')+'connect/prompt_permission.php'+'?api_key='+FB.Facebook.apiKey+'&v='
                	+FB.Facebook.version
	                +'&next='+encodeURIComponent(singleton._permissionDialog._createCrossDomainClosingLink())
        	        +'&cancel='+encodeURIComponent(singleton._permissionDialog._createCrossDomainClosingLink())
                	+'&channel_url='+encodeURIComponent(FB.XdComm.Server.singleton.get_receiverUrl())
	                +'&ext_perm='+permission;singleton._permissionDialog.show();
                
        	    //GM: call the callback on closing event
	            singleton._permissionDialog.add_closing(
        	        Delegate.create(null,function(closingResult)
                	{
	                    singleton._permissionDialog=null;
        	            if(callback){callback.invoke();}
                	})
	            );
        	    //END modifications
	        })
	    );
	}
    });
}


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" : "" );
}