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

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
	if(window.is_initialized) {
    	callback();
  	} else {
    	FB_RequireFeatures(["XFBML","Api"], function() {
        	FB.FBDebug.LogLevel = 1;
        	FB.init("eae6543800ebb4735d0c9a32882ce0e0", "http://snapza.com/files/xd_receiver.html");
        	window.is_initialized = true;
        	callback();
      	});
  	}
}

function showDocAfterRender() {
		
	ensure_init(function() {
   		//FB.XFBML.Host.get_areElementsReady().waitUntilReady (show_fbconnect);	
    });
}


//simple ajax function
function ajax(url, vars, callbackFunction) {
  var request =  new XMLHttpRequest();
  request.open("POST", url, true);
  request.setRequestHeader("Content-Type",
                           "application/x-www-form-urlencoded");

  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      if (request.responseText) {
        callbackFunction(request.responseText);
      }
    }
  };
  request.send(vars);
}



/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * This could be used to do some in-page
 * replacements and avoid a full page refresh.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user
 */
function facebook_session_is_ready(link_to_current_user, callback_url) {
	var user = FB.Facebook.apiClient.get_session() ?
        FB.Facebook.apiClient.get_session().uid :
        null;
	if (!user) {
    	alert("no user found");
    	return;
 	}
	var params;
	if (link_to_current_user) {
    	params += '&link_to_current_user=1';
 	}
	
  	window.location = callback_url;

}



/* Onclick event for login button
 * This will process the session when it becomes available.
 */
function facebook_session_on_ready(link_to_current_user, callback_url) {
	ensure_init(function() {
   		FB.Facebook.get_sessionState().waitUntilReady(function() {
       	facebook_session_is_ready(link_to_current_user, callback_url);
        });
    });
}

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

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  ensure_init(function() {
         FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
     //ge('feed_loading').style.visibility = "hidden";
  });
}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook"
 * is hidden in the "add run" form.
 * This function detects whether the user is logged into facebook but just
 * not connected, and shows the checkbox if that's true.
 *
 */
function facebook_show_feed_checkbox() {
  ensure_init(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if (status != FB.ConnectState.userNotLoggedIn) {
            // If the user is currently logged into Facebook, but has not
            // authorized the app, then go ahead and show them the feed dialog + upsell
            checkbox = ge('publish_fb_checkbox');
            if (checkbox) {
              checkbox.style.visibility = "visible";
            }
          }
        });
    });
}

function fbinvite(){
	var current_location = document.location.href;
	var message = 'Hey, check out <a href=\'http://imgfave.com\'>imgfave.com</a>. It\'s a fun image bookmarking site with lots of amazing art, graphic design, and photography.';
	if(typeof logged_in_username != 'undefined'){
		message += ' \nHere\'s my profile: <a href=\'http://imgfave.com/'+logged_in_username+'\'>http://imgfave.com/'+logged_in_username+'</a>';
	}
	var contents = '<fb:request-form action="http://imgfave.com/invites/facebook?next='+current_location+'"  method="POST"'+
                                 'invite="true"'+
                                 'type="imgfave"'+
                                 'content="'+message+' <fb:req-choice url=\'http://imgfave.com\' label=\'Go to imgfave.com\' />  " >'+
                '<fb:multi-friend-selector showborder="false" cols="4" rows="3" exclude_ids=""   actiontext="Select some friends that you\'d like to invite."></fb:multi-friend-selector>'+
                '</fb:request-form>';
	var dialog = new FB.UI.FBMLPopupDialog('Invite friends to join imgfave', contents, false, true);
	dialog.setContentWidth(630);
    dialog.setContentHeight(510);
    dialog.set_placement(FB.UI.PopupPlacement.topCenter);
	dialog.show();
}

function pprompt(){
	FB.Facebook.apiClient.users_hasAppPermission("offline_access",function(result){
		if (result == 0) {
			FB.Connect.showPermissionDialog('offline_access');
		}else{
			alert('already have offline_access')
		}
	});
}

function checksession(){
	del_cookie('18455ec17407d4c497733bba79c00424_session_key');
	alert("session key: "+FB.Facebook.apiClient.get_session().session_key);
}

function del_cookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
alert("cookie deleted");
}