var asset_for_fb_post = {};
var reload_after_post = false;
var notificationMsg_part1 = "is using Webfetti to send ";
var notificationMsg_part2 = " to friends on Facebook. You can too, <a href=\"http://www.webfetti.com/home.jhtml?";
var notificationMsg_part3 = "\">click here!</a>";
	

// returns asset info extracted from hidden variables in the asset placeholder
function extractAssetData(action) {
	// for smile swfs and gidgets, we dont require images tag while generating 
	// facebook template data see FbPublish.getTemplateData(asset)
	var imagesRequired = true;
	var assetType = "Custom Layouts";
	var assetTypeSingular = "Custom Layout";
		 
	if (action == "createLayout") {
		// if the user has created a layout, we cannot get the image-url of that 
		// layout immediately with the current setup, so we just use a generic
		// image, set up the return json with known layout-editor url and the url
		// to the user's public layouts on the webfetti		
		var url =  "http://ak.webfetti.com/assets/layouts/tn/v1/my/1053/1053121.jpg";
		return {
			"imageSection": "<a href='"+window.location.href+"'><img src='"+url+"' /></a>",
			"imageSrc": url, 
			"type": assetType,
			"typeForActionLink": assetTypeSingular,
			"assetUrl": "http://"+document.location.host + "/user-layouts/MySpace/" + urUserId +".jhtml", // urUserId defined in wf_vars.js
			"topCatUrl": window.location.href,
			"action": action,
			"imagesRequired": imagesRequired
		};
	}

	var assetPath = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[2];
	assetPath = assetPath.substring(1, assetPath.length);
	assetType = assetPath.indexOf("/") != -1 ? assetPath.substring(0, assetPath.indexOf("/")) : assetPath;
	if( assetType == "quizzes" ) assetType = "Quiz";
	assetTypeSingular = assetType.replace(/s$/, "");

	var baseUrl = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[1];
	if (baseUrl.charAt(0) != '/') {
		baseUrl = "/" + baseUrl;
	}
	var topCatUrl = "http://"+document.location.host + baseUrl + "/" + assetType + ".jhtml";

	var actualAssetUrl = $("#asset_display_placeholder_"+asset_for_fb_post.id+" a").attr("href");
	if (!actualAssetUrl || actualAssetUrl.length < 0) {
		var pathToken = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[2];
		actualAssetUrl = "http://"+document.location.host + baseUrl + pathToken;
		if (pathToken.indexOf(".jhtml") == -1) { // if the current page is not favorites page (blendedAsset.tag)
			actualAssetUrl += ".jhtml";
		}
	}
	else {
		actualAssetUrl = "http://"+document.location.host + actualAssetUrl;
	}

	var imageSection = "";
	var imageSrc = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[0];
	var swfSrc = "";
	var assetId = asset_for_fb_post.id;
	if (assetType == 'Gidgets' || (assetType == 'Graphics' && imageSrc.indexOf(".swf") != -1)) {
		// depending on whether it is being published from detials page,
		// or gallery page, set appropriate image and swf sources
		if ($(".asset_rating :hidden").val() && $(".asset_rating :hidden").val().split("|")[3] && $(".asset_rating :hidden").val().split("|")[3] == "true") {
			imageSection = "<fb:swf swfsrc='"+imageSrc+"' "+ "imgsrc='"+imageSrc.replace(".swf", "p.gif")+"' " +
				"imgstyle='float:left' quality='high' loop='false' height='244' width='325'/>";
			swfSrc = imageSrc;
			imageSrc = imageSrc.replace(".swf", "p.gif");
		}
		else {
			imageSection = "<fb:swf swfsrc='"+imageSrc.replace("p.gif", ".swf")+"' "+ "imgsrc='"+imageSrc+"' " +
				"imgstyle='float:left' quality='high' loop='false' height='244' width='325'/>";
			swfSrc = imageSrc.replace("p.gif", ".swf");
		}
		
		imagesRequired = false;
	}
	else if (assetType == 'Smileys' && imageSrc.indexOf(".swf") != -1) {
		if(!$.browser.msie) {
		    imageSrc = "http://smileys.smileycentral.com/cat/" + $("#div_"+asset_for_fb_post.id+" object embed").attr("id") +"p.gif";
		    if (document.location.href.indexOf("/favorites.jhtml") != -1) {
		    	actualAssetUrl = "http://" + document.location.host + $("#asset_display_placeholder_"+asset_for_fb_post.id+" a").attr("href");
		    }
		}
		else {
			imageSrc = "http://smileys.smileycentral.com/cat/" + $("#div_"+asset_for_fb_post.id+" object").attr("name") +"p.gif";
			if (document.location.href.indexOf("/favorites.jhtml") != -1) {
		    	actualAssetUrl = "http://" + document.location.host + $("#asset_display_placeholder_"+asset_for_fb_post.id).parent().attr("href");
		    }
		}
		// the transport swf interprets an ' literally as it should but the fbml needs that to be escaped
		// so I guess for now it might be better to just get rid of it. if you think you have a workaround
		// please change the following line of code.
		var flashvars = "";
		if(!$.browser.msie)
		    flashvars = $("#div_"+asset_for_fb_post.id+" object embed").attr("flashvars").replace(/'/g, "");
		else
			flashvars = $("#div_"+asset_for_fb_post.id+" object > param[name='flashvars']").val().replace(/'/g,"");
		imageSection += "<fb:swf swfsrc='http://smileys.smileycentral.com/cat/F/uitransport_wf2.swf' "+
			"imgsrc='"+imageSrc+"' flashvars='auto=1&"+flashvars+"' "+
			"imgstyle='float:left;width:154;height:110' quality='high' loop='false' height='182' width='130'/>";
		
		if (actualAssetUrl.indexOf("?selectedPath=") == -1) {
			actualAssetUrl = window.location.href + "?selectedPath="+$("#assetPath_"+asset_for_fb_post.id).val();
		}

		swfSrc = "http://smileys.smileycentral.com/cat/F/uitransport_wf2.swf?auto=1&"+flashvars;
		imagesRequired = false;
	}
	else if (assetType == 'Quiz' || assetType == 'Glitter' || (assetType == 'Smileys' && imageSrc.indexOf(".gif") != -1) || 
				(assetType == 'Graphics' && imageSrc.indexOf(".gif") != -1)) {
		swfSrc = "http://ak.webfetti.com/assets/gifLoader.swf?assetUrl="+encodeURIComponent(imageSrc);
		imagesRequired = false;
		
		if (assetType == 'Smileys') {
			if (actualAssetUrl.indexOf("?selectedPath=") == -1) {
				actualAssetUrl = window.location.href + "?selectedPath="+$("#assetPath_"+asset_for_fb_post.id).val();
			}
		}
	}
	else {
        var partnerId = ((actualAssetUrl.indexOf("?") != -1) ? "&" : "?") + FbPublish.getPartnerId(action);
        // don't URL encode the following. Facebook ignores the entire anchor tag 
        // on the imageSection if you do
        var hrefUrl = (actualAssetUrl + partnerId).replace(/'/g, "%27").replace(/,/g, "%2C").replace(/\!/g, "%21").replace(/#/g, "%23");
        hrefUrl = hrefUrl.replace(/\$/g, "%24").replace(/\?/g, "%3F");
        imageSection = "<a href='"+hrefUrl+"'><img src='"+imageSrc+"' /></a>";
        
        if (assetType == 'Cursors') {
			if (actualAssetUrl.indexOf("?selectedPath=") == -1) {
				actualAssetUrl = window.location.href + "?selectedPath="+$("#assetPath_"+asset_for_fb_post.id).val();
			}
		}
	}

	if( assetType == 'Quiz' ) {
		if( action == 'ownWall' ) action = 'selfWall';
		else if( action == 'friendsWall' ) action = 'otherWall';
		var quizName = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[3];
		var quizResult = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[4];
		var quizBlurb = $("#asset_display_placeholder_hidden_"+asset_for_fb_post.id).val().split("|")[5];
		
		asset_for_fb_post = {};
		return {
			"assetId": assetId,
			"imageSection": imageSection,
			"imageSrc": imageSrc,
			"swfSrc": swfSrc,
			"type": assetType,
			"quizName": quizName,
			"quizResult": quizResult,
			"quizBlurb": quizBlurb,
			"typeForActionLink": assetTypeSingular,
			"assetUrl": actualAssetUrl,
			"topCatUrl": topCatUrl,
			"action": action,
			"imagesRequired": imagesRequired
		};
	} else {
		asset_for_fb_post = {};
		return {
			"assetId": assetId,
			"imageSection": imageSection,
			"imageSrc": imageSrc,
			"swfSrc": swfSrc,
			"type": assetType,
			"typeForActionLink": assetTypeSingular,
			"assetUrl": actualAssetUrl,
			"topCatUrl": topCatUrl,
			"action": action,
			"imagesRequired": imagesRequired
		};
	}
}

function fb_init() {
	// facebook post buttons mouseover/mouseout changes
	$(".fb_post_btn, .fb_post_post_wall_btn, .fb_post_send_wall_btn, .fb_post_add_prof_btn").hover( function() {
		var src = $(this).attr("src");
		$(this).attr("src", src.replace('.gif', '_over.gif') );
	}, function() {
 		var src = $(this).attr("src");
 		$(this).attr("src", src.replace('_over.gif', '.gif') );
	});

  // clicking on FB Post button should pop up the modal with options to share the asset
  $(".fb_post_btn").click(function () {
	    log.once("fbpostmodal").profile(false);
	    var aId = $(this).parent().find(":hidden").val().split("|")[0];
	    var aName = $(this).parent().find(":hidden").val().split("|")[2];
	    // is the case for FB Post button on smiley details page
	    if (aId.length == 0) {
	      aId = s_cur_asset_id; // s_cur_asset_id is used in generating copy code
	      aName = $("#smiley_"+aId).attr("title"); // the individual smiley asset div titles are the asset names
	    }
	    load_asset_click(aId,false);
	    log("FB Post Modal for %s (#%d)",aName,aId);
	    var assetHeight = Number($("#assetHeight_"+aId).val());
	    var assetWidth = Number($("#assetWidth_"+aId).val());
	    var assetAspect = -1;
	    if(assetHeight==0) assetAspect = 0;
	    else assetAspect = assetWidth/assetHeight;
	    log("Asset height, width, aspect from product.xml:",assetHeight,assetWidth,assetAspect);
	    var dAssetHeight = $("#asset_"+aId).height();
	    var dAssetWidth = $("#asset_"+aId).width();
	    var dAssetAspect = -1;
	    var bUsingDetectedDimensions = false;
	    if(dAssetHeight==0) dAssetAspect = 0;
	    else dAssetAspect = dAssetWidth/dAssetHeight;
	    log("Detected height, width, aspect:",dAssetHeight,dAssetWidth,dAssetAspect);
	    if((assetHeight==0 && assetWidth==0)||(assetHeight.toString()=="NaN" && assetWidth.toString()=="NaN")){
	      log("Asset height, width not set in product.xml, using detected height, width");
	      assetHeight=dAssetHeight;
	      assetWidth=dAssetWidth;
	      bUsingDetectedDimensions=true;
	    }else if( (assetAspect>1 && dAssetAspect<1) || (assetAspect<1 && dAssetAspect>1)){
	      log.error("Asset height, width set in product.xml are inverted;  swapping them");
	      var t = assetHeight;
	      assetHeight=assetWidth;
	      assetWidth=t;
	    }
	    if(assetWidth > 190 && assetHeight <= assetWidth){
	      log("Width is excessive, scaling down");
	      assetHeight = Math.round((190/assetWidth) * assetHeight);
	      assetWidth = 190;
	    }else if(assetHeight > 190 && assetWidth <= assetHeight){
	      log("Height is excessive, scaling down");
	      assetWidth = Math.round((190/assetHeight) * assetWidth);
	      assetHeight = 190;
	    }else if((window.assetType!=21||bUsingDetectedDimensions) && window.assetType!=2 ){
	      log("Asset is undersized, scaling up");
	      if(assetWidth >= assetHeight){
	        log("Width is largest dimension");
	        assetHeight = Math.round((190/assetWidth) * assetHeight);
	        assetWidth = 190;
	      }else{
	        log("Height is largest dimension");
	        assetWidth = Math.round((190/assetHeight) * assetWidth);
	        assetHeight = 190;
	      }
	    }
	    log("Scaled height, width",assetHeight,assetWidth);
	    var assetPath = $("#asset_display_placeholder_hidden_"+aId).val().split("|")[2];
	    assetPath = assetPath.substring(1, assetPath.length);
	
	    var assetType = assetPath.indexOf("/") != -1 ? assetPath.substring(0, assetPath.indexOf("/")) : assetPath;
	    var mediaSrc = $("#asset_display_placeholder_hidden_"+aId).val().split("|")[0];
	    if (assetType == 'Smileys' && mediaSrc.indexOf(".swf") != -1) {
	      if(!$.browser.msie)
	          mediaSrc = "http://smileys.smileycentral.com/cat/tn/" + $("#div_"+aId+" object embed").attr("id") +".jpg";
	      else
	        mediaSrc = "http://smileys.smileycentral.com/cat/tn/" + $("#div_"+aId+" object").attr("name") +".jpg";
	      $("#fb_post_asset_display").attr("width",100);
	      $("#fb_post_asset_display").attr("height",140);
	    }
	    else if (assetType == 'Gidgets' || (assetType == 'Graphics' && mediaSrc.indexOf(".swf") != -1)) {
	      // depending on whether it is being published from details page,
	      // or gallery page, set appropriate image and swf sources
	      if ($(".asset_rating :hidden").val() && $(".asset_rating :hidden").val().split("|")[3] && $(".asset_rating :hidden").val().split("|")[3] == "true") {
	        mediaSrc = mediaSrc.replace(".swf", "p.gif");
	      }
	      if(assetWidth > 0) $("#fb_post_asset_display").attr("width",assetWidth); else $("#fb_post_asset_display").removeAttr("width");
	      if(assetHeight > 0) $("#fb_post_asset_display").attr("height",assetHeight); else $("#fb_post_asset_display").removeAttr("height");
	    }
	    else {
	      if(assetWidth > 0) $("#fb_post_asset_display").attr("width",assetWidth); else $("#fb_post_asset_display").removeAttr("width");
	      if(assetHeight > 0) $("#fb_post_asset_display").attr("height",assetHeight); else $("#fb_post_asset_display").removeAttr("height");
	    }
    	$("#fb_post_asset_display").attr("src", mediaSrc);
		log("Showing modal");
		asset_for_fb_post = {
			id:aId,assetName:aName
		};

		try {$("#fbPostModal").dialog("open");}catch (e){}
		ckTrk("/clicks/fbpostmodal/open/"+ratings_urchin_path);
	});

	// clicking on 'Post to Wall' should publish the feed to users own wall on facebook
	$(".fb_post_post_wall_btn").click(function() {
    if(tbCheck("fb","",true)){    	
      ckTrk("/clicks/fbposttowall"+s_cur_asset_id);
      $("#fbPostModal").dialog("close");
      var assetDataToPublish = extractAssetData("ownWall");
      if(FwpConnect.networks.facebook.loggedIn) {
        FbPublish.publishFeed(assetDataToPublish, null, null, FB.FeedStorySize.full,
            FB.RequireConnect.promptConnect, function() {});
      }
      else {
        FwpConnect.connect("facebook", function() {
          reload_after_post = true;
          FbPublish.publishFeed(assetDataToPublish, null, null, FB.FeedStorySize.full,
            FB.RequireConnect.promptConnect, function() {
                if(reload_after_post) {
                  reload_after_post = false;
                  window.location.reload();
                }
            });
        });
      }
    }
	});

	// posting to friend's wall
	$(".fb_post_send_wall_btn").click(function() {
		ckTrk("/clicks/fbposttofriendswall/"+s_cur_asset_id);
		//ckTrk("/clicks/fbposttofriendswall/"+ratings_urchin_path);
    if(tbCheck("fb","",true)){
      $("#fbPostModal").dialog("close");
      var assetToPublish = extractAssetData("friendsWall");
      if(FwpConnect.networks.facebook.loggedIn) {
        invokeFriendsChooser(assetToPublish);
      }
      else {
        FwpConnect.connect("facebook", function() {
          reload_after_post = true;
          invokeFriendsChooser(assetToPublish);
        });
      }
    }
	});

	// create modals
  createFbPostModal();
  createFriendsListModal();
  createFeedSettingsModal();
}

/**
 * Check the publish tracker cookie to see if the user has either 
 * "loved" or "tagged" the asset already
 */
function alreadyPublished(assetId) {
	var publishTrackerCookie = getCookie("fb_pub_track");
	if (publishTrackerCookie && publishTrackerCookie.length > 0) {
		var cookieData = publishTrackerCookie.parseJSON();
		if (cookieData[assetId] && (cookieData[assetId] == "love" || cookieData[assetId] == "tag")) {
			return true;
		}
	}
	return false;
}

/**
 * Save the user action in a cookie after publishing the asset
 * User should not be prompted to publish after tagging and 
 * loving the same asset. Cookie is valid for a day.
 */
function saveUserActionOnAsset(publishedAsset) {
	var publishTrackerCookie = getCookie("fb_pub_track");
	var dataObj = {};
	if (publishTrackerCookie && publishTrackerCookie.length > 0) {
		dataObj = publishTrackerCookie.parseJSON();
	}
	var assetObj = publishedAsset;
	dataObj[assetObj.assetId] = assetObj.action;
	setCookie("fb_pub_track", ObjectToJSONString(dataObj), new Date(new Date().getTime()+(24*60*60*1000)),"/",null,null,false);
}

function onNetworkLogin(params, firstTime) {
	// This gets invoked in 2 cases:
	// 1) User clicks connect and submits credentials
	// 2) On FwpConnect.init, the user is connected but there is no cookie for that network
	// In either case a remote call to server is made, cookie is sent in response and set, then this callback invoked.
	$(".regDisplayName").text(params.displayName);
	$(".facebookPhotoUrl").css('background', 'url(' + params.photoUrl + ') no-repeat bottom center');

	// show feed dialog if not present
	/*var settings = getFeedSettings();
	if (!settings) {
		$("#feedSettingsModal").dialog("open");
	} else {*/
		// refresh page to display new state
		window.location.reload();
	//}
}

function onNetworkDisconnect(network) {
	// On FwpConnect.init, network cookie was detected but user is no longer connected to network.
	// Cookie has been deleted and this callback invoked.
	//alert('wf_common - disconnected from ' + network);

	// refresh page to display new state
	window.location.reload();
}

function showPromptConnectDialog(onConnect, onClose, onNo, beforeConnect)
{
  $("#promptConnectModal").dialog("destroy").dialog({
    autoOpen:false,
    draggable:true,
    resizable:false,
    modal:true,
    overlay:{opacity:0,background:"black"},
		dialogClass:"wf_fb_modal",
		position:"center",
		height:"auto",
		width:369,
		show:{effect:"fade",speed:500},
		hide:{effect:"fade",speed:250},
	  close:onClose||function(){}
	 }
  ).show();
  $(".wf_fb_modal .ui-resizable-handle").hide();
  if($.browser.msie)
    $(".wf_fb_modal .ui-dialog-titlebar").hide();
  $("#promptConnectModal #promptConnectButton").click(function() {
  	if (beforeConnect) {
  		beforeConnect();
  	}
  	FwpConnect.connect('facebook', function(params, firstTime) {
      onConnect(params, firstTime);
  	});
  });
  $("#promptConnectNoButton, #promptConnectModal .fb_dialog_cancel_button").click(function() {
  	if (onNo) {
  		onNo();
  	}
    $("#promptConnectModal").dialog("close");
  });
  try {
  	$("#promptConnectModal").dialog("open");
  } catch (e) {
  	if (e.message == 'Invalid argument.') 
  		;// swallow this exception in IE
  	else throw e;
  }
}

function createFeedSettingsModal()
{
  $("#feedSettingsModal").dialog({
    autoOpen:false,
    draggable:true,
    resizable:false,
    modal:true,
    overlay:{opacity:0,background:"black"},
		dialogClass:"wf_fb_modal",
		position:"center",
		height:"auto",
		width:369,
		show:{effect:"fade",speed:500},
		hide:{effect:"fade",speed:250},
		close:function() {
			saveFeedSettings(true, true, true);
			window.location.reload();
		}
	 }
  ).show();
  $(".wf_fb_modal .ui-resizable-handle").hide();
  if($.browser.msie)
    $(".wf_fb_modal .ui-dialog-titlebar").hide();
  $("#feedSettingsModal input.ok").click(function() {
    $("#feedSettingsModal").dialog("close");
  });
  $("#feedSettingsModal .fb_dialog_cancel_button").click(function() {
    $("#feedSettingsModal").dialog("close");
  });
}

function createFbPostModal() {
	$("#fbPostModal").dialog({
		autoOpen:false,
		draggable:true,
		resizable:false,
		modal:true,
		overlay:{opacity:0,background:"black"},
		dialogClass:"wf_fb_modal",
		position:"center",
		height:"auto",
		width:416,
		show:{effect:"fade",speed:500},
		hide:{effect:"fade",speed:250},
		open:function(){
			// moved click tracking to the fb post button click function
			// ckTrk("/clicks/fbpostmodal/open/"+ratings_urchin_path);
		},
		close:function(){
			ckTrk("/clicks/fbpostmodal/close/"+ratings_urchin_path);
		}
	}).show();
	$(".wf_fb_modal .ui-resizable-handle").hide();
  if($.browser.msie)
    $(".wf_fb_modal .ui-dialog-titlebar").hide();
  $("#fbPostModal .fb_dialog_cancel_button").click(function() {
    $("#fbPostModal").dialog("close");
  });
}

function createFriendsListModal() {
	$("#friendsListModal").dialog({
		autoOpen:false,
		draggable:true,
		resizable:false,
		modal:true,
		overlay:{
			opacity:0.0,
			background:"black"
		},
		dialogClass:"wf_fb_modal",
		position:"center",
		height:"auto",
		width:500,
		show:{
			effect:"fade", speed:500
		},
		hide:{
			effect:"fade", speed:250
		},
		open:function(){
			ckTrk("/clicks/friendsListModal/open/"+ratings_urchin_path);
		},
		close:function(){
			ckTrk("/clicks/friendsListModal/close/"+ratings_urchin_path);
		}
	}).show();

	$(".wf_fb_modal .ui-resizable-handle").hide();
  if($.browser.msie)
    $(".wf_fb_modal .ui-dialog-titlebar").hide();
  $("#friendsListModal .fb_dialog_cancel_button").click(function() {
    $("#friendsListModal").dialog("close");
  });

	$("#friends_list_send_btn").click(function() {
		var selectedFriendIds = new Array();
		var idIndex = 0;
		$("#friends_chooser_div li.selected").each(function() {
      selectedFriendIds[idIndex++] = Number($(this).attr("id").split("_")[1]);
    });
//		// insert a default message if the user hasn't entered any
//		if ($("#fbPostUserMessage").val().trim().length > 0) {
//			asset_for_fb_post.message = $("#fbPostUserMessage").val().trim();
//		}
//		else {
//			asset_for_fb_post.message = "Hey, check out these cool "+asset_for_fb_post.type+"!";
//		}

		// recursively post to all selected friends' wall
		var notifyMsg = notificationMsg_part1 + asset_for_fb_post.type + notificationMsg_part2 + FbPublish.getPartnerId("notify") + notificationMsg_part3; 
		// the above line is here for a reason. getPartnerId references 'partnerVal' var which is
		// available only on webfetti pages but this js file is shared in registration too
		var postToFriendsWall = function() {
  			if (selectedFriendIds.length > 0) {
  				var targetIds = new Array(1);
  				targetIds[0] = selectedFriendIds.shift();
  				FbPublish.publishFeed(asset_for_fb_post, targetIds, null, FB.FeedStorySize.full,
			  		FB.RequireConnect.promptConnect, postToFriendsWall);
			  	FbPublish.notifyFriends(targetIds, notifyMsg, function() {});
  			}
  			else {
  				// we should reload the page so that the page is in the right login state (cookies set)
  				// if the user connected to FB just before posting to friends wall
  				if(reload_after_post) {
  					reload_after_post = false;
  					window.location.reload();
  				}
  			}
  		};
		postToFriendsWall();
		$("#friendsListModal").dialog("close");
	});
	$("#friends_list_cancel_btn").click(function() {
		$("#friendsListModal").dialog("close");
    if(reload_after_post) {
      reload_after_post = false;
      window.location.reload();
    }
	});
}

/**
 * Gets the friends list and displays the friend chooser dialog. User is allowed
 * to choose only upto 3 friends at a time due to facebook limitations.
 */
var invokeFriendsChooser = function(assetToPublish) {
	asset_for_fb_post = assetToPublish;
	var fields = 'name,pic_square,current_location';
//  $("#fbPostUserMessage").val("");
  $("#friends_chooser_div").empty().append("<img src='http://ak.webfetti.com/fb/ajax-loader.gif' alt='loading...' style='margin:91px 0 0 217px;'/>");
  ckTrk("/clicks/fbposttofriendswall"+ratings_urchin_path);
  try{$("#friendsListModal").dialog("open");}catch(e){}
	FbPublish.getFriends(function (fInfoList) {
		FbPublish.getInfo(fInfoList, fields, showFriendsChooserDialog);
	});
};

function showFriendsChooserDialog (fList) {
	var tableToInsert = "";
	if (fList.length > 1) {
		// sort friends by name
		fList.sort(function(a, b) {
      if(a.name > b.name) return 1;
      else if(a.name < b.name) return -1;
      else return 0;
		});
	  tableToInsert += getFriendsChooser(fList);
	}

	$("#friends_chooser_div").empty().append(tableToInsert);

	$("#friends_chooser_div li").click(function () {
    if($(this).hasClass("selected"))
      $(this).removeClass("selected");
    else if($("#friends_chooser_div li.selected").length < 3)
      $(this).addClass("selected");
    else{
      var t = this;
      $(t).addClass("error");
      setTimeout(function(){$(t).removeClass("error");},1500);
    }
	});
}

/**
 * Iterates over friends list and extracts name, small pic and location info
 * to build selectable cells for friends chooser dialog
 */
function getFriendsChooser(fList) {
	var tds = "";
  $(fList).each(function(i,fInfo){
    var city = (fInfo.current_location != null && fInfo.current_location.city != undefined) ? getTruncatedLoc(fInfo.current_location.city) : "Undisclosed";
    var url = (fInfo.pic_square != null && fInfo.pic_square.length > 0) ? fInfo.pic_square : "http://static.ak.fbcdn.net/pics/q_silhouette.gif";
    tds +=
      "<li id='friend_"+fInfo.uid+"'><a href='javascript:;'>" +
        "<span class=\"friend_pic_square\" style=\"background-image: url("+url+");\">" +
          "<span>&nbsp;&nbsp;</span>" +
        "</span>" + getTruncatedName(fInfo.name) +
        "<span id=\"location_span\" class=\"friend_location\">" + city + "</span>" +
      "</a></li>";
  });
	return tds;
}

/**
 * Individual names (first/last/middle) that are > 12 chars are
 * truncated to 12 chars + "..." at the end. Facebook does this
 * when they provide the similar friends chooser dialog for invites
 */
function getTruncatedName(name) {
	var nameSplits = name.split(/\s/g);
	var namepart = "";
	if (nameSplits.length > 1) {
		for (var i=0; i<nameSplits.length; i++) {
			if (nameSplits[i].length > 12) {
				namepart += nameSplits[i].substring(0, 9) + "...";
			}
			else {
				namepart += nameSplits[i];
			}
			
			if (i < nameSplits.length-1) {
				namepart += " ";
			}
		}
	}
	else if (name.length > 12){
		namepart = name.substring(0, 9) + "...";
	}
	else {
		namepart = name;
	}
	
	return namepart;
} 

/**
 * truncates location to 12 chars  
 */
function getTruncatedLoc(location) {
	if (location.length > 12) {
		location = location.substring(0, 9) + "...";
	}
	return location;
}

function getFeedSettings() {
	var cookie = getCookie('feed_settings');
	if (!cookie)
		return null;
	return eval('({' + cookie + '})');
}

function saveFeedSettings(tag, love, createLayout) {
	var cookie = 'tag:' + tag + ',';
	cookie += 'love:' + love + ',';
	cookie += 'createLayout:' + createLayout;
	setCookie( "feed_settings", cookie, null, "/", null, null );
}

function checkFeedSettings(action) {

	return true;

// Just return true because we decided not to have feed settings for the user
// and just point them to facebook user's app settings page.

//	var settings = getFeedSettings();
//	if (!settings) {
//		// this shouldn't happen, but default is true for everything, so return true
//		return true;
//	}
//	return settings[action];
}

function shouldPromptToConnect() {
	return !(getCookie("shouldPromptToConnect") == "false");
}

function dontConnectNow() {
	// set a cookie so we don't prompt user to connect again for 24 hours
	setCookie("shouldPromptToConnect",false,new Date(new Date().getTime()+(24*60*60*1000)),"/",null,null);
}