/*
http://wiki.developers.facebook.com/index.php/Trying_Out_Facebook_Connect
http://wiki.developers.facebook.com/index.php/JS_API_N_FB
http://wiki.developers.facebook.com/index.php/Facebook_Connect_Tutorial1
http://wiki.developers.facebook.com/index.php/Facebook_Connect_Login_Buttons	
http://communitygrids.blogspot.com/2008/02/little-more-jsfacebook-hacking.html
http://wiki.developers.facebook.com/index.php/JavaScript_Client_Library
http://wiki.developers.facebook.com/index.php/JS_API_Index
http://wiki.developers.facebook.com/index.php/Talk:Fql.multiquery
http://wiki.developers.facebook.com/index.php/JS_API_M_FB.ApiClient.callMethod

http://www.facebook.com/developers/
http://www.facebook.com/developers/editapp.php?app_id=136660998934
*/

jQuery.extend({
	format: function format($text, $data) {
		for ($key in $data)
		{
			$text = $text.split('{' + $key + '}').join($data[$key]);
		}
	
		return $text;
	}
});


jQuery.popup = {

	type: 1,

	init: function() {

		$id = FB.Connect.get_loggedInUser();

		$popup = $('#popup-friends');
		$popup.data('id', $id);
		$popup.data('limit', 50);
		$popup.data('selected', {});

		$parameters = {};
		$parameters['queries'] = {
			query1: "SELECT uid, name, pic_square_with_logo, profile_url, current_location from user WHERE uid=" + $id,
			query2: "SELECT \'\' from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + $id + ") AND sex = 'male'",
			query3: "SELECT \'\' from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + $id + ") AND sex = 'female'",
			query4: "SELECT uid, name, pic_square, pic, profile_url, hometown_location, sex from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + $id + ") AND sex = 'male' ORDER BY name ASC LIMIT 0, " + $popup.data('limit'),
			query5: "SELECT uid, name, pic_square, pic, profile_url, hometown_location, sex from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + $id + ") AND sex = 'female' ORDER BY name ASC LIMIT 0, " + $popup.data('limit')
		};

		$api = FB.Facebook.apiClient;
		$api.callMethod(
			'fql_multiquery',
			$parameters,
			function($result) {	
				$popup.data('data', {
					user: $result[0]['fql_result_set'][0],
					friendCount: [$result[1]['fql_result_set'].length, $result[2]['fql_result_set'].length],
					friends: [[$result[3]['fql_result_set'], $result[4]['fql_result_set']]]
				});
				$popup.data('pageCount', [Math.ceil($popup.data('data').friendCount[0] / $popup.data('limit')), Math.ceil($popup.data('data').friendCount[1] / $popup.data('limit'))]);
				$popup.data('page', 1);
				$popup.find('strong.title').html('Hi ' + $popup.data('data').user.name);
				$popup.find('.submit').click(function() {
					jQuery.popup.submit();									  
				});

				jQuery.popup.resize();
				jQuery.popup.page(1);
				//jQuery.popup.show(1);
		});
		
		$(window).bind('resize scroll', function() { jQuery.popup.resize(); });
	},
	
	show: function($type) {
		jQuery.popup.type = parseInt($type, 10);
		jQuery.popup.page(1);

		$popup = $('#popup-friends');
		$popup.data('selected', {});
		$popup.show();
		$('#popup-overlay').show();
	},

	hide: function() {
		$popup = $('#popup-friends');
		$popup.hide();
		$('#popup-overlay').hide();
	},

	page: function($page) {
		$popup = $('#popup-friends');
	
		if (typeof $page == 'string')
		{
			$offset = $page;
			$pageCount = $popup.data('pageCount');
			$page = $popup.data('page');
	
			switch ($offset)
			{
				case '-1': $page = ($page == 1 ? $pageCount : $page - 1); break;
				case '1': $page = ($page == $pageCount ? 1 : $page + 1); break;
			}
		}
	
		$popup.data('page', $page);
	
		$data = $popup.data('data').friends;
	
		if ($data[$page - 1] == null)
		{
			$query = "SELECT uid, name, pic_square, pic, profile_url, hometown_location, sex from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=" + $id + ") AND sex = '" + (jQuery.popup.type == 1 ? 'male' : 'female') + "' ORDER BY name ASC LIMIT " + Math.max(0, $page - 1) * $popup.data('limit') + "," + $popup.data('limit');

			$api.fql_query($query, function($result) {
				$data[$page - 1] = $result;
				jQuery.popup.pageCallback($page);
			});
		}
		else
		{
			jQuery.popup.pageCallback($page);
		}
	},

	pageCallback: function($page) {	
		$popup = $('#popup-friends');
	
		$data = $popup.data('data').friends[$page - 1];

		if ($page == 1) $data = $data[jQuery.popup.type - 1];

		$template = $popup.find('textarea').val();
		$html = "";
	
		for ($i = 0; $i < $data.length; $i++) {
			$value = $data[$i];

			$value.location = ($value.hometown_location == null ? '-' : $value.hometown_location.city + ', ' + $value.hometown_location.country);
			$value = {
				id: $value.uid,
				name: $value.name,
				thumbnail: ($value.pic_square == '' ? 'assets/images/popup-friends-items-image-small.jpg' : $value.pic_square),
				image: ($value.pic == '' ? 'assets/images/popup-friends-items-image.jpg' : $value.pic),
				location: $value.location,
				sex: $value.sex,
				style: ($popup.data('selected')[$value.uid] ? " class=\"active\"" : "")
			};

			$html += jQuery.format($template, $value);
		}

		$popup.find('.items ul').html($html);
		$popup.find('.items ul')[0].scrollTop = 0;
		$popup.find('.items a').click(function() {
			$button = $(this);
			$selected = !$button.hasClass('active');
			
			$limit = 3;

			if ($selected && jQuery.popup.value().length >= $limit)
			{
				alert("You can only choose up to " + $limit + " friends, please deselect a friend first by clicking on the friend again.");
				return;
			}
			
			$id = $button.attr('rel');
			$data = $popup.data('selected');
			$data[$id] = ($selected ? {
				id: $id,
				name: $button.find('span strong').html(),
				image: $button.find('img').attr('rel'),
				sex: $button.find('input[name=sex]').val()
			} : null);

			if ($selected)
			{
				$button.addClass('active');
				$button.addClass($data[$id].sex);
			}
			else
			{
				$button.removeClass('active');
			}

			jQuery.popup.status();
		});
		
		jQuery.popup.status();
		
		$pagination = $popup.find('.pagination');
	
		$template = $pagination.find('textarea').val();
		$html = "";

		$count = $popup.data('pageCount')[jQuery.popup.type - 1];
		$data = {};
		$data['items'] = '';
	
		for ($i = $count; $i >= 1; $i--)
		{
			$data['items'] += "<li><a href=\"javascript:void(0)\"" + ($i == $page ? " class=\"active\"" : "") + " rel=\"" + $i + "\">" + $i + "</a></li>";
		}

		if ($count <= 1) $template = '';

		$pagination.find('ul').html(jQuery.format($template, $data));		
		$pagination.find('a[class=]').click(function() {
			jQuery.popup.page(parseInt($(this).attr('rel'), 10));																					 
		});
		$pagination.find('a.prev, a.next').click(function() {
			jQuery.popup.page(($(this).attr('class') == 'prev' ? '-1' : '1'));																					 
		});
		
		jQuery.popup.resize();
	},

	resize: function() {
		$popup = $('#popup-friends');
		$popup.css('margin-top', Math.round(($(window).height() - $popup.height()) / 2));
	},

	status: function() {
		$popup = $('#popup-friends');
		$data = jQuery.popup.value();
		$limit = 3;
		
		$male = 0;
		$female = 0;
		
		for ($i = 0; $i < $data.length; $i++) {
			switch ($data[$i].sex) {
				case 'male': $male += 1; break;
				case 'female': $female += 1; break;
			}
		}

		$male = Math.max(0, 3 - $male);
		$female = Math.max(0, 3 - $female);

		$subtitle = "Please choose " + $limit + " " + (jQuery.popup.type == 1 ? "male" : "female") + " friends";
		//if ($male > 0) $subtitle += "<br />" + $male + " more m" + ($male == 1 ? "a" : "e") + "n";
		//if ($female > 0) $subtitle += "<br />" + $female + " more wom" + ($female == 1 ? "a" : "e") + "n";

		$popup.find('.subtitle').html($subtitle);
		$status = ($data.length == $limit ? 'All friends selected, please click submit to continue' : Math.max(0, $limit - $data.length) + ' friends remaining...');
		$popup.find('.status').html($status);	
	},
	
	submit: function() {	
		$data = jQuery.popup.value();
		$limit = 3;

		if ($data.length < $limit)
		{
			alert('Please select ' + Math.max(0, $limit - $data.length) + ' more friends to continue');
			return;
		}

		jQuery.popup.hide();

		$('#saw')[0].friends(jQuery.popup.type, $data);
	},

	value: function() {
		$popup = $('#popup-friends');
		$data = $popup.data('selected');
		$value = [];

		for ($id in $data) {
			if ($data[$id]) $value.push($data[$id]);	
		}

		return $value;
	},

	user: function() {
		$popup = $('#popup-friends');

		return $popup.data('data').user;	
	}
	
};



