/**
 * 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  
	 */
	 /* dev IDS selfWall: 98415488827,
		otherWall:98415488827*/
	templateBundleIds: {
		love: 137441520211,
		tag: 137441520211,
		createLayout: 137441520211,
		friendsWall: 139035750211,
		ownWall: 137441520211,
		otherWall: 189150965211,
		selfWall: 189150965211,
		fShareGame: 105111718460,
		fPostScore: 105112833460,
		fPostChallengeWin: 105114643460,
		fPostChallengeLoose: 105114193460,
		fSharePick7: 127223608460,
		ZwinkyDefaultPostAvatar: 128323086975,
		ZwinkyHalloweentPostAvatar: 158443051975
	},
	//dev Ids
	//fShareGame: 112234371827
	//fPostScore: 112226841827,
	//fPostChallengeWin: 112520046827,
	//fPostChallengeLoose: 112519336827
	
	//Prod Ids
	//fShareGame: 98310963460
	//fPostScore: 98309583460
	//fPostScore: 97276433460,
	// fShareGame: 97276983460
	/**
	 * 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",
		selfWall: "ZKzeb920",
		otherWall: "ZKzeb921",
		notify: "Zkzeb843",
		local: "ZLzeb001",
		global: "ZVzeb001",
		zwinky: "ZJzeb031"
	},
	/**
	 * returns the partnerId query params
	 */
	getPartnerId: function(action) {
		var parentId = (parentPtnrVal != null && parentPtnrVal.length > 0) ? parentPtnrVal : "ZKxdm030"; 
		if(FwpConnect.product == 'iwon') {
			return "partner="+FbPublish.partnerIds[action]+(parentId != "ZKxdm030"?"_"+parentId:"");
		} else {
			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"
	 },
	/**
	 * this was used, but not anymore... so it just returns true...
	 **/
	checkFeedSettings: function(action) {
		return true;
	},
	/** 
	 * 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_general, 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 (FbPublish.checkFeedSettings(feedType)) {
			if (FbPublish.isWithinAllowedPublishCount()) {
				var templateData = FbPublish.getTemplateData(asset);
				try {
					//moved this close func call from fb_common (only for IWON) 
					//in case FB publish dialog doesnt open then we wouldnt want the modal to close
					if( FwpConnect.product == "iwon" ) {
						$("#fbPostModal").dialog("close");
						$('#replyPostModal').dialog("close");
						
						if(asset.action == "fSharePick7") {
							urchinTracker("/clicks/fbconnect/pick7Invite/post");
						} else {
							urchinTracker("/clicks/fbconnect/gameplayer/post/"+ launchGameObject.gameId + "/" + launchGameObject.signedIn );
						}
					}
					FB.Connect.showFeedDialog(FbPublish.templateBundleIds[asset.action], templateData, targetIds, body_general, 
					feedStorySize, requireConnect, function(exception) {
						if (exception) {
							FwpConnect.logError("Facebook", "FB.publish:"+asset.action, exception);
						} else {
							FbPublish.updatePublishCount();
						}
						callback(asset);
					});
				} catch (exception) {
					FwpConnect.logError("Facebook", "publish:"+asset.action, exception.message || exception);
				}
			}
			else {
				// ignore warning message for other publish requests 
				if( ('ownWall|friendsWall|selfWall|otherWall').match(asset.action) != -1 ) {
					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;
		var templateData;
		var imageHref;
		if( FwpConnect.product == 'iwon' ) {
			clickHere = getDownloadPath();
			imageHref = clickHere;//"http://"+ baseUrl + "?utm_campaign=IWONFB";

			if(asset.action == "fSharePick7") {
				templateData = {
					"play-href": clickHere,
					"action-link-text": "Play Pick 7 Now!"
				};
				asset.imageHref = clickHere;
			} else {
				clickHereText = (asset.action=="fPostChallengeWin" || asset.action=="fPostChallengeLoose")?"Play now":launchGameObject.gameName
				
				templateData = {
					"game": "<a href='"+ clickHere +"' target='_blank'>"+launchGameObject.gameName+"</a>",
					"score": finalScore,
					"score2": challengerScore,
					"click-here": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
					"action-link": imageHref,
					"action-link-text": "IWON Games"
				};
			}
		} 
		else if(FwpConnect.product == 'zwinky'){
			if(asset.type == 'zwinkyImage'){
				var clickHere = getZwinkyDownloadPath();
				var imageHref = clickHere;
				var clickHereText = "Click Here";
				if(asset.imageSrc.indexOf('dev') != -1 ){
					alert("----- The Link: " + asset.imageSrc + " \n\n --has a dev reference, so we are using a non dev reference.");
					asset.imageSrc = "http://assets.zwinky.com/facebook/fbTestImage/zwinkyTestFBImage.jpg" 
				}
				else{
					asset.imageSrc = asset.imageSrc
				}	
				try{
					if(asset.campaign && asset.campaign == "halloween"){
						templateData = {
							"click-here": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
							"click-html": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
							"action-link": imageHref,
							"action-link-text": "Halloween Yourself!",
							"images":[{ "src":asset.imageSrc, "href":imageHref }]
						};
					}
					else{
						templateData = {
							"click-here": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
							"click-html": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
							"action-link": imageHref,
							"action-link-text": "Create Your Cartoon!",
							"images":[{ "src":asset.imageSrc, "href":imageHref }]
						};
					}
				}
				catch(e){
					templateData = {
						"click-here": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
						"click-html": "<a href='"+ clickHere +"' target='_blank'>"+ clickHereText +"</a>",
						"action-link": imageHref,
						"action-link-text": "Create Your Cartoon!",
						"images":[{ "src":asset.imageSrc, "href":imageHref }]
					};
				}
				return templateData;
			}
		}
		else if( asset.type != 'Quiz' ) {
			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>";
			imageHref = asset.assetUrl + ((asset.assetUrl.indexOf("?") != -1) ? "&"+FbPublish.getPartnerId(asset.action) : "?"+FbPublish.getPartnerId(asset.action)) + "&theme=fcbk";
			
			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
			};
		} else if( asset.type == 'Quiz' ) {
			var trkingUrl = asset.assetUrl+"?"+FbPublish.getPartnerId(asset.action)+"&ref=fb";
			clickHere = " <a href='"+ trkingUrl +"'>Click here</a>"
			imageHref = asset.assetUrl;
			templateData =  {
				"noun": "<a href='" + trkingUrl + "'>" + asset.quizName + "</a>",
				"result": "<a href='" + trkingUrl + "'>" + asset.quizResult + "</a>",
				"blurb": asset.quizBlurb,
				"action-link": trkingUrl,
				"click-here": clickHere
			};
		}
		if (asset.imagesRequired) {
			templateData["images"] = [{"src": asset.imageSrc.replace(" ",""), "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 && FwpConnect.product != 'iwon' ) {
			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();
	},
	
	/**
	 * Send email given friend ID, email subject and body. The body can be html or fbml. Atleast one param can not be null.
	 * return results to callback
	 */
	sendEmail: function (arrFriendIds, mail_subject, html_body, fbml_body, callback) {
		try {
		 	FbPublish.checkPermission( "email", false, function(hasPermission) {
				if (hasPermission != 0) {
					try {
						FB.Facebook.apiClient.notifications_sendEmail(arrFriendIds, mail_subject, html_body, fbml_body, function(result, exception) {
							// result param will have the comma separated list of recipients
							if (exception) {
								FwpConnect.logError("Facebook", "FB.notifications_sendEmail", exception);
							}
							callback(result);
						});
					}
					catch (exception) {
						FwpConnect.logError("Facebook", "notifications_sendEmail", exception.message || exception);
					}
				}
			});
		}
		catch (exception) {
			FwpConnect.logError("Facebook", "checkPermission", exception.message || exception);
		}
	},
	
	/**
	 * Check FB App permission. Bypass show Permissions dialog if needed (If you only want to check the status of the permission)
	 */
	checkPermission: function ( permission, showPermDialog, callback ) {
		try {
			FB.Facebook.apiClient.users_hasAppPermission(permission,
				function(result) {
					// prompt offline permission
			        if (showPermDialog && result == 0) {
						// render the permission dialog
			            try {
			            	FB.Connect.showPermissionDialog(permission, callback);
			            }
						catch (exception) {
							FwpConnect.logError("Facebook", "promptPermission", exception.message || exception);
						}
			        } else {
			            // permission already granted or we have bypassed dialog.
			            callback(result);
			        }
				}
			);
		 }
		catch (exception) {
			FwpConnect.logError("Facebook", "FB.Facebook.apiClient.users_hasAppPermission", exception.message || exception);
		}
	}
};