
  
var FBMConfig = {
	appIDs: {'localhost':'d61f9187fea6e9ad5b8767271d7ab5c1','deadspace.alpha.ea.com':'f2b2e99f7649a796b957f195617d4109',
			'deadspace.beta.ea.com':'6efa49ac24350fa34a024b421190b02b','hs.lizwarner.com':'06c3062e31f2301c33766d0a9e14fcd6',
			'tony.lizwarner.com':'a75ee0af315a40b223fe08f201ca3ff9','deadspace.ea.com':'11291158f25b70c3f38cf2749e962cfb'}, 
    //connectFile: 'fbconn/xd_receiver.html', // default for testing. this file needs to be relative to the app root
    //appRootURL: 'http://myhouse.lizwarner.com:8090/', // default for testing. this belongs to "generic app"
    debug: false,
    //sequencer: null,  
    limit: 5,
    //haveLogin: false,
    //haveRealLogin: false,
    wallposts: null,
    wallindex: 0,
    typewriter: null,
    wallLength: 0,
    wall: {'message':'loading...'}
};


/**
 * FBMwallPretties helper function to avoid cut-and-paste code, as wall posts are loaded 2 ways
 * used in callbacks, so not in object scope
 * @param item the actual post with all its data
 * @param likeselem dom element to be populated 
 * @param imgelem dom element to be populated if applicable
 * @param timeelem dom element to be populated 
 * @param shareelem dom element to be populated if applicable
 * @return  void 
 */


function FBMwallPretties(item,likeselem,imgelem,timeelem,shareelem,commentselem) {
	var pers = 'people';
	var plur = '';
	// do the "likes"
	
	if(item.likes.count == 1) {
		pers = 'person';
		plur = 's';
	}
	likeselem.innerHTML = '<a href="http://www.facebook.com/deadspace" target="_blank">' + item.likes.count + '</a> ' + pers + ' like' + plur + ' this'	

	// do comments
	var comcount = 0;
	if(item.comments && item.comments.count) {
		comcount = item.comments.count;
	}
	if(commentselem) {
		commentselem.innerHTML = ' <a href="' + item.permalink + '" target="_blank">View All ' + comcount + ' Comments</a>';
	}
	// do the post time
	var date = new Date(item.created_time*1000);
	
	// ref: http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3 (there must be a smarter way -LW)
	var m_names = new Array("January", "February", "March", 
	"April", "May", "June", "July", "August", "September", 
	"October", "November", "December");
	var curr_hour = date.getHours();
	var a_p = '';
	if (curr_hour < 12) { a_p = "am";  }
	else { a_p = "pm"; }
	if (curr_hour == 0) { curr_hour = 12; }
	if (curr_hour > 12) { curr_hour = curr_hour - 12; }
	// end probably-very-dumb section. -LW
	
	timeelem.innerHTML = m_names[date.getMonth()] + ' ' + date.getDate() + ' at ' + curr_hour + a_p;
	
	// do the image if applicable
	if(item.attachment && item.attachment.media && item.attachment.media[0] && item.attachment.media[0].type && item.attachment.media[0].src) {
			var theImgUrl = item.attachment.media[0].src; // handle relative URLs in Facebook images and avoid safe_image.php entirely
			if(theImgUrl.indexOf('safe_image.php') != -1) {
				theImgUrl = unescape(theImgUrl.substring(theImgUrl.indexOf('url=') + 4));
			}
		imgelem.innerHTML = '<img src="' + theImgUrl + '" width="90"/>';
	// another common kind of image (swf icon)	
	} else if (item.attachment && item.attachment.media && item.attachment.media[0] && item.attachment.media[0].type
			 && item.attachment.media[0].type == 'swf' && item.attachment.media[0].swf && item.attachment.media[0].swf.preview_img ) {
		imgelem.innerHTML = '<img src="' + item.attachment.media[0].swf.preview_img + '" width="130"/>';
		
	} else {
		imgelem.innerHTML = '';
	}
	$(imgelem).fadeIn('slow', function() { });
    
}


// Facebook Adapter object