function hide()
{
	jQuery.popup.hide();
}


function login()
{
	$('#popup-overlay').show();
	FB.Connect.requireSession(function() { status(true); }, function() { status(false); });
}


function logout()
{
	jQuery.popup.hide();

	FB.Connect.logout(function() { status(false); });	
}


function friends($type)
{
	jQuery.popup.show($type);	
}


function status($connected)
{
	$('#popup-overlay').hide();

	if ($connected)
	{
		jQuery.popup.init();

		$id = FB.Connect.get_loggedInUser();
		$query = 'SELECT uid, name, pic_square_with_logo, profile_url, current_location from user WHERE uid=' + $id;

		$api = FB.Facebook.apiClient;
		$api.fql_query($query, function($result) {
			$('#saw')[0].loadWheel($result[0]);
		});
	}
	else
	{
		login();
	}
}


function check()
{
	FB.Connect.ifUserConnected(function() { status(true); }, function() { status(false); });
}


function publish($data)
{
	//http://wiki.developers.facebook.com/index.php/JS_API_M_FB.Connect.ShowFeedDialog

	$ids = [];
	$saved = [];
	$killed = [];
	
	for ($i = 0; $i < $data.length; $i++) {
		$value = $data[$i];
		$value.url = "<a href=\"http://www.facebook.com/profile.php?id=" + $value.id + "\">" + $value.name + "</a>";

		if ($i == 1) $ids.push($value.id);

		if ($value.status) $saved.push($value.url);
		else $killed.push($value.url);
	}
	
	$friend = $killed.pop();
	$body = $saved.join(" and ") + " lived but "  + $killed.join(", ") + " and " + $friend + " were killed. <a href=\"http://www.saw6film.com\">Saw VI</a> -- In theaters October 23.";
	
	$data = {};
	$data['title'] = "put you on the Saw VI Wheel of Death.";
	$data['body'] = $body;
	$data['short'] = $data['title'] + ' ' + $data['body'];

	/*
	Mark put you on the Saw VI Wheel of Death. Johannes Anderson and Mark Nobel lived but Rolf Jensen, Jason Benekis, Franike Palmer, and Casey Simms were killed. Saw VI -- In theaters October 23.
	{*actor*} {*short*}
	{*actor*} {*title*}
	{*body*}
	{"short":"short","title":"title","body":"body"}
	Wheel of Death
	http://www.saw6film.com/wheelofdeath
	*/

	$id = FB.Connect.get_loggedInUser();

	FB.Connect.showFeedDialog(143498588934, $data, null, '', null, FB.RequireConnect.promptConnect, function() {
		FB.Connect.logoutAndRedirect(document.location.href);
	}, "The game has come full circle. The choice was yours. Who did you chose and why?", { value: "" });

	jQuery.popup.hide();
}


$().ready(function() {
	FB.init('871ea25ebd24706141ede202b627418f', 'xd_receiver.htm', { forceBrowserPopupForLogin: false });
	FB.ensureInit(function() {

		/*
		publish([
			{ id: 510246764, name: 'Sarah Noble', status: true },
			{ id: 510152181, name: 'Celia Noble', status: true },
			{ id: 510246764, name: 'Steven Macdowel', status: false },
			{ id: 100000017240914, name: 'Kimberley Joanne Bird', status: false },
			{ id: 1178218575, name: 'Rodrigo Romero', status: false },
			{ id: 1671860493, name: 'Mickey Smith', status: false }
		]);
		*/
								  
		//check();
		//if (FB.Connect.get_loggedInUser() != null) FB.Connect.logout();
	});
});