var domain = window.location.hostname;

var Social = {
	checkinShown:	false,
	type: 			"twitter",  //facebook, getglue,
	defaultText: 	"Enter Text",
	Twitter: {
		popupTitle:			"Post a Tweet",
		timestamp:			0,
		height: 			50,
		width: 				400,
		mobileWidth:		296,
		style: 				"<style>#tweet-box-header{height: 25px;} .btn{float: right;font-size: 12px;height: auto;line-height: auto;margin: 0;padding: 0;text-align: center;width: 100px; border:none;}</style>",
		timeout:			'',
		defaultText: 		"FXM",
		hasCommented:		false
	},
	Facebook: {
		loginStatus:		"",
		subscribedToLike:	false,
		appId: 				"263420703718560",
		mustLikeAppId:		"",
		accessToken: 		"",
		userID: 			"",
		popupTitle: 		"FX Network TV Group on Facebook",
		defaultText: 		"Comment",
		hasCommented:		false
	},
	GetGlue: {
		authInPopup:		true,
		authPopup:			null,
		authPopupTimer:		null,
		authTimerLength:	500,
		userId: 			"",
		popupTitle: 		"You are watching FX Movie Channel",
		defaultText: 		"Check In",
		hasCommented:		false
	}
};

var signed_request = false;

/********************************************************/
/********** ********** ** Social ** ********** **********/
/********************************************************/
function getGetGlueLoginStatus() {
	var temp_cookie = getCookie('gg_glue_userId');

	if((temp_cookie==null || temp_cookie=="")) {
		return false;
	} else {
		Social.GetGlue.userId = temp_cookie;
		
		updateGetGlueLoginStatus();
		
		return true;
	}
}

function updateGetGlueLoginStatus() {
	//change the copy of the button, if you want to
	$('#getglue-login a').html('Check In With GetGlue');

	var url 	= "/fxm/connect/get_glue_user";
	var params 	= {};
	$.post(url, params, function(response) {
		if (response.user_id && response.user_id != "") {
			Social.GetGlue.userId = response.user_id;
			
			message = 'Hello ' + response.username;
			$('#loginBtns p:first').text(message);
			
			//avatar
			var userimg = $("<img />").attr('src', "http://s3.amazonaws.com/adb/"+Social.GetGlue.userId+"/avatar.png").css({width: '75', height: '75'});
			$('#avatar').html(userimg);
		}
		else {
			//GetGlue didn't get authorized
		}
	},'json');
}

function promptGetGlueLogin() {
	var is_logged_in = getGetGlueLoginStatus();

	if(! is_logged_in) {
		if (Social.GetGlue.authInPopup) {
			if (Social.GetGlue.authPopup) {
				Social.GetGlue.authPopup.focus();
			} else {
				Social.GetGlue.authPopup = window.open(GlobalRoot+"connect/login", "getGlueLogin", "status=0, toolbar=0, location=0, meunbar=0, directories=0, resizable=0, scrollbars=0, height=400, width=850");
				Social.GetGlue.authPopupTimer = setTimeout(checkIfGetGlueAuthPopupClosed, Social.GetGlue.authTimerLength);
			}
		}
		else {
			window.location = GlobalRoot+"connect/login";
		}
	} 

	createCommentForm("getglue");
}
function checkIfGetGlueAuthPopupClosed() {
		var temp_cookie = getCookie('gg_glue_userId');
		if ( Social.GetGlue.authPopup.closed || (temp_cookie!=null && temp_cookie!="")) {
			updateAfterGetGlueAuthPopupCloses();
		}
		else {
			Social.GetGlue.authPopupTimer = setTimeout(checkIfGetGlueAuthPopupClosed, Social.GetGlue.authTimerLength);
		}
}
function updateAfterGetGlueAuthPopupCloses() {
	Social.GetGlue.authPopup = null;
	$('#facebook-likebox-container').append($('#facebook-likebox-moveable').detach().removeClass('moved'));
	prepareSocialTabToLoad('#checkin', true);
	prepareSocialTabToLoad('#leaderboard', true);
	updateGetGlueLoginStatus();
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}
function loadGlueList() {
	var url 	= GlobalRoot+"social/get_gg_comments";
	var params 	= {};
	$.post(url, params, function(response) {
		if (response.success == "true") {
			$('#content_getglue').html(response.html);

			setTimeout(loadGlueList, 120000);
		}
		else {
			//GetGlue API call error
		}
	},'json');
}