var FBManager = {

	/**
	 * enable debug mode (sets a bunch of console log messages with exceptions and warnings)
	 *
	 * @return void
	 */
	
    debugOn: function() {
	   FBMConfig.debug = true;
    },

	/**
	 * disable debug mode
	 *
	 * @return void
	 */
	
    debugOff: function() {
	   FBMConfig.debug = false;
    },

	/**
	 * write to console log if debug is true
	 *
	 * @param  message string
	 * @return void
	 */
	
    debugLog: function (message) {
	  if(FBMConfig.debug) {	
		console.log(message);
	  }
    },

	/**
	 * get comments from ORC's cache
	 *
	 * @param  textelem  populates with comment text
	 * @param  personelem populates with name
	 * @param  numelem populates with number of commenets
	 * @param  object_id fb object to comment on 
	 * @return void
	 */

	getCachedComments: function(textelem,personelem,numelem,object_id) {
		$.getJSON('/en_US/facebookcomments?object_id=' + object_id, function(data) {
		  var len = data.length;
		  var showtext = '';
		  if(data[len - 1].text) {
			 showtext = data[len - 1].text;
		  }
		  //textelem.html('"' + showtext + '"');
		  FBMConfig.commentIndex = 0;
		  var index = len -1;
		  var newDate = new Date();
		
		  window.setInterval(function() { 
			if( textelem.is(':visible') ) {
			 index -= 1;
			 if (index < 0) { index = len - 1; } 
			   var thisComment = data[index].text;
			  // truncate long-ass comments
			   if (thisComment.length > 220) {
			 	  thisComment = thisComment.substring(0,220) + '...';
			   }
					
			 if(data[index].text) { textelem.html('"' + thisComment + '"'); 
			     textelem.hide();
			     personelem.hide();
				 personelem.html('<fb:name uid="' + data[index].fromid + '" linked="true">Facebook User</fb:name>');
				 FB.XFBML.parse(document.getElementById('postername'));
			     personelem.fadeIn('slow',function(){});
				 textelem.fadeIn('slow',function(){});
				 newDate.setTime( data[index].time *1000 );
				var m_names = new Array("January", "February", "March", 
				"April", "May", "June", "July", "August", "September", 
				"October", "November", "December");
				 $('#commentdate').html(m_names[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear());
			 }
			} // end if visible
		  },7000); // end setInterval
		  numelem.html(len);
		  personelem.html('<fb:name uid="' + data[len -1].fromid + '" linked="true">Facebook User</fb:name>');
		// @todo Liz see if this parse call is needed with new api
		  FB.XFBML.parse(document.getElementById('postername'));
		});
	},
	
	/**
	 * parse an arbitrary dom element
	 * @param element to populate
	 * @return  void (this is an asynchronous method and can't return directly to calling script)
	 */
	
	parseElem: function(elem) {
		FB.XFBML.parse(elem);
	},
	
	

	
	/**
	 * get number of fans
	 * @param elem dom element to be populated
	 * @param pageId
	 * @return  void (this is an asynchronous method and can't return directly to calling script)
	 */
	
	getFanCount: function(elem,pageID) {
		// @todo Liz test this refactoring 
		
		FB.api(
		  {
		    method: 'fql.query',
		    query: "select fan_count from page where page_id  = " + pageID
		  },
		  function(response) {
			var data = 0;
			if(response && response[0] && response[0].fan_count) {
				data = response[0].fan_count;
			}
			elem.innerHTML = data + 'people are fans of this page';
		  });
	},
	
	/**
	 * get number of people who like an object (e.g. a video) // 1384161211719 is a test vid with people who like it
	 * @param elem dom element to be populated
	 * @param objectID
	 * @return  void (this is an asynchronous method and can't return directly to calling script)
	 */
	
	getLikes: function(elem,objectID) {
		// now get the wall posts no matter what
	    FB.api(
	      {
	        method: 'fql.query',
	        query: "SELECT user_id from like where object_id = '" + objectID + "'"
	      },
	      function(response) {
			   if(response && response.length) {
					data = response.length;
				} else {
					data = 0;
				}
			elem.innerHTML = data; 
		  });
	},
	

	/**
	 * get admin+fan posts from a FB fan page
	 * @param i index into pre-loaded post array
	 * @param likeselem dom element to load with people-like-this data
	 * @param timeelem dom element to load with created_time
	 * @param shareelem dom element to load with share link
	 * @return text of post
	 */
	
	getWallPost: function(i,likeselem,imgelem,timeelem,shareelem,commentselem,setindex) {
		if(i < 0) {
			i = FBMConfig.wallLength + i;
		} else if (i >= FBMConfig.wallLength) {
			i = i % FBMConfig.wallLength;
		}
		if(setindex) {
			FBMConfig.wallindex = i;
		}
		var ret = FBMConfig.wall[i].message;
		// now populate all the "likes, image, share this" stuff
		FBMwallPretties(FBMConfig.wall[i],likeselem,imgelem,timeelem,shareelem,commentselem);
		return ret; // returning this one for the typewriter widget
	},
	
	/**
	 * get admin+fan posts from a FB fan page
	 * @param pageID numeric string (198819371999 is the id for the Dead Space 2 fan page)
	 * @param elem dom element to be populated with results once they come in
	 * @param emptyMessage string to show if no results
	 * @param limit int query limit
	 * @param likeselem dom element to be populated 
	 * @param imgelem dom element to be populated if applicable
	 * @param timeelem dom element to be populated 
	 * @param shareelem dom element to be populated if applicable
	
	 * @param emptyMessage message to display if there is no data
	 * @return  void (this is an asynchronous method and can't return directly to calling script)
	 */
	
	getPageStream: function(pageID,elem,emptyMessage,limit,likeselem,imgelem,timeelem,shareelem,commentselem) {
		$.getJSON('/en_US/facebookcomments?object_id=pagedefault', function(response) {
			var data = '';
				if(response.length >= 1) {
					for(var j=0;j<response.length;j++) {
						var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
					  	response[j].message = response[j].message.replace(exp,"<a target='_blank' href='$1'>$1</a>");
					}
					FBMConfig.wall = response;
					
					FBMConfig.wallLength = response.length;
					$("#fbwallcontent").html(response[0].message);
					// now populate all the "likes, image, share this" stuff
					FBMwallPretties(response[0],likeselem,imgelem,timeelem,shareelem,commentselem);
					$('#wallcounter').html((FBMConfig.wallindex + 1) + '/' + FBMConfig.wallLength);
					$('#wallcounter3').html('1/' + FBMConfig.wallLength);
					
				} else {
					FBMConfig.wall = new Array();
					FBMConfig.wallLength = 0;
					$("#fbwallcontent").html('No Comments Available');	
				}

		});
	}
	

};

//////////////////// only quiz functions after this point


function inviteFriends() {
	var add = {
	  method: 'fbml.dialog',
	  display: 'dialog',
	  fbml:  '<fb:request-form method="get" action="http://' + document.domain + ':' + location.port + '/home#flash/mediaid=beat2swfquiz-20100610015716783" content=\'Take the quiz <fb:req-choice url="http://' + document.domain + ':' + location.port + '/home#flash/mediaid=beat2swfquiz-20100610015716783" label="Confirm" />\' type="game" invite="true" style="width:200px;">' +
	    '<div class="clearfix" style="padding-bottom: 10px;">' +
	      '<fb:multi-friend-selector condensed="false" cols="4" actiontext="Invite Friends" rows="4" />' +
	    '</div>' +
	  '</fb:request-form>' 
   };

	FB.ui(add, showQuizResultCallback);
//	FB.ui(add, function() {   });
}

function someOmnitureProbably() {
	// do nothing for now
}

// This function returns the appropriate reference,
// depending on the browser.
// currently also rolled into showQuizResult in case that solves the fb callback scoping weirdness.
function getFlexApp(appName)
{
  if (navigator.appName.indexOf ("Microsoft") !=-1)
  {
    return window[appName];
  }
  else
  {
    return document[appName];
  }
}


function showQuizResult()
{
	var app = '';
	var appName = 'FB_Quiz';
	if (navigator.appName.indexOf ("Microsoft") !=-1)
    {
      app =  window[appName];
    }
    else
    {
     app = document[appName];
    }
	app.gotoResult(); 
}

var showQuizResultCallback = this.showQuizResult.bindTo(this);

function promptPerms() {
 FB.getLoginStatus(function(response) {
	var session = FB.getSession();

	if(!session) { // no session. force a login, check perms
  	  FB.login(function(response) { 
	  		if (response && response.session) {
	    		  if (response && response.perms) { 
					// do nothing
	    		  } else {
		     	       FB.login(someOmnitureProbably(), {perms:'read_stream,publish_stream'});
		          } 
	  		} 

		},{perms:'read_stream,publish_stream'}); // end call to FB.login
  } else { // have a session, check perms
        if(url.indexOf('publish_stream') != -1) {
		FB.api(
    		{
      			method : 'Users.hasAppPermission',
      			ext_perm : 'publish_stream'
    		},
    		function(response) { 
      		if(!response || (response && response != 1)) { // we have no perms, force the perms dialog
			FB.login(function(){ }, {perms:'read_stream,publish_stream'});
      	        }});
      } //end if no publish_stream perm visible
  } // end else (have session, check perms)
 }); // end getloginstatus
} // end function


function getQuizResult() {
	// we must be loading or re-loading. time to make sure the user is logged in. 
	var nameEQ = 'quizusertype=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) { if(c.substring(nameEQ.length,c.length) == 'X') { promptPerms(); } return c.substring(nameEQ.length,c.length);}
	}
	// default if the cookie was somehow not set
	promptPerms();
	return 'X';
}

