var friendListTemplate = ' \
<div class="scroller" onscroll="scrollFriendList(this);" style="margin:0px 0px 3px 0px;float:left;height:400px;width:240px;overflow-y:scroll;overflow-x:none;background:white;border:1px solid #535353"> \
	<div class="friendListSpinner" style="margin:5px 10px 10px 7px;"> \
		Loading friends...<br> \
		<img src="/images/spinner2.gif" style="margin-top:3px;"> \
	</div> \
	<div class="iHaveNoFriends" style="margin:5px 10px 10px 7px;display:none;"> \
		None found <br> \
	</div> \
	<form> \
		<div class="friendList" style="display:none;"> \
		</div> \
	</form> \
</div> \
<div style="display:none;" class="checkall"> \
	<span class="linklike" style="font-size:12px;" onclick="checkAllFriends()">check all</span> \/ \
	<span class="linklike" style="font-size:12px;" onclick="uncheckAllFriends()">uncheck all</span> \
</div> \
';

checkAllFriendsWhoLoad = 1;
uncheckAllFriendsWhoLoad = 0;
function checkAllFriends()
	{
	$j('.fchk').each(function()
		{
		$j(this).attr('checked', true);
		var thisfbid = $j(this).attr('fbid');
		hlite(thisfbid);
		})
	checkAllFriendsWhoLoad = 1;
	uncheckAllFriendsWhoLoad = 0;
	}

function uncheckAllFriends()
	{
	$j('.fchk').each(function()
		{
		$j(this).removeAttr('checked');
		var thisfbid = $j(this).attr('fbid');
		hlite(thisfbid);
		})
	uncheckAllFriendsWhoLoad = 1;
	checkAllFriendsWhoLoad = 0;
	}

function makeArrayOfInvitees()
	{
	var invitees = new Array(); // create an array of friends to invite
	$j(".fchk:checked").each(function(count,tag) // cycle through each checked checkbox
		{
		invitees.push($j(tag).val());
		})
	return invitees;
	}

function sendRequestToRecipients(message, success, forwardingURL, title) { // forwardingURL is the url we should send the recipient to after they click the fb request
	if ((!message) || (message == ''))
		{
		message = me.name + ' invited you to join Fandalism, an invite-only community for musicians. This invite expires soon so accept it fast!'		
		}
	if (!success)
		{
		debug('/js/facebookfriendlist making default success function');
		debug(success);
		var success = function(){};
		}
	if (!forwardingURL)
		{
		var forwardingURL = '';
		}
	if (!title)
		{
		var title = 'Send Invites';
		}
	var invitees = makeArrayOfInvitees();
	debug(invitees.length);
	FB.ui({method: 'apprequests',
		message: message,
		data: {"username":me.username},
		title: title,
		to: invitees // we just created this array, above
	}, function(response)
		{
		debug('response from fb:');
		debug(response);
		if (!response)
			{
			debug('you clicked the cancel button');
			return false;
			}
		$j.post('/api/logFacebookRequests/',
			{
			request: response.request,
			to: response.to,
			forwardingurl: forwardingURL,
			description: message 
			},function(response)
				{
				debug('you sent requests');
				success(response);
				})
		});
}
	
function hlite(x)
	{
	if ($j('#c' + x).attr('checked'))
		{
		$j('#b' + x).addClass('nameo-selected');
		$j('#b' + x).removeClass('nameo');
		}
	else
		{
		$j('#b' + x).addClass('nameo');
		$j('#b' + x).removeClass('nameo-selected');
		}
	}

function checkMe(fbid)
	{
	// $j('#c' + fbid).attr("checked", "checked");
	if ($j('#c' + fbid).attr("checked"))
		{
		$j('#c' + fbid).removeAttr("checked");
		fchk($j('#c' + fbid));
		}
	else
		{
		$j('#c' + fbid).attr("checked","checked");
		fchk($j('#c' + fbid));
		}
	}
	
function loadMoreFriends(first)
	{
		for (var i=first;i<first+numberOfFriendsToLoadAtOneTime;i++)
		{
			if (i < numberOfEntries)
				{
				var check_this_one = '';
				if (friendsObj[i].is_app_user)  
					{ 
					if (makeArrayOfInvitees().length < maxInvitesAllowed) // online pre-check a name if we're under 50 (or whatever the max is)
						{
						check_this_one = 'checked'; 
						}
					}
				$j('.friendList').append('<span onclick="checkMe(' + friendsObj[i].uid + ')" class="nofl"><div class="nameo friendname" id="b' + friendsObj[i].uid + '"><input name="userid" ' + check_this_one + ' onclick="checkMe(' + friendsObj[i].uid + ');" class="fchk" type="checkbox" fbid="' + friendsObj[i].uid + '" value="' + friendsObj[i].uid + '" id="c' + friendsObj[i].uid + '">' + friendsObj[i].name + '</div></span>');
				if (check_this_one != '') { fchk($j('#c' + friendsObj[i].uid)); } // if checked, run fchk (which highlights and counts it)
				}
		}
	}