/***  Twitter  ***/
function getTwitterLoginStatus() {
	twttr.anywhere(function (T) {
		if (T.isConnected()) {
			return true;
		} else {
			return false;
		}
	});
}

function updateTwitterLoginStatus(user) {
	//change the copy of the button, if you want to
	$('#twitter-login a').html('Tweet with Twitter');
	
	//authComplete passed us the data we need
	screenName = user.data('screen_name');
	profileImage = user.data('profile_image_url');
	
	//welcome message
	message = 'Hello ' + screenName;
	$('#loginBtns p:first').text(message);
	
	//avatar
	var userimg = $("<img />").attr('src', profileImage);
	$('#avatar').html(userimg);
	
	createCommentForm("twitter");
}

function promptTwitterLogin()
{
	twttr.anywhere(function (T) {
		T.signIn();
		T.bind("authComplete", function (e, user) {
		    // triggered when auth completed successfully
			updateTwitterLoginStatus(user);
	    });
	});
}

function fadeInTwitterList() {
	$("#content_twitter .list_item").fadeTo('slow', 1, function() {
		// Animation complete.
	});
}
function refreshTwitter() {
	$flashdiv = $('#add-comment-flash-message');
	
	$flashdiv.text('Your message has been posted to Twitter.').fadeIn();
	clearTimeout(Social.Twitter.timeout);
	Social.Twitter.timeout = setTimeout(loadTwitterListNoCache, 8000);
	$textarea = $('#add-comment-twitter');
	
	Social.Twitter.hasPosted = true;	//flag so you don't disply default text next time
	$textarea.empty();

	twttr.anywhere(function (T) {
		T("#add-comment-twitter").tweetBox({
		  counter: 	true,
		  height: 	Social.Twitter.height,
		  width: 	_mobile ? Social.Twitter.mobileWidth : Social.Twitter.width,
		  label: 	"<link href=\"http://"+domain+"/fxm/theme/css/twitter.css?v=1\" rel=\"stylesheet\">",
		  defaultContent: '',
		  onTweet:	refreshTwitter,
		});
	});
}
function loadTwitterList(justTweeted) {
	var url 	= GlobalRoot+"social/tweets/" + (justTweeted=="no_cache" ? "no_cache" : "");
	var action 	= "loadList";
	var params 	= {
		action:			"loadList",
		lastTimestamp:	Social.Twitter.timestamp
	};
	$.post(url, params, function(response) {
		if(response.success == "true"){
			$('#content_twitter').html(response.html);
			//handling for iPad scroll pane
			/*if ((navigator.userAgent.match(/iPad/i) != null)||(navigator.userAgent.match(/iPhone/i) != null)){
				//$("#twitterList").jScrollTouch();
			}else{
				//setup jscrollpane
			}*/

			if (Social.Twitter.timestamp != 0) fadeInTwitterList();

			//set timestamp and set timeout to refresh 2 minutes
			Social.Twitter.timestamp = response.timestamp;
			clearTimeout(Social.Twitter.timeout);
			Social.Twitter.timeout = setTimeout(loadTwitterList, 120000);

			$('#content_twitter .listItem').children().find("a").attr('target', '_blank');
		}
		else {
			//Twitter API call error
		}
	},'json');
}
function loadTwitterListNoCache() {
	loadTwitterList("no_cache");
}

