/**
 * Facebook feed publishing API
 */
FbPublish = {
	
	/**
	 * After registering template bundles on the console on Facebook
	 * developer's page, the template bundles IDs should be added here
	 * and could be attached to a user action in order to publish  
	 */
	templateBundleIds: {
		love: 137441520211,
		tag: 137441520211,
		createLayout: 137441520211,
		friendsWall: 139035750211,
		ownWall: 137441520211,
		selfWall: 93576753827,
		otherWall: 93576753827
	},
	
	/**
	 * Partner Ids to keep track of the action that led to the toolbar downloads
	 */
	partnerIds: {
		love: "Zkzeb842",
		tag: "Zkzeb842",
		createLayout: "Zkzeb842",
		friendsWall: "Zkzeb841",
		ownWall: "Zkzeb840",
		notify: "Zkzeb843"
	},
	
	/**
	 * returns the partnerId query params
	 */
	getPartnerId: function(action) {
		var parentId = (parentPtnrVal != null && parentPtnrVal.length > 0) ? parentPtnrVal : "ZKxdm030"; 
		return "partner="+FbPublish.partnerIds[action]+"_"+parentId;
	},
	
	/**
	 * verbs for template data 
	 */
	 verbs: {
	 	love: "loved",
	 	tag: "tagged",
	 	createLayout: "made",
	 	ownWall: "posted",
	 	friendsWall: "sent",
	 	selfWall: "took",
	 	otherWall: "took"
	 },
	
	/** 
	 * Publishes a story to the profile of users identified by the array
	 * of 'targetIds'. If targetIds is null, it publishes to the current
	 * user's profile (mini-feed or Wall). For more info on args, go to
	 * http://wiki.developers.facebook.com/index.php/JS_API_M_FB.Connect.ShowFeedDialog 
	 */
	publishFeed: function (asset, targetIds, body, feedStorySize, requireConnect, callback) {
		// check user's feed settings to see if the user has agreed to publish
		// feed for this action
		var feedType = asset.action == "ownWall" ? "love" : asset.action;
		if (checkFeedSettings(feedType)) {
			if (FbPublish.isWithinAllowedPublishCount()) {
				var templateData = FbPublish.getTemplateData(asset);
				try {
					FB.Connect.showFeedDialog(FbPublish.templateBundleIds[asset.action], templateData, targetIds, body, 
					feedStorySize, requireConnect, function(exception) {
						if (exception) {
							FwpConnect.logError("Facebook", "FB.publish:"+asset.action, exception);
						}
						FbPublish.updatePublishCount();
						callback();
					});
				}
				catch (exception) {
					FwpConnect.logError("Facebook", "publish:"+asset.action, exception.message || exception);
				}
			}
			else {
				// ignore warning message for other publish requests 
				if(asset.action == "ownWall" || asset.action == "friendsWall") {
					alert("Sorry, you have exceeded the daily Facebook feed posting limits.");
				}
			}
		}
		else {
			// user has set not to publish for this action, so just complete this 
			// api call by calling the callback()
			callback();
		}	
	},
	
	/**
	 * Generates the template data - populates all template tokens with appropriate data
	 * For more info - http://wiki.developers.facebook.com/index.php/Template_Data
	 */
	getTemplateData: function(asset) {
		var clickHere = "<a href='"+asset.topCatUrl + ((asset.topCatUrl.indexOf("?") != -1) ? "&"+FbPublish.getPartnerId(asset.action) : 
			"?"+FbPublish.getPartnerId(asset.action)) + "&theme=fcbk'>Click here</a>";
		var clickHereOneLiner = "<a href='"+asset.assetUrl + ((asset.assetUrl.indexOf("?") != -1) ? "&"+FbPublish.getPartnerId(asset.action) : 
			"?"+FbPublish.getPartnerId(asset.action)) + "&theme=fcbk'>Click here</a>";
		var imageHref = asset.assetUrl + ((asset.assetUrl.indexOf("?") != -1) ? "&"+FbPublish.getPartnerId(asset.action) : 
			"?"+FbPublish.getPartnerId(asset.action)) + "&theme=fcbk";
		var templateData;
		
		if( asset.type == 'Quiz' ) {
			templateData =  {
				"noun": asset.quizName,
				"result": asset.quizResult,
				"blurb": asset.quizBlurb,
				"action-link": imageHref
			};
		} else {
			templateData =  {
				"verb": FbPublish.verbs[asset.action],
				"noun": asset.type,
				"where": (asset.action == "ownWall") ? "to their wall" : "at <a href='http://www.webfetti.com/home.jhtml?theme=fcbk&"+FbPublish.getPartnerId(asset.action)+"'>Webfetti</a>",
				"superfetti": "at <a href='http://apps.facebook.com/superfetti/'>Superfetti</a>",
				"click-here": clickHere,
				"click-here-one-liner": clickHereOneLiner,
				"do-what": (asset.action == "createLayout") ? "make" : "post",
				"image-section": asset.imageSection,
				"action-link-text": "Get this "+asset.typeForActionLink+" at Webfetti.com!",
				"action-link": imageHref
			};
		}
		//console.debug(asset.type + ' ' + asset.action + ' ' + FbPublish.verbs[asset.action] + ' ' + templateData["click-here-one-liner"]);
		if (asset.imagesRequired) {
			templateData["images"] = [{"src":asset.imageSrc, "href":imageHref}];
		}
		else {
			templateData["video"] = {
				"video_src": asset.swfSrc,
				"preview_img": asset.imageSrc
			}
		}
		return templateData;
	},
	
	/**
	 * On some instances webfetti reloads the current page upon some user action. 
	 * (for eg. when user rates an asset without logging in). We store a cookie 
	 * with the rated asset info and if we identify the user as a Facebook user, 
	 * upon reloading the page we tr to publish the rating on to user's FB profile.
	 * Delete the cookie after publishing the feed.
	 * 
	 * update: this method is not used for posting now(3/6/09).
	 * 
	 * @deprecated  
	 */ 
	publishIfPending: function() {
		var fbPublishCookie = getCookie("fb_publish");
		if (fbPublishCookie && fbPublishCookie.length > 0 ) {
			if (FbPublish.isWithinAllowedPublishCount()) {
				var cookieData = fbPublishCookie.parseJSON();
				// is the posting was to be done on friends' wall?
				if (cookieData.friendsWall) {
					var assetData = ObjectToJSONString(cookieData.assetData);
					window[cookieData.friendsWallCallback].apply(this, new Array(assetData));
					FwpConnect.deleteCookie("fb_publish");
				}
				// is it on user's own wall?
				else {
					//console.debug( "cookie data: " + cookieData );
					if (FwpConnect.networks.facebook.loggedIn) {
						FbPublish.publishFeed(cookieData, null, null, FB.FeedStorySize.full, FB.RequireConnect.promptConnect, function() {
							FwpConnect.deleteCookie("fb_publish");
						});
					}	
				}
			}
			else {
				alert("Sorry, you have exceeded the daily Facebook post limits.");
				FwpConnect.deleteCookie("fb_publish");
			}				
		}
	},
	
	/**
	 * Retrieves friends list for the current logged-in user 
	 * http://wiki.developers.facebook.com/index.php/JS_API_M_FB.ApiClient.Friends_get
	 */  
	getFriends: function(callback) {
		try {
			FB.ensureInit(function(exception) {
				if (exception) {
					FwpConnect.logError("Facebook", "FB.ensureInit", exception);
				}
				try {
					FB.Facebook.apiClient.friends_get(null, function(friendsList, exception) {
						if (exception) {
							FwpConnect.logError("Facebook", "FB.friendsGet", exception);
						}
						callback(friendsList);
					});
				}
				catch (ex) {
					FwpConnect.logError("Facebook", "friendsGet", ex.message || ex);
				}
			});
		}
		catch (exc) {
			FwpConnect.logError("Facebook", "ensureInit", exc.message || exc);
		}
	},
	
	/**
	 * Gets information of friends in the given list for the fields as asked for in 
	 * the comma separated list.
	 * http://wiki.developers.facebook.com/index.php/Users.getInfo
	 */
	getInfo: function(friendsList, fields, callback) {
		try {
			FB.Facebook.apiClient.users_getInfo(friendsList, fields, function(friendsInfo, exception) {
				if(exception) {
					FwpConnect.logError("Facebook", "FB.getInfo", exception);
				}
				callback(friendsInfo);
			});
		}
		catch (e) {
			FwpConnect.logError("Facebook", "getInfo", e.message || e);
		}
	},
	
	/**
	 * Checks if the user is still within the daily limits allowed for publishing.
	 * Users are allowed to publish only upto a preset number of times for now
	 * (max allowed by Facebook is 10 per user per app per day - includes all 
	 * kinds of post a user could make using the app)
	 */
	isWithinAllowedPublishCount: function() {
		var publishCountCookie = getCookie("fb_pub_counter");
		if (publishCountCookie && publishCountCookie.length > 0) {
			var cookieData = publishCountCookie.parseJSON();
			return cookieData.count < 10;
		}
		return true;
	},
	
	/**
	 * Update the publish count and store it in a cookie; if the user clears the 
	 * cookie we lose the count but we are oka with it. We dont want to implement
	 * an elaborate mechanism involving server-side storage for this functionality 
	 */
	updatePublishCount: function() {
		var publishCountCookie = getCookie("fb_pub_counter");
		var dataObj;
		if (publishCountCookie && publishCountCookie.length > 0) {
			var cookieData = publishCountCookie.parseJSON();
			dataObj = {count: (cookieData.count) + 1};
		}
		else {
			dataObj = {count: 1};
		}
		setCookie("fb_pub_counter", ObjectToJSONString(dataObj), new Date(new Date().getTime()+(24*60*60*1000)),"/",null,null,false);
	},
	
	/**
	 * Sends notification to friends 
	 * http://wiki.developers.facebook.com/index.php/JS_API_M_FB.ApiClient.Notifications_send
	 */
	notifyFriends: function(arrFriendIds, message, callback) {
		try {
			FB.Facebook.apiClient.notifications_send (arrFriendIds, message, function(result, exception) {
				// result param will have the comma separated list of recipients
				if (exception) {
					FwpConnect.logError("Facebook", "FB.notify", exception);
				}
				callback();
			});
		}
		catch (exception) {
			FwpConnect.logError("Facebook", "notify", exception.message || exception);
		}
	},
	
	/**
	 * Invite friends dialog generator
	 */
	inviteFriends: function (type, actionUrl, content, apiKey, labelText, actionText, inviteText) {
		var box_fbml = 
			"<fb:fbml>" +
			"<fb:request-form method=\"post\" type=\""+type+"\" action=\""+actionUrl+"\" invite=\"true\" " +
			"content=\""+content+" \<fb:req-choice url='http://www.facebook.com/add.php?api_key="+apiKey+"' label='"+labelText+"'/\>\">" +
			"<fb:multi-friend-selector showborder=\"false\" actiontext=\""+actionText+"\" cols=\"4\">" +
			"</fb:multi-friend-selector>" +
			"</fb:request-form>" +
			"</fb:fbml>";
		var inviteDialog = new FB.UI.FBMLPopupDialog (inviteText, box_fbml);
		inviteDialog.set_placement(FB.UI.PopupPlacement.center);
		inviteDialog.setContentWidth(650);
		inviteDialog.setContentHeight(600);
		inviteDialog.show();
	}
	
};