function scrollFriendList(obj)
	{
	var scrollBottom = $j('.friendList').height() - $j('.scroller').scrollTop();
	if (scrollBottom < 1200)
		{
		friendCounter = friendCounter + numberOfFriendsToLoadAtOneTime;
		loadMoreFriends(friendCounter);
		}
	}

function fchk(obj)
	{
	selectedID = $j(obj).val();
	var invitees = makeArrayOfInvitees();
	if (invitees.length > maxInvitesAllowed) // too many selected. unselect the last one & send a message.
		{
		// debug($j("#c" + selectedID).html());
		$j("#c" + selectedID).removeAttr("checked")
		// alert("We're sure " + prettyFriendsObj[selectedID] + " is awesome. But you can only invite up to " + maxInvitesAllowed + " people at a time. Facebook's rules.");
		alert("You can only invite up to " + maxInvitesAllowed + " people at a time. Facebook's rules.");
		}
	else // make selected items look pretty
		{
		hlite(selectedID);
		}
	}

$j(document).bind('facebookFriendsLoaded',function(obj)
	{
	$j('.friendListSpinner').hide();
	$j('.checkall').show();
	$j('.friendList').show();
	if (numberOfEntries == 0)
		{
		debug(numberOfEntries);
		$j('.iHaveNoFriends').show();
		}
	})

waitingForFacebook = 0; // keep a count, just in case it takes too long.
maxInvitesAllowed = 50;
function getFacebookFriends(idToPopulate, height, mode, maxInvitesAllowed) 
	{
	if (!maxInvitesAllowed) { var maxInvitesAllowed = 50;  }
	window.maxInvitesAllowed = maxInvitesAllowed;
	if (!height) { var height = 400; }
	if (!mode) { var mode = 'notUsers' } // can be "everyone", "users", "notUsers"
	globalVarIdToPopuplate = idToPopulate;
	$j('#' + globalVarIdToPopuplate).html(friendListTemplate); // first, replace html of chosen ID with the blank friends list...
	$j(".scroller").height(height);
	if (!facebookReady) // this global variable is set in /fbstuff.  it turns into 1 when the user is logged in & API is ready. we do this here to avoid a race condition, which would happen if we simply waited for the event (facebookReady) to fire.
		{
		var waitingForFacebookTimer = setTimeout(function()
			{
			waitingForFacebook++;
			debug('Getting friends, try: ' + waitingForFacebook)
			if (waitingForFacebook < 400)
				{
				getFacebookFriends(idToPopulate, height, mode, maxInvitesAllowed);
				}
			else 
				{
				clearTimeout(waitingForFacebookTimer);
				$j('.friendListSpinner').hide();
				$j('#modal-share-facebook').modal('hide');
				alert('There was some sorta error loading your friends. Sorry.  Should work next time, hopefully.');
				return false;
				}
			},50)
		return false;
		}
	jQuery.support.cors = true;
	var postData = new Object();

	var queries = new Object();
	queries.users = 'SELECT name, uid, is_app_user FROM user WHERE is_app_user and uid IN (SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY name';
	queries.notUsers = 'SELECT name, uid, is_app_user FROM user WHERE not is_app_user and uid IN (SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY name';

	FB.api(
	  {
	    method: 'fql.multiquery',
	    access_token: me.fb_accesstoken,
	    queries: queries
	  },
	  function(response) {
		if (typeof response.error_msg != 'undefined')
			{
			debug('error:');
			debug(response);
			alert('And error happened while trying to get your friend list from Facebook.\n\nHere\'s what Facebook is telling us:\n\n' + response.error_msg);
			$j('#modal-share-facebook').modal('hide');
			return false;
			}
		array1 = response[0].fql_result_set;
		array2 = response[1].fql_result_set;
		if (mode == 'everyone')
			{
			var response = array2.concat(array1); // merge the 2 result sets, showing users first
			}
		else if (mode == 'users')
			{
			var response = array2;
			}
		if (mode == 'notUsers')
			{
			var response = array1;
			}
		if (response.length == 0)
			{
			$j(document).trigger('noFacebookFriends');
			}
		friendsObj = response; 
		numberOfEntries = friendsObj.length;
		numberOfFriendsToLoadAtOneTime = 150;
		friendCounter = 0;
		loadMoreFriends(friendCounter);
		$j(document).trigger('facebookFriendsLoaded');
	  }
	);

	}

/* this is how you would run all the scripts on this page
$j(document).bind('facebookReady',function()
	{
	getFacebookFriends();
	});
*/