/***  Facebook  ***/
function copyFacebookLikeBoxToTab() {
	if ($('.copy-likebox').length > 0)
		$('.copy-likebox').append($('#facebook-likebox-moveable').detach().addClass('moved'));
}
function checkIfUserLikes() {
	if (Social.Facebook.accessToken != '') { //cant make call without accessToken
		FB.api({ method: 'pages.isFan', page_id: Social.Facebook.mustLikeAppId }, function(resp) {
			if (resp == true || (resp.error_code && resp.error_code != 104)) { //error 104 = Incorrect Signature

			}
			else if (resp == false) {

			}
		});
	}
}
function updateFacebookAndGetGlueInTab() {
	copyFacebookLikeBoxToTab();
}
function switchFacebookLoginStatus(response) {
	status = response ? response.status : Social.Facebook.loginStatus;
	//debug.log("switchFacebookLoginStatus " + status)

	switch (status) {
		case "unknown":			//not logged into FB
			break;
		case "notConnected":	//haven't allowed app access
			subscribeToFacebookAuth();
			break;
		case "connected":		// good to go
			break;
		default:				//nothing to see here
			break;
	}
}
function handleAuthResponse(response) {
	Social.Facebook.accessToken = response.authResponse.accessToken;
}
function subscribeToFacebookAuth() {
	FB.Event.unsubscribe('auth.login', handleAuthResponse);
	FB.Event.subscribe('auth.login', handleAuthResponse);
}
function getFacebookLoginStatus(callback) {
	FB.getLoginStatus(function(response) {
		if (response.authResponse) {
			//debug.log(response);
			Social.Facebook.loginStatus = response.status;
			if (response.authResponse) {
				$('#facebook-login a').html('Post With Facebook');
				
				Social.Facebook.userID = response.authResponse.userID;
				Social.Facebook.accessToken = response.authResponse.accessToken;

				FB.api('/me', function(response) {
					message = 'Hello ' + response.name;
					$('#loginBtns p:first').text(message);
					
					//avatar
					var userimg = $("<img />").attr('src', 'http://graph.facebook.com/' + response.username + '/picture');
					$('#avatar').html(userimg);
					//welcome message (response.name)
					createCommentForm('facebook');
				});
			} else {
				Social.Facebook.accessToken = "";
			}
			if (callback) {
				callback(response);
			}
		} else {
			console.log('User cancelled login or did not fully authorize.');
		}
		
		return true;
	});
	
	return false;
}
function initFacebookCallbacks() {
	FB.init({
		appId  : Social.Facebook.appId,
		status : true, 	// check login status
		cookie : true, 	// enable cookies to allow the server to access the session
		xfbml  : true 	// parse XFBML
    });

	getFacebookLoginStatus(switchFacebookLoginStatus);

	$('#allow-app-button').live('click', function (e) {
		e.preventDefault();
		promptFacebookLogin();
	});
}
function initFacebookCommenting() {
	// Liking of Comments
	$('.facebookItem .like').live('click', function(e) {
		e.preventDefault();
		$(this).data({
			'id' : $(this).attr('data-id')
		});
		var likesObject;
		try {
			eval("likesObject = " + $(this).attr('data-likes'));
			$(this).data({
				'likes' : likesObject
			});
		}
		catch(e) {
			$(this).data({
				'likes' : null
			});
		}
		var $scope = $(this);
		if ($(this).text() == "Like") {
			//user "Like"s
			FB.api("/"+$(this).data('id')+"/likes", 'POST', function(response) {
				if (response == true)
					$scope.text('Unlike');
			});
		}
		else {
			//user "Unlike"s
			FB.api("/"+$(this).data('id')+"/likes", 'DELETE', function(response) {
				if (response == true)
					$scope.text('Like');
			});
		}
	});

	//Commenting
	$('.facebookItem .comment').live('click', function(e) {
		//a user clicks "Comment"
		e.preventDefault();
		$(this).data({
			'id' : $(this).attr('data-id')
		});
		var $form = $(this).parents('.listItem').find('form.comments');
		$(this).parents('.listText').after($form);
		$form.toggleClass('hidden');
		if ($form.hasClass('hidden'))
			$(this).text('Comment');
		else
			$(this).text('Cancel');
	});
	$('.facebookItem form.comments').live('submit', function(e) {
		//a user submits their comment
		e.preventDefault();

		var message = $(this).find('input[name="message"]').val();
		var $scope = $(this);
		var $parent_comment = $(this).parent().find('a.comment');

		FB.api('/'+$(this).data('id')+'/comments', 'post', {'message' : message}, function(response) {
			if (response.id) {
				FB.api('/'+response.id, function  (response) {
					$scope.before('<div class="listComments"><div class="listCommentsThumbnail"><a href="http://www.facebook.com/profile.php?id='+response.from.id+'" class="username"><img src="http://graph.facebook.com/'+response.from.id+'/picture" /></a></div><div class="listCommentsText"><a href="http://www.facebook.com/profile.php?id='+response.from.id+'" class="username">'+response.from.name+'</a> '+response.message+' <p></p><div class="twitterTime">Just now <a href="#" class="like" data-id="'+response.id+'">Like</a></div></div></div>');

					$scope.find('input.facebook-comment').val('');
					$scope.toggleClass('hidden');
					$parent_comment.text('Comment');
				});
			};
		});
	});
}
function promptFacebookLogin() {
	var logged_in = getFacebookLoginStatus();
	
	if (Social.Facebook.accessToken == "" || ! logged_in) {
		FB.login(function (response) {
			getFacebookLoginStatus();
		}, { scope : 'publish_stream,user_likes' });
	}

	createCommentForm("facebook");
}
function loadFacebookList() {
	//if (Social.Facebook.accessToken != "") {
		var url 	= GlobalRoot+"social/get_facebook";
		var params 	= {
			action:			"loadFacebook",
			timestamp:		0,	//this is not required?
			accessToken: 	Social.Facebook.accessToken
		};
		$.post(url, params, function(response) {
			if(response.success == "true"){
				$('#content_facebook').html(response.html);

				$('#content_facebook .like').each(function() {
					$(this).siblings(".comment").before($(this));
				});

				FB.getLoginStatus(function(response) {
					//this should always have a session because we force login, right?
					//debug.log(response.session.uid);
					if (response.authResponse) {
						$('#content_facebook .like').each(function(index) {
							var uid = response.authResponse.userID;
							//debug.log($(this).attr('data-likes'));
							$(this).data({
								'id' : $(this).attr('data-id')
							});
							var likesObject;
							try {
								eval("likesObject = " + $(this).attr('data-likes'));
								$(this).data({
									'likes' : likesObject
								});
							}
							catch(e) {
								$(this).data({
									'likes' : null
								});
							}
							var $likes = $(this).data('likes');
							if ($likes != null & $likes != "null") {
								for (var i=0; i<$likes.data.length; i++) {
									var like = $likes.data[i];
									if (like.id == uid) {
										$(this).text('Unlike');
									};
								};
							};
						});
					}
					else {
						//response didn't include session
					}
				});
			}
			else {
				//ajax error
			}
		},'json');
	//}
	//else {
		//user not logged in
	//	promptFacebookLogin();
	//}
}
function postFB(text) {

	if (Social.Facebook.accessToken != "") {
		$flashdiv = $('#add-comment-flash-message');
		$textarea = $('#add-comment-text');
		
		if (text != ""){
			$flashdiv.html("Posting your message, please wait...");

			var url = GlobalRoot+"social/get_facebook";
			var action = "postFacebook";
			
			path = 'http://'+ domain;
			var picture = $('#movie-details-hero').attr('data-thumb');				//if on movie detail page, this will be set in markup
			if(picture == undefined) {
				picture = '';
			} else {
				picture = path + picture;
			}
			var description = $('#movie-details-hero').attr('data-description');	//if on movie detail page, this will be set in markup
			if(description == undefined) {
				description = '';
			} 
			var link = $('#movie-details-hero').attr('data-link');					//if on movie detail page, this will be set in markup
			if(link == undefined) {
				link = '';
			} else {
				link = path + link;
			}
			var params = {  userid: Social.Facebook.userID, 
							action: action,
							message: text, 
							picture: picture, 
							description: description, 
							link: link, 
							accessToken: Social.Facebook.accessToken };

			$.post(url, params, function(msg) {
				if (msg.html == "needLike") {
					$flashdiv.html('You need to "Like" the FX Movie Channel page to post its Facebook wall.').fadeIn();
				}else{
					$flashdiv.html('Your message has been posted to your Facebook wall.').fadeIn();
					setTimeout(function() {
						loadFacebookList();
					}, 200);
					setTimeout(function() {
						Social.Facebook.hasPosted = true;	//flag so you don't disply default text next time
						$flashdiv.fadeOut(function() {
							$textarea.val('');
						});
					}, 2000);
				}
			},'json');
		}
		else {
			$flashdiv.html('Please enter a message').fadeIn();
		}
	}
	else {
		promptFacebookLogin();
		//FB.login ( '' , { perms : 'publish_stream,user_likes' } );
	}
	return false;
}
/*** End Facebook  ***/