function setQuizResult(type) {
	document.cookie = 'quizusertype=' + type + '; expires=Thu, 2 Aug 2020 20:00:00 UTC; path=/';
}

function wallPost(type) {
	var ptype = 'Champion of Action';
	var timage = 'http://ll.assets.ea.com/nawp/na/u/f/GPO/eagames/deadspace/deadspace2/061510/quiz/championofaction.jpg';
	var desc = 'You\'re a resourceful person with extremely strong convictions! The Church of Unitology requires focused individuals like you are prepared to take action at a moment\'s notice, helping us expand the good work of Michael Altman. Join the church and embark on a path of adventure. It\'s your destiny.';
	
    if(type == 'L') {
	   ptype = 'Paragon of Loyalty';
	   timage = 'http://ll.assets.ea.com/nawp/na/u/f/GPO/eagames/deadspace/deadspace2/061510/quiz/paragonofloyalty.jpg';
	    desc = 'Not everybody likes to rock the boat! That\'s OK. Decent, hardworking and respectful individuals like you make up most of our congregation. It\'s through our unified efforts that we prepare for that great and holy day&mdash;The Convergence. Unitology is the clearest path to being part of something wonderful. (and enjoying life after death!).';
	} else if (type == 'E') {
		ptype = 'Master of Communication';
		timage = 'http://ll.assets.ea.com/nawp/na/u/f/GPO/eagames/deadspace/deadspace2/061510/quiz/masterofcommunication.jpg';
		desc = 'You\'re certainly equipped with quick wits and a gift for gab. Your social skills will make you an indispensible member of our congregation. As Unitologists, we believe humanity will one day come together as a holy unified force. It\'s like we\'re throwing the biggest party ever&mdash;and you\'re going to be one of the esteemed emcees!';
	}

		var publish = {
		  method: 'stream.publish',
		  message: '',
		  attachment: {
		    name: ptype,
		    description: (
		      desc
		    ),
		    href: 'http://apps.facebook.com/discoverquiz',
		    "media": [
                {
                    "src":  timage,
					 "type" : 'image',
                    "href": "http://deadspace.ea.com" 
                } 
            ]	
		  },
		  action_links: [
		    { text: 'Discover Your Potential', href: 'http://apps.facebook.com/discoverquiz' }
		  ],
		  user_prompt_message: 'Publish Your Results!'
		};

		FB.ui(publish, someOmnitureProbably());
}



