var api_client = null;
var pending = [];
var in_ajax = false;
var ignore = 0;
var page = 0;
var sort = 'last_update';
var dir = 'desc';
var fixed_dialogs = true;
var autopos_dialogs = false;
var traders = [];

if (($.browser.msie) && ($.browser.version.substr(0,1)=="6"))
{
	fixed_dialogs = false;
}

$(document).ready(function(){
	$("#progress").fadeOut(500);
	$(".tabs").find("a").click(function(){
		var tab = this.href.replace(/^.*#/,"");
		var tabs = $(this).parent(".tabs");
		$(this).addClass("active");
		tabs.find("a").not(this).removeClass("active");
		tabs.find("div").filter("#"+tab).show();
		tabs.find("div").not("#"+tab).hide();
		return false;
	});
	$("div.ingredient").mouseenter(function(){
		hint_show($(this),$("img",this));
	}).mouseleave(function(){
		hint_hide();
	});
	$("textarea").focus(function(){
		if ($(this).hasClass("empty"))
		{
			$(this).removeClass("empty").val("");
		}
	}).blur(function(){
		if (this.value=="")
		{
			$(this).addClass("empty").val(this.title);
		}
	}).each(function(){
		this.o_value = this.value;
		if (this.value=="")
		{
			$(this).addClass("empty").val(this.title);
		}
	}).keydown(function(e){
		if (((e.keyCode>=33) && (e.keyCode<=40)) || (e.keyCode==8) || (e.keyCode==46)) return true;
		if (e.keyCode==13)
		{
			this.blur();
			return false;
		}
		if (this.value.length>=159) return false;
		return true;
	});

	if (debug)
	{
		$(".dump_var").click(function(){
			var val = $("#"+$(this).attr("rel"));
			if (val.css("display")=="none") val.show();
			else val.hide();
		});
	}

	if (!fb_user) return;

	$.ajaxSetup({
		url: (sid_param!="")?"ajax.php?"+sid_param:"ajax.php",
		global: true,
		type: "POST",
		dataType: "json"
	});

	var r = new RegExp("^#[0-9]+$");
	if (r.exec(window.location.hash)!=null)
	{
		show_user(window.location.hash.replace("#",""));
	}
	r = new RegExp("[?&]uid=([0-9]+)");
	var res = r.exec(window.location.href);
	if (res)
	{
		show_user(res[1]);
	}

	$(document).bind("ajaxStart",function(){
		in_ajax = true;
		$("#progress").fadeIn(500);
	});
	
	$(document).bind("ajaxStop",function(){
		$("#progress").fadeOut(500);
		in_ajax = false;
	});

	$(document).bind("ajaxError",function(){
		$("#progress").fadeOut(500);
		in_ajax = false;
	});

	window.setTimeout("check_pending()",4000);

	show_addme(1);
});

function set_variable(key,val)
{
	if (pending.length>0){
		var r = new RegExp("^"+key+"=");
		for (var i=0;i<pending.length;i++){
			if (r.exec(pending[i])!=null){
				pending[i] = key+"="+val;
				return;
			}
		}
	}
	pending = pending.concat(key+"="+val);
}

function check_variable(key,el)
{
	if (el.value==el.o_value) return;
	el.o_value = el.value;
	set_variable(key,el.value);
}

function check_pending()
{
	if ((!in_ajax) && (pending.length>0)){
		do_ajax(pending.join("&"));
		pending = [];
	}
	window.setTimeout("check_pending()",2000);
}

function process_ajax(res)
{
	if ((res.error!=null) && (res.error!=""))
	{
		$("#status").html(res.error).addClass("error");
		if (!ignore)
		{
			var dialog = modal_dialog("dialog");
			dialog.find(".message").html("<p>The following error occured:</p><p class=\"error\">"+res.error+"</p>");
			dialog.find(".extra_buttons").html("<button onclick=\"document.location='logout.php';\">Reconnect</button>");
			modal_show(dialog);
		}
	}
	else if ((res.status!=null) && (res.status!=""))
	{
		$("#status").html(res.status).fadeIn(200);
		window.setTimeout(function(){
			$("#status").fadeOut(2000);
		},3000);
	}
	if (res.res_info!=null)
	{
		if (res.res_info!="")
		{
			$("#res_info").html(res.res_info).show();
		}
		else
		{
			$("#res_info").hide();
		}
	}
	if (res.res_message!=null)
	{
		if (res.res_message!="")
		{
			$("#res_message").html(res.res_message).show();
		}
		else
		{
			$("#res_message").hide();
		}
	}
	if (res.res_traders!=null)
	{
		if (res.res_traders!="")
		{
			traders = res.res_traders;
			display_traders();
			$("#res_traders").show();
		}
		else
		{
			traders = [];
			$("#res_traders").hide();
		}
	}
	if (res.res_friends!=null)
	{
		if (res.res_friends!="")
		{
			traders = res.res_friends;
			display_traders(true);
			$("#res_traders").show();
		}
		else
		{
			traders = [];
			$("#res_traders").hide();
		}
	}
	if (res.res_temp!=null)
	{
		if (res.res_temp!="")
		{
			traders = traders.concat(res.res_temp);
			display_temp(res.res_temp);
			$("#res_temp").show();
		}
		else
		{
			$("#res_temp").hide();
		}
	}
	if (res.npages!=null)
	{
		if (res.npages>0)
		{
			page = res.page;
			if (res.page>0) $(".prev").show();
			else $(".prev").hide();
			if (res.page<res.npages-1) $(".next").show();
			else $(".next").hide();
			$(".navigation").find("span").html(res.navigation);
		}
		else
		{
			page = 0;
			$(".prev").hide();
			$(".next").hide();
			$(".navigation").find("span").html("");
		}
	}
	if (res.sort!=null)
	{
		sort = res.sort;
		dir = res.dir;
	}
}

function do_ajax(query,callback)
{
	if (callback==null) callback = process_ajax;
	query = query+"&friends_only="+$("#friends_only:checked").val()+"&locale="+locale.locale;
	$.ajax({
		data: query,
		success: callback
	});
}

function toggle_ingredient(d)
{
	var c = d.className.replace(/ingredient\s+/,"");
	var c2;

	switch(c){
	case "normal":
		c2 = "give";
		break;
	case "give":
		c2 = "want";
		break;
	case "want":
		c2 = "normal";
		break;
	};
	set_variable(d.id,c2);
	$("#"+d.id).removeClass(c).addClass(c2);
}

function reset_ingredients()
{
	if (confirm(locale.reset_confirm))
	{
		$(".ingredient").removeClass("give").removeClass("want").addClass("normal");
		do_ajax("reset=1");
	}
}

function hint_show(d,i,ox,oy)
{
	var hint = $("#hint");
	var o = i.offset();
	var h = i.attr("alt");
	var pos,stars;

	if (ox==null) ox = 0;
	if (oy==null) oy = 0;
	o.left += 4+ox;
	o.top += i.height()-4+oy;
	o.position = "absolute";
	pos = h.indexOf("*");
	if (pos>0)
	{
		stars = h.substr(pos);
		h = h.substr(0,pos-1);
		hint.appendTo(d).css(o).show().find("span").html(h+"&nbsp;<img src=\""+staticurl[0]+"img/star_"+stars.length+".png\" alt=\""+stars+"\" />");
	}
	else
	{
		hint.appendTo(d).css(o).show().find("span").html(h);
	}
}

function hint_hide()
{
	$("#hint").hide();
}

function do_feed()
{
	var w = "";
	var g = "";
	var d,i,s,imgs,caption;
	var r = new RegExp("^.*/rcmarket/");

	d = $(".ingredient").get();
	if (d.length==0) return;
	imgs = [{"type": "image","src": "http://fb.yris.be/rcmarket/img/logo.png","href": "http://fb.yris.be/rcmarket/"}];
	for (var x=0;x<d.length;x++)
	{
		if (d[x].className.match("normal")!=null) continue;
		i = $(d[x]).find("img").get();
		if (i.length!=1) continue;
		i = i[0];
		s = i.alt.replace(/ \**$/,"").toLowerCase();
		if (d[x].className.match("want")!=null)
		{
			if (w!="") w = w+", ";
			w = w+s;
		}
		else if (d[x].className.match("give")!=null)
		{
			if (imgs.length<20)
			{
				imgs = imgs.concat({"type": "image","src": "http://fb.yris.be/rcmarket/img/"+s+".png","href": "http://fb.yris.be/rcmarket/"});
			}
			if (g!="") g = g+", ";
			g = g+s;
		}
	}
	if ((w=="") || (g==""))
	{
		alert(locale.feed_warning); 
	}
	else
	{
		caption = "{*actor*} is looking for "+w+" and is willing to give "+g+".";
		if ($("#level").val()) caption = caption+" (Level "+$("#level").val()+")";
		FB.Connect.streamPublish("",{"caption": caption,"media": imgs},[{"text": "Trade","href": "http://apps.facebook.com/rcmarket/?uid="+fb_user}]);
		try {
			pageTracker._trackEvent("fb","publish_ingredients");
		} catch(err) {}
	}
}

function modal_dialog(d,e)
{
	var dialog = $("#"+d);
	var h,x,y,my;

	h = dialog.height();
	x = Math.round(($(window).width()-dialog.width())/2);
	y = Math.round(($(window).height()-h)*0.38);
	if ((autopos_dialogs) && (e!=null))
	{
		my = e.pageY;
		if (my==null) my = e.y;
		dialog.attr("mousey",my);
		y = Math.round(my-h*0.62);
	}
	else if (fixed_dialogs)
	{
		dialog.css("position","fixed");
	}
	dialog.css({"left":x,"top":y});
	dialog.find(".close").one("click",function(){
			modal_close(dialog);
	});
	return dialog;
}

function modal_show(dialog)
{
	modal_resize(dialog);
	$("#mask").css({"width":$(window).width(),"height":$(document).height()}).show();
	dialog.show();
}

function modal_resize(dialog)
{
	var mousey = dialog.attr("mousey");
	var x = Math.round(($(window).width()-dialog.width())/2);
	var y;

	if (mousey>0)
	{
		y = Math.round(mousey-dialog.height()*0.62);
	}
	else
	{
		y = Math.round(($(window).height()-dialog.height())*0.38);
	}
	dialog.css({"left":x,"top":y});
}

function modal_close(dialog)
{
	dialog.attr("mousey",0);
	dialog.hide();
	$("#mask").hide();
}

function show_user(uid,e)
{
	var dialog = modal_dialog("user_info",e);
	dialog.find(".user_info").hide();
	dialog.find(".user_busy").show();
	dialog.find(".dialog_buttons").find("button").not(".close").remove();
	modal_show(dialog);
	for (var i=0;i<traders.length;i++)
	{
		if (traders[i].uid==uid)
		{
			display_user(dialog,traders[i]);
			return false;
		}
	}

	do_ajax("user="+uid,function(res){
		if ((!res.user) || (!res.user.uid))
		{
			modal_close(dialog);
			process_ajax(res);
		}
		else
		{
			traders = traders.concat(res.user);
			display_user(dialog,res.user);
		}
	});

	return false;
}

function display_traders(large)
{
	var t = $("#res_traders");
	var line,title,i,j,positive;
	var uids = [];
	var headers;
	
	if (large)
	{
		headers = [
			"<a href=\"#\" onclick=\"friends_sort('name'); return false;\">"+locale.profile+"</a>",
			"<a href=\"#\" onclick=\"friends_sort('last_update'); return false;\">"+locale.last_update+"</a>",
			"<a href=\"#\" onclick=\"friends_sort('friend_since'); return false;\">"+locale.friend_since+"</a>"
		];
	}
	else
	{
		headers = [locale.profile,locale.last_update];
	}
	headers = headers.concat([locale.give,locale.want]);
	t.html("<tr><th>"+headers.join("</th><th>")+"</th></tr>");
	for (i=0;i<traders.length;i++)
	{
		uids = uids.concat(traders[i].uid);
		line = "<tr id=\"trader_"+traders[i].uid+"\" onclick=\"show_user('"+traders[i].uid+"',event);\"";
		if (traders[i].friend) line = line+" class=\"friend\"";
		if (traders[i].online) line = line+" title=\""+locale.online+"\"";
		line = line+">";
		line = line+"<td class=\"mo name first\"><a href=\"#"+traders[i].uid+"\" onclick=\"return false;\"><img src=\""+traders[i].pic_square+"\" class=\"profile_pic\" />";
		if (traders[i].online) line = line+"<img class=\"online\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\"("+locale.online+")\" />";
		else line = line+"<img class=\"offline\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\"\" />";
		if (large)
		{
			line = line+htmlspecialchars(traders[i].name);
		}
		else
		{
			line = line+htmlspecialchars(traders[i].first_name);
		}
		positive = (traders[i].neval+traders[i].eval)/2;
		if (positive>0)
		{
			line = line+"&nbsp;<span class=\"eval\">(+"+positive+")</span>";
		}
		line = line+"</a></td>";
		line = line+"<td class=\"mo last_update\">"+traders[i].last_update_short+"</td>";
		if (large)
		{
			line = line+"<td class=\"mo friend_since\">"+traders[i].friend_since+"</td>";
		}
		line = line+"<td class=\"mo\">";
		for (j=0;j<traders[i].give_match.length;j++)
		{
			title = traders[i].give_match[j].name;
			line = line+"<img class=\"ingredient\ ingr24 ingr24-"+traders[i].give_match[j].iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" title=\""+title+"\" /> ";
		}
		line = line+"</td><td class=\"mo last\">";
		for (j=0;j<traders[i].want_match.length;j++)
		{
			title = traders[i].want_match[j].name;
			line = line+"<img class=\"ingredient\ ingr24 ingr24-"+traders[i].want_match[j].iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" title=\""+title+"\" /> ";
		}
		line = line+"</td></tr>";
		t.append(line);
	}
	if (api_client!=null)
	{
		api_client.fql_query('SELECT uid,online_presence FROM user WHERE uid IN ('+uids.join(',')+')',function(rows){
			if (rows!=null)
			{
				for (i=0;i<rows.length;i++)
				{
					if ((rows[i].online_presence=='active') || (rows[i].online_presence=='idle')) $("#trader_"+rows[i].uid).attr("title",locale.online).find("img.offline").addClass("online");
				}
			}
		});
	}
}

function display_temp(list)
{
	var t = $("#res_temp_container");
	var line,title,i,j;
	
	t.find("div.temp").remove();
	for (i=0;i<list.length;i++)
	{
		title = htmlspecialchars(list[i].first_name);
		line = "<div class=\"temp\" onclick=\"show_user('"+list[i].uid+"',event);\">";
		line = line+"<a href=\"#"+list[i].uid+"\" onclick=\"return false;\"><img src=\""+list[i].pic_square+"\" class=\"profile_pic\" alt=\""+title+"\" title=\""+title+"\" /></a>";
		line = line+"</div>";
		t.append(line);
	}
}

function display_user(dialog,user)
{
	var d,iid,title,i,p,n,t;

	dialog.find(".dialog_buttons").prepend("<button class=\"add\" onclick=\"window.open('http://www.facebook.com/profile.php?id="+user.uid+"&amp;ref=rcmarket');\">"+locale.user_visit.replace("%name",user.first_name)+"</button>");
	dialog.find(".user_info_link").attr("href","http://www.facebook.com/profile.php?id="+user.uid);
	dialog.find(".user_pic").attr("src",user.pic_square);
	dialog.find(".user_name").text(user.name);
	dialog.find(".user_level").text(user.level);
	dialog.find(".user_last_update").text(user.last_update);
	dialog.find(".user_first_name").text(user.first_name);
	if (user.comment!="") dialog.find(".user_comment").show().text(user.comment);
	else dialog.find(".user_comment").hide();

	d = dialog.find(".user_give");
	d.html("");
	if (user.give_match.length>0)
	{
		for (i=0;i<user.give_match.length;i++)
		{
			iid = user.give_match[i].iid;
			title = user.give_match[i].name;
			if (user.give_match[i].value)
			{
				title += " "+(new Array(Number(user.give_match[i].value)+1).join("*"));
			}
			d.append("<div class=\"trade-ingredient\" id=\"trade_"+iid+"\"><img class=\"ingr32 ingr32-"+iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" /></div>");
		}
		d.append("<br clear=\"all\" />");
	};
	for (i=0;i<user.give.length;i++)
	{
		iid = user.give[i].iid;
		title = user.give[i].name;
		if (user.give[i].value)
		{
			title += " "+(new Array(Number(user.give[i].value)+1).join("*"));
		}
		d.append("<div class=\"trade-ingredient\" id=\"trade_"+iid+"\"><img class=\"fade ingr24 ingr24-"+iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" /></div>");
	}
	d = dialog.find(".user_want");
	d.html("");
	if (user.want_match.length>0)
	{
		for (i=0;i<user.want_match.length;i++)
		{
			iid = user.want_match[i].iid;
			title = user.want_match[i].name;
			if (user.want_match[i].value)
			{
				title += " "+(new Array(Number(user.want_match[i].value)+1).join("*"));
			}
			d.append("<div class=\"trade-ingredient\" id=\"trade_"+iid+"\"><img class=\"ingr32 ingr32-"+iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" /></div>");
		}
		d.append("<br clear=\"all\" />");
	}
	for (i=0;i<user.want.length;i++)
	{
		iid = user.want[i].iid;
		title = user.want[i].name;
		if (user.want[i].value)
		{
			title += " "+(new Array(Number(user.want[i].value)+1).join("*"));
		}
		d.append("<div class=\"trade-ingredient\" id=\"trade_"+iid+"\"><img class=\"fade ingr24 ingr24-"+iid+"\" src=\""+staticurl[0]+"img/spacer.gif\" alt=\""+title+"\" /></div>");
	}
	dialog.find(".trade-ingredient").mouseenter(function(){
		var o = dialog.offset();
		hint_show($(this),$("img",this),-o.left,-o.top);
	}).mouseleave(function(){
		hint_hide();
	}).click(function(){
		var i = $(this);
		if (i.hasClass("selected"))
		{
			i.removeClass("selected");
		}
		else
		{
			i.parent().find(".trade-ingredient.selected").removeClass("selected");
			i.addClass("selected");
		}
		trade_check_ok(dialog);
	});
	t = dialog.find(".pre-trade");
	t.attr("disabled","disabled").addClass("fade").one("click",function(e){
		dialog.hide();

		var trade_dialog = modal_dialog("trade_dialog",e);
		trade_dialog.attr("uid",user.uid);
		trade_dialog.find(".user_first_name").text(user.first_name);
		trade_dialog.find(".trade_send").one("click",function(){
			var params = {
				trade: trade_dialog.attr("uid"),
				want: Number(dialog.find(".user_give .trade-ingredient.selected").attr("id").replace("trade_","")),
				give: Number(dialog.find(".user_want .trade-ingredient.selected").attr("id").replace("trade_","")),
				trade_comment: trade_dialog.find("#trade_comment").val()
			};
			do_ajax($.param(params));
			try {
				pageTracker._trackEvent("fb","trade");
			} catch(err) {}
			trade_dialog.find("#trade_comment").val("");
			modal_close(trade_dialog);
		});
		modal_show(trade_dialog);
	});

	d = dialog.find(".user_evaluation");
	d.html("");
	if (user.neval>0)
	{
		p = (user.neval+user.eval)/2;
		n = user.neval-p;
		d.append("<div>");
		for (i=0;i<p;i++)
		{
			d.append("<img src=\""+staticurl[0]+"img/spacer.gif\" alt=\"+\" class=\"eval eval_up\" />");
		}
		for (i=0;i<n;i++)
		{
			d.append("<img src=\""+staticurl[0]+"img/spacer.gif\" alt=\"-\" class=\"eval eval_down\" />");
		}
		d.append("</div>");
	}
	d = dialog.find("div.eval");
	if ((user.uid!=fb_user) && (user.was_friend))
	{
		i = d.find("img");
		i.addClass("fade");
		if (user.can_rate)
		{
			i.addClass("rate").click(function(e){
				dialog.hide();
				var rate = 1;
				if (this.alt=="-") rate = -1;
				var rate_dialog = modal_dialog("rate_dialog",e);
				rate_dialog.attr("rate",rate);
				rate_dialog.attr("uid",user.uid);
				rate_dialog.find(".user_first_name").text(user.first_name);
				if (rate>0)
				{
					$("#rate_warning").hide();
					document.getElementById("rate_ok").checked = true;;
				}
				else
				{
					$("#rate_warning").show();
					document.getElementById("rate_ok").checked = false;;
				}
				rate_dialog.find(".rate_send").attr("disabled","disabled").addClass("fade").one("click",function(){
					var uid = rate_dialog.attr("uid");
					var rate = rate_dialog.attr("rate");
					if (rate_dialog.find("#rate_comment").val()=="") return;
					for (var t=0;t<traders.length;t++)
					{
						if (traders[t].uid==uid)
						{
							traders[t].rate = rate;
							traders[t].can_rate = false;
							break;
						}
					}
					var params = {
						rate: uid+"_"+rate,
						rate_comment: rate_dialog.find("#rate_comment").val()
					};
					do_ajax($.param(params));
					try {
						pageTracker._trackEvent("fb","rate",(rate>0) ? "positive" : "negative");
					} catch(err) {}
					rate_dialog.find("#rate_comment").val("");
					modal_close(rate_dialog);
				});
				modal_show(rate_dialog);
				$("#rate_comment").keyup(function(){ rate_check_ok(rate_dialog); }).get(0).focus();
				$("#rate_ok").click(function(){ rate_check_ok(rate_dialog); });
			});
		}
		else
		{
			i.removeClass("rate").unbind("click");
		}
		if (user.rate>0)
		{
			i.filter("[alt='+']").removeClass("fade");
		}
		else if (user.rate<0)
		{
			i.filter("[alt='-']").removeClass("fade");
		}
		d.show();
	}
	else
	{
		d.hide();
	}
	dialog.find(".user_busy").hide();
	dialog.find(".user_info").show();
	modal_resize(dialog);
}

function rate_check_ok(rate_dialog)
{
	var comment = document.getElementById("rate_comment");
	var rate_ok = document.getElementById("rate_ok");

	if ((comment.value.length<3) || (!rate_ok.checked))
	{
		rate_dialog.find(".rate_send").attr("disabled","disabled").addClass("fade");
	}
	else
	{
		rate_dialog.find(".rate_send").removeAttr("disabled").removeClass("fade");
	}
}

function trade_check_ok(dialog)
{
	if (!fb_user)
	{
		init_user();
		return;
	}
	var want = dialog.find(".user_give .trade-ingredient.selected");
	var give = dialog.find(".user_want .trade-ingredient.selected");
	
	if ((want.length==1) && (give.length==1))
	{
		dialog.find(".pre-trade").removeAttr("disabled").removeClass("fade");
	}
	else
	{
		dialog.find(".pre-trade").attr("disabled","disabled").addClass("fade");
	}
}

function trade_status(id,status)
{
	var params = {
		trade_status: id+"_"+status
	};
	do_ajax($.param(params),function(res){
		process_ajax(res);
		$("#trade_"+id).find("img").each(function(){
			var a = $(this).closest("a");
			$(this).appendTo(a.parent());
			a.remove();
			if (!$(this).hasClass("trade_"+status))
			{
				$(this).addClass("blank");
				try {
					pageTracker._trackEvent("fb","trade_status",status);
				} catch(err) {}
				if (status=="accept")
				{
					var uid,my_ingr,their_ingr;
					for (var i=0;i<messages.length;i++)
					{
						if (messages[i].id==id)
						{
							uid = messages[i].uid_from;
							my_ingr = document.getElementById("iid_to_"+id).alt.replace(/ \**$/,"").toLowerCase();
							their_ingr = document.getElementById("iid_from_"+id).alt.replace(/ \**$/,"").toLowerCase();
						}
					}
					var params = {
						caption: "{*actor*} accepted to trade their "+my_ingr+" for your "+their_ingr+".",
						media: [{
							type: "image",
							src: "http://fb.yris.be/rcmarket/img/logo.png",
							href: "http://fb.yris.be/rcmarket/"
						}]
					};
					var actions = [{
						text: "Trade",
						href: "http://apps.facebook.com/rcmarket/"
					}];
					FB.Connect.streamPublish("",params,actions,uid);
				}
			}
		});
	});
}

function friends_sort(type)
{
	if (type==sort)
	{
		if (dir=='asc') dir = 'desc';
		else dir = 'asc';
	}
	else
	{
		sort = type;
		dir = 'asc';
	}
	do_ajax('friends=1&page='+page+'&sort='+sort+'&dir='+dir);
}

function show_addme(id)
{
	var addme = $("#addme_"+id);
	if (addme.length==0) return;
	addme.animate({"marginRight": 0},500,"linear",function(){ show_addme(id+1); });
}

function init_facebook(key)
{
	FB.init(key,"xd_receiver.htm");
	FB_RequireFeatures(["XFBML","Api"],function(){
		if (debug==1)
		{
			FB.FBDebug.logLevel = 4;
			FB.FBDebug.isEnabled = true;
		}
		FB.Facebook.init(key,"xd_receiver.htm",null);
		api_client = FB.Facebook.apiClient;
	});
	FB_RequireFeatures(["CanvasUtil"],function(){
		autopos_dialogs = true;
		on_resize();
//		FB.CanvasClient.syncUrl();
		$(document).ready(on_resize);
		$(document).bind("ajaxStop",function(){
			on_resize();
		});
	});
}

function on_resize()
{
	FB.CanvasClient.setCanvasHeight((Number($(document).height())+40)+"px");
}

function init_user()
{
	FB.Connect.requireSession(function(){
		fb_user = FB.Connect.get_loggedInUser();
	});
}

function htmlspecialchars(str)
{
	if (str==null) return "";
	str = str.split('&').join('&amp;');
	str = str.split('"').join('&quot;');
	str = str.split('\'').join('&#039;');
	str = str.split('<').join('&lt;');
	str = str.split('>').join('&gt;');
	return str;
}