function createCommentForm(visibleType) {
	Social.type = visibleType;
	$popupHeader = $('#add-comment-header');
	$submitBtn = $('#add-comment-button');
	$textarea = $('#add-comment-text');
	$twitterDiv = $('#add-comment-twitter');
	$socialcommentDiv = $('#social-comment');	//hide show all commenting if not logged in
	$commentDiv = $('#add-comment-regular');
	$flashDiv = $('#add-comment-flash-message');
	
	$socialcommentDiv.show();
	
	// get the value of the comment area
	var commentText = $textarea.val();

	if (Social.type == 'twitter') {
		
		// update default comment if viewing movie detail page
		var commentValue = (commentText != '') ? commentText : Social.Twitter.defaultText;
		if (commentValue == Social.Facebook.defaultText || commentValue == Social.GetGlue.defaultText) { commentValue = Social.Twitter.defaultText; }
		
		//if user has already posted - clear the text box - https://jira.blitzagency.com/browse/FXM-59
		if(	Social.Twitter.hasPosted == true) {
			commentValue = '';
		}
		$commentDiv.hide();
		$twitterDiv.show();
		$flashDiv.html('');		//reset
		$popupHeader.text(Social.Twitter.popupTitle);
		
		$submitBtn.val(Social.Twitter.defaultText);
		$textarea.val(commentValue);

		$twitterDiv.empty();

		twttr.anywhere(function (T) {
			T("#add-comment-twitter").tweetBox({
			  counter: 	true,
			  height: 	Social.Twitter.height,
			  width: 	_mobile ? Social.Twitter.mobileWidth : Social.Twitter.width,
			  label: 	"<link href=\"http://"+domain+"/fxm/theme/css/twitter.css?v=1\" rel=\"stylesheet\">",
			  defaultContent: commentValue,
			  onTweet:	refreshTwitter,
			});
		});
	}
	else if (Social.type == 'facebook') {
		
		// update default comment if viewing movie detail page
		var commentValue = (commentText != '') ? commentText : Social.Facebook.defaultText;
		if (commentValue == Social.Twitter.defaultText || commentValue == Social.GetGlue.defaultText) { commentValue = Social.Facebook.defaultText; }
		
		//if user has already posted - clear the text box - https://jira.blitzagency.com/browse/FXM-59
		if(	Social.Facebook.hasPosted == true) {
			commentValue = '';
		}
		$flashDiv.html('');		//reset
		$commentDiv.show();
		$twitterDiv.hide();
		$popupHeader.text(Social.Facebook.popupTitle);

		$submitBtn.val(Social.Facebook.defaultText);
		$textarea.val(commentValue);
		// $textarea.focus(function() {
		// 	$textarea.val('');
		// });
		$submitBtn.unbind('click');
		$submitBtn.click(function() {
			if (Social.Facebook.accessToken != "") {
				var comment = $textarea.val();
				if (comment != Social.defaultText) {
					postFB(comment);
				}
			}
			else {
				promptFacebookLogin();
			}
		});
	}
	else if (Social.type == 'getglue') {
		
		// update default comment if viewing movie detail page
		var commentValue = (commentText != '') ? commentText : Social.GetGlue.defaultText;
		if (commentValue == Social.Facebook.defaultText || commentValue == Social.Twitter.defaultText) { commentValue = Social.GetGlue.defaultText; }
		
		//if user has already posted - clear the text box - https://jira.blitzagency.com/browse/FXM-59
		if(	Social.GetGlue.hasPosted == true) {
			commentValue = '';
		}
		
		$flashDiv.html('');		//reset
		$commentDiv.show();
		$twitterDiv.hide();
		$popupHeader.text(Social.GetGlue.popupTitle);

		$submitBtn.val(Social.GetGlue.defaultText);
		$textarea.val(commentValue);
		$textarea.focus(function() {
			$textarea.val('');
		});
		$submitBtn.unbind('click');

		$submitBtn.click(function() {
			if (Social.GetGlue.userId != '') {
				var comment = $textarea.val();
				if (comment != Social.defaultText) {
					var url 	= "/fxm/connect/check_in/"+comment;
					var params 	= {};

					$flashDiv.html("Posting your message, please wait...");
					$.post(url, params, function(response) {
						if (response.error != "true") {
							Social.GetGlue.hasPosted = true;	//flag so you don't disply default text next time
							$textarea.val('');
							$flashDiv.html('You have successfully checked in to GetGlue.').fadeIn();
						}
						else {
							//GetGlue checkin API error
						}
					},'json');
				}
			}
			else {
				$flashDiv.html('You must be logged in to post').fadeIn();
				promptGetGlueLogin();
			}
		});
	}
}
function initSocial() {
	$('#facebook-login a').click(function (e) {
		e.preventDefault();
		promptFacebookLogin();
		trackPage('communitytab:facebook');
	});
	$('#twitter-login a').click(function (e) {
		e.preventDefault();
		promptTwitterLogin();
		trackPage('communitytab:twitter');
	});
	$('#getglue-login a').click(function (e) {
		e.preventDefault();
		promptGetGlueLogin();
		trackPage('communitytab:getglue');
	});
	
	var logged_in = getFacebookLoginStatus();
	if(! logged_in) {
		logged_in = getTwitterLoginStatus();		
	}
	if(! logged_in) {
		logged_in = getGetGlueLoginStatus();
	}
}

function getQueryString() {
	  var result = {}, queryString = location.search.substring(1),
	      re = /([^&=]+)=([^&]*)/g, m;

	  while (m = re.exec(queryString)) {
	    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	  }

	  return result;
}

/********************************************************/
/** UI **/
/********************************************************/
function initAccordions () {
	$(".accordion, .fxmovies-community, .schedule").accordion();
}
function initUiTabs() {
	$(".tabs").each(function(index) {
		var currentTab = -1;
		$(this).find("a").each(function(index2) {
			$(this).click(function (e) {
				e.preventDefault();
				if (index2 != currentTab) {
					currentTab = index2;
					var href = $(this).attr("href");
					prepareSocialTabToLoad(href);
					$(this).parent().parent().find(".selected").removeClass("selected");
					$(this).parent().addClass("selected");
					$(this).parent().parent().parent().find(".tab").each(function () {
						if ($(this).attr("id") == href.substr(1) ) {
							$(this).removeClass('offscreenTab');
							//$(this).show();
						}
						else {
							$(this).addClass('offscreenTab');
							//$(this).hide();
						}
					});
				}
				else {
					//tab already loaded
				}
			});
		});
		$(this).find("a").each(function(index) {
			$(this).parent().addClass("tabnum-"+index);
		});
		$(this).find("a:first").trigger("click");
	});
}
function prepareSocialTabToLoad(href, forceLoad) {
	var date = getQueryString()['date'];
	var query_str = (signed_request ? "?signed_request=" + signed_request  : '');

	if(date!=undefined && date != '' && isDev) {
		query_str += ((query_str != '') ? "&" : "?") + "date="+server_time.replace(' ', 'T');
	}

	var tab_urls = {
		"#checkin" 		: GlobalRoot+"stats/checkin_tab" + query_str,
		"#leaderboard" 	: GlobalRoot+"stats/you_tab" + query_str,
		"#watching" 	: GlobalRoot+"stats/whos_watching_tab",
		"#stickers" 	: GlobalRoot+"stats/fx_tab",
		"null" 			: ""
	}
	if (tab_urls[href] != undefined && ($(href).hasClass("content_loaded") == false || forceLoad == true)) {
		$(href).empty().append('<span class="loading"></span>');
		$(href).load(tab_urls[href], function() {
			$(href).removeClass("loading");
			$(href).addClass("content_loaded");
			updateFxInteractions();
			updateFxRecentCheckins();
			updateFacebookAndGetGlueInTab();
			communityTabScroll();
		});
	}
	else {
		communityTabScroll();
	}
}
function communityTabScroll() {
	if (!_mobile && !_facebook) {
		$(".fxmovies-community .tab").each(function (){
			var content_height = 1320;
			var maxHeight = $(this).offset().top + $(this).outerHeight();
			maxHeight -= content_height;
			if (maxHeight > 0) {
				//$(this).css({'height':'auto'});
				//$(this).css({'overflow-y':'scroll', 'height': $(this).height()-maxHeight});
				//debug.log("TABS: offset().top " + $(this).offset().top + ' outerHeight():' + $(this).outerHeight() + '  content_height:' + content_height);
			}
		});
	}
}

function initSocialTabs(){
	initFacebookCommenting();
	// hide content for all tabs
	$('.fxmovies-community .tab').hide();

	// load up the correct tab
	$('.fxmovies-community #content_all').show();

	// function to handle the click event for the tab links
	$('.tabs a').click(function(e) {

		// disable default behavior
		if (e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}

		// mark all tabs as unselected and hide their data
		$('.tabs li').removeClass('selected');
		$('.fxmovies-community .tab').hide();

		// mark selected tab and display its data
		$(this).parent().addClass('selected');
		$('.fxmovies-community #' + $(this).attr('id')).show();
	});
}

// using window ready is better than DOM ready for performance reasons (according to whom?)
$('document').ready(function() {
    initFacebookCallbacks();
    createCommentForm('facebook');	//intialize comment form, default = facebook

    //initUiTabs();					//initialize Ui Tab state
	initSocial();
	initSocialTabs();
});
