﻿var oData;
var sValue;
var oReg;
var oMatch;
var iSelection = 0;
var eSelected = null;
var bIsSearch = false;
var bLoading = false;
var aLoad;
var iLoad = 0;
var oLoadTimer;

$(document).ready(function() {
	$.ajaxSetup({ cache: false });
	$(document).pngFix();

	// toggle tabs
	var eImg;
	$(".menu .toggle").toggle(function() {
		eImg = $($(this).children().get(1));
		($(this)).blur();
		if (!$.browser.msie) {
			$($(this).parent().get(0)).children(".data").slideDown("medium");
			$(eImg).slideUp("fast", function() { arrow(eImg, "up"); });
		} else {
			$($(this).parent().get(0)).children(".data").show();
			$(eImg).hide(1, function() { arrow(eImg, "up"); });
		}
	}, function() {
		eImg = $($(this).children().get(1));
		($(this)).blur();
		if (!$.browser.msie) {
			$($(this).parent().get(0)).children(".data").slideUp("medium");
			$(eImg).slideUp("fast", function() { arrow(eImg, "down"); });
		} else {
			$($(this).parent().get(0)).children(".data").hide();
			$(eImg).hide(1, function() { arrow(eImg, "down"); });
		}
	});
	function arrow(eImg, sTo) {
		var sFrom = (sTo == "up") ? "down" : "up";
		$(eImg).attr("src", ($(eImg).attr("src")).replace(sFrom, sTo));
		if (!$.browser.msie) $(eImg).slideDown("fast");
		else $(eImg).show();
	};
	$(".menu .toggle").mouseover(function() {
		$(this).children(":last-child").css("opacity", "1");
	}).mouseout(function() {
		$(this).children(":last-child").css("opacity", "0.6");
	}).children(":last-child").css("opacity", "0.6");
	if ($("#load").length) {
		if ($("#load").val().length) {
			aLoad = ($("#load").val()).split(",");
			triggerLoad();
		}
	}

	if ($("#tabUpdates, #tabRequests, #tabInvites").length) {
		var sSource;
		var sQuery = (location.search.length > 0) ? location.search.replace("?", "") : "";
		var sContent = sQuery.length ? (sQuery == "friends" ? "Requests" : "Invites") : "Updates";
		var sShow;
		if (!$("#tab" + sContent).length) sContent = "Updates";
		myRA(sContent);

		$("#tabUpdates, #tabRequests, #tabInvites").click(function() {
			sSource = $(this).attr("id").replace("tab", "");
			if (sSource == sContent || bLoading) return false;
			$("#tab" + sContent).removeClass("t-on").addClass("t-off");
			sContent = sSource;
			$("#tab" + sContent).removeClass("t-off").addClass("t-on");
			$("#content").css("opacity", "0.4");
			$("#content").after($("<div id=\"loadingCon\" style=\"position:absolute;top:50px;left:0;width:669px;text-align:center;\"><div id=\"loading\" style=\"width:100px;height:100px;margin:0 auto;\"></div></div>"));
			if (!$.browser.msie)
				swfobject.embedSWF("/flash/loading/loading.swf", "loading", "100", "100", "9.0.0", "js/expressInstall.swf", { s: 40, c: "white" }, {}, { quality: "height", menu: "false", wmode: "transparent" });
			else
				$("#loadingCon").html($("<div style=\"width:100px;padding:10px;\" class=\"f16 b white dark-bg\">LOADING</div>"));
			myRA(sContent);
		});
	};

	// contact suggest
	if ($("input[name='addrecipient']").length) {
		var sExistSend = ($("input[name='sendto']").val().length > 0) ? "?e=" + $("input[name='sendto']").val() : "";
		$.getJSON("/mycontacts.aspx" + sExistSend,
			function(data) {
				oData = data;

				// if existing sendto via querystring
				if ($("input[name='sendto']").val().length > 0) {
					var sSentTo = ($("input[name='sendto']").val()).split(",");
					$("input[name='sendto']").val("");
					for (var i = 0; i < sSentTo.length; i++)
						selectContact(sSentTo[i]);
				}
			});

		$("input[name='addrecipient']").keyup(function(event) {
			if (oData) {
				sValue = ($(this)).val();
				if (sValue.length == 0 || /27/.test(event.keyCode) || (/13/.test(event.keyCode) && !bIsSearch)) {
					removeContacts();
					return;
				}

				// clear contacts element
				if ($("#contacts").length > 0)
					$("#contacts").html("");
				else {
					$($(this).parent().get(0)).append("<div id=\"contacts\" class=\"interact-bg black12\"></div>");
					$(document).bind("keyup", function(e) { keySelection(e); });
					$("form").bind("submit", function(e) { return false; });
				}
				$("#contacts").attr("style", "visibility:hidden;position:absolute;top:23px;left:0px;width:144px;overflow:auto;z-index:10;");
				searchContacts(sValue, 1);
			}
			$("input[name='addrecipient']").blur(function() { if (!bIsSearch) selectContact(); });
		}).focus();
	}

	// add to control (friends, favs)
	if ($(".addTo a").length) bindAddClick();
});

function bindAddClick() {
	$(".addTo a, .remove").bind("click", function(event) {
		// oConfig.t = Type, oConfig.i = Item, oConfig.a = Action, oConfig.u = User
		var sSrc = event.target.nodeName.toLowerCase();
		var eContainer = (sSrc == "img") ? $($($(event.target).parent().get(0)).parent().get(0)) : ($(event.target).parent().get(0));
		var oConfig = eval("(" + $(eContainer).children("span").html() + ")");
		var sMsg = "";
		var eAdd = (sSrc == "img") ? $($(event.target).parent().get(0)).blur() : $(event.target);
		var sHref;
		var sImg;
		var bRemove;
		var bSpecial = false; // used for special cases with multi actions (ie. remove friend on event invites)

		if (bLoading) return false;
		if ($(eAdd).attr("href").indexOf("#") != -1) sHref = ($(eAdd).attr("href")).split("#")[1];
		else return true;

		if (sHref.indexOf("sp-") != -1) {
			$(this).unbind("click");
			bSpecial = true;
			sSrc = "img";
			eContainer = $(eContainer).offsetParent().offsetParent().offsetParent().find(".addTo");
			eAdd = $(eContainer).find("a[href='#deny']");
			oConfig = eval("(" + $(eContainer).find(".hide").html() + ")");
		}

		if (sHref == "sp-remove") oConfig.a = "3";
		if (sHref == "deny") oConfig.a = "3";
		if (sHref == "block") oConfig.a = "5";
		if (sHref == "unblock") oConfig.a = "6";
		if ((oConfig.t == 1 && oConfig.a == 4) || sHref == "sp-remove") {
			bRemove = confirm("Are you sure you want to remove " + oConfig.u + " from your friends?");
			if (!bRemove) {
				bindAddClick();
				return false;
			}
		}
		if (oConfig.t == 1 && oConfig.a == 5) {
			bRemove = confirm("Are you sure you want to block " + oConfig.u + "?");
			if (!bRemove) {
				bindAddClick();
				return false;
			}
		}
		$(this).fadeTo("medium", 0.5);
		bLoading = true;
		process(this);
		return false;

		function process(eSrc) {
			$.getJSON("/add-to.aspx?t=" + oConfig.t + "&i=" + oConfig.i + "&a=" + oConfig.a + "&u=" + oConfig.u,
				function(data) {
					if (!bSpecial) bindAddClick();
					bLoading = false;
					switch (oConfig.t) {
						case "1": // friends
							if (data.status == "true") {
								// oConfig.a: 1 = request, 2 = approve, 3 = deny, 4 = delete
								$(eAdd).unbind("click");
								if (!bSpecial) {
									switch (oConfig.a) {
										case "1":
											sMsg = "Request has been sent";
											sImg = "/images/interact/icon/fr-pending.gif";
											break;
										case "2":
											sMsg = "You are now friends";
											sImg = "/images/interact/icon/fr-approved.gif";
											$(eContainer).children(".approve, .deny").attr("onmouseover", "").attr("onmouseout", "").unbind("click").css("opacity", 0.5);
											$($(eContainer).children(".friends, .block")).mouseout(function() { togTxt(this, "You are now friends"); });
											break;
										case "3":
											sMsg = "Request has been denied";
											sImg = "/images/interact/icon/fr-denied.gif";
											$(eContainer).children(".approve, .deny").attr("onmouseover", "").attr("onmouseout", "").unbind("click").css("opacity", 0.5);
											$($(eContainer).children(".friends, .block")).mouseout(function() { togTxt(this, "Request has been denied"); });
											break;
										case "4":
											sMsg = "Removed from friends";
											sImg = "/images/interact/icon/fr-removed.gif";
											$(eContainer).children("a").unbind("click").attr("onmouseover", "").attr("onmouseout", "").css("opacity", 0.5);
											break;
										case "5":
											sMsg = "Blocked";
											sImg = "/images/interact/icon/fr-blocked.gif";
											$(eContainer).children("a").unbind("click").attr("onmouseover", "").attr("onmouseout", "").css("opacity", 0.5);
											break;
										case "6":
											sMsg = "Unblocked";
											sImg = "/images/interact/icon/fr-unblocked.gif";
											$(eContainer).children("a").unbind("click").attr("onmouseover", "").attr("onmouseout", "");
											break;
									};
									if (sSrc == "img") {
										if (sImg.length) $($(eAdd).children().get(0)).attr("src", sImg);
										$(eAdd).mouseover(function() { togTxt(eAdd, sMsg); });
										togTxt(eAdd, sMsg);
									} else
										$(eAdd).html(sMsg);
								}
							}
							if (!bSpecial) $(eSrc).css("opacity", 1);
							break;

						case "2": // invites
							if (data.status == "true") {
								// oConfig.a: 1 = attending, 3 = not attending
								$(eAdd).unbind("click");
								switch (oConfig.a) {
									case "1":
										sMsg = "Attending";
										sImg = "/images/interact/icon/fr-approved.gif";
										$(eContainer).children("a").removeAttr("onmouseover").removeAttr("onmouseout").unbind("click").css("opacity", 0.5);
										break;
									case "3":
										sMsg = "Not attending";
										sImg = "/images/interact/icon/fr-denied.gif";
										$(eContainer).children("a").removeAttr("onmouseover").removeAttr("onmouseout").unbind("click").css("opacity", 0.5);
										break;
								};
								if (sSrc == "img") {
									if (sImg.length) $($(eAdd).children().get(0)).attr("src", sImg);
									$(eAdd).mouseover(function() { togTxt(eAdd, sMsg); });
									togTxt(eAdd, sMsg);
								} else
									$(eAdd).html(sMsg);

								if (sHref == "sp-remove") {
									$($(eSrc).parents().get(0)).html(oConfig.u + " has been removed from your friends.")
									oConfig.t = "1";
									oConfig.a = "3";
									process(this);
								}
							}
							$(eSrc).css("opacity", 1);
							break;
					};
				});
		}
	});
};

function togTxt(eLink, sMsg) {
	sMsg = (sMsg.length == 0) ? "<br />" : unescape(sMsg);
	$($($(eLink).parent().get(0)).children().get(0)).html(sMsg);
};


/*** My RA display ***/

function myRA(sContent) {
	var sURL;
	switch (sContent) {
		case "Updates": sURL = "my-updates"; break;
		case "Requests": sURL = "my-friends"; break;
		case "Invites": sURL = "my-invites"; break;
	};
	bLoading = true;
	$.getJSON("/" + sURL + ".aspx",
		function(data) {
			switch (sContent) {
				case "Updates": myUpdates(data); break;
				case "Requests": myFriends(data); break;
				case "Invites": myInvites(data); break;
			};
			bLoading = false;
		});
}

function myUpdates(data) {
	var sSectionLink = "<a href=\"/##1##\" class=\"f10 ##2##-rev\">##3##</a> ";
	var sCommentLink = "<a href=\"/##1##\" class=\"f10 interact-rev\">##2##</a> ";
	var eItem;
	var sOutput;
	var bNew;
	var bNewEvents = false;
	var iLowCount = 10;
	$("#content").html("");

	$.each(data.updates, function (i, row) {
		bNew = parseInt(row.isnew);
		eItem = (bNew) ? $("<div class=\"hr-top\" style=\"margin:16px 8px 8px 0\"></div>") : $("<div style=\"margin:8px 8px 8px 0\"></div>");

		switch (parseInt(row.section)) {
			case 1: // new events submitted
				bNewEvents = true;
				if (bNew) {
					sOutput = replaceString(sSectionLink, "events.aspx", "local", "Events")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<a href=\"/events.aspx?ai=" + data.areaid + "\" class=\"total white b\">" + row.L1 + "</a> "
					+ "in <a href=\"/events.aspx?ai=" + data.areaid + "\" class=\"white b\">" + row.L2 + "</a> " + row.T1
					+ "<input type=\"hidden\" name=\"date\" value=\"" + row.date + "\" />"
					+ "</div>";
				break;

			case 3: // photos
				sOutput = replaceString(sSectionLink, "events.aspx", "local", "Events")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update white pt4 pb8\">"
					+ "<a href=\"/photo-gallery.aspx?set=" + row.item + "\" class=\"white b\">"
					+ "<img src=\"" + row.img + "\" alt=\"\" width=\"152\" height=\"100\" border=\"0\" class=\"fl mr8\" />" + row.title + "</a><br />";
				if (row.intro.length > 0) sOutput += row.intro + "<br />";
				sOutput += "<span class=\"grey f10\">Photos by <a href=\"" + row.contact + "\" class=\"grey\">" + row.author + "</a></span>"
					+ "</div><div class=\"clear\"></div>";
				break;

			case 4: // local news
			case 5: // fav dj news
				sOutput = replaceString(sSectionLink, "news.aspx", "global", "News")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\"><a href=\"/news.aspx?id=" + row.item + "\" class=\"white b\">" + row.title + "</a><br />" + row.intro + "<br />"
					+ "<span class=\"f10 grey\">";
				if (row.section == 5) sOutput += "Favourite / <a href=\"/dj/" + row.djurl + "\" class=\"grey\">" + row.dj + "</a>";
				else sOutput += "Location / <a href=\"/local.aspx\" class=\"grey\">" + data.areaname + "</a>";
				sOutput += "</span></div>";
				break;

			case 6: // features
				sOutput = replaceString(sSectionLink, "features.aspx", "global", "Features")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\">"
					+ "<a href=\"/feature.aspx?id=" + row.item + "\" class=\"white b\">"
					+ "<img src=\"" + row.img + "\" alt=\"\" width=\"312\" height=\"116\" border=\"0\" class=\"fl mr8\" />"
					+ row.title + "</a><br />" + row.intro + "<br />"
					+ "<span class=\"grey f10\">Favourite / <a href=\"/dj/" + row.djurl + "\" class=\"grey\">" + row.dj + "</a></span>"
					+ "</div><div class=\"clear\"></div>";
				break;

			case 7: // reviews with fav djs
			case 8: // reviews with fav labels
				sOutput = replaceString(sSectionLink, "reviews.aspx", "music", "Reviews")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\">"
					+ "<a href=\"/review-view.aspx?id=" + row.item + "\" class=\"white b\">";
				if (row.img.length > 0) sOutput += "<img src=\"" + row.img + "\" alt=\"\" width=\"100\" height=\"100\" border=\"0\" class=\"fl mr8\" />";
				sOutput += row.title + "</a><br />" + row.intro + "<br />"
					+ "<span class=\"grey f10\">Reviewed by <a href=\"" + row.contact + "\" class=\"grey\">" + row.author + "</a><br />"
					+ "<span style=\"line-height:10px;\">Favourite / ";

				if (row.rls) {
					$.each(row.rls, function (a, label) {
						sOutput += "<a href=\"/record-label.aspx?id=" + label.rlid + "\" class=\"grey\">" + label.rl + "</a>";
						if (a < row.rls.length - 1) sOutput += ", ";
					});
				}
				if (row.rls && row.djs) sOutput += ", ";
				if (row.djs) {
					$.each(row.djs, function (a, artist) {
						sOutput += "<a href=\"/dj/" + artist.djurl + "\" class=\"grey\">" + artist.dj + "</a>";
						if (a < row.djs.length - 1) sOutput += ", ";
					});
				}
				sOutput += "</span></span><div class=\"clear\"></div></div>";
				break;

			case 9: // dj feeds
				sOutput = replaceString(sSectionLink, "dj-feeds.aspx", "music", "DJ Feeds")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\">";
				if (row.status == 1) sOutput += "<a href=\"/feed-item.aspx?id=" + row.item + "\" class=\"white b\">";
				else sOutput += "<a href=\"/dj/" + row.djurl + "/feed?item=" + row.item + "\" class=\"white b\">";
				sOutput += row.title + "</a><br />";
				if (row.intro.length > 0) sOutput += row.intro + "<br />";
				sOutput += "<span class=\"grey f10\">Favourite / <a href=\"/dj/" + row.djurl + "\" class=\"grey\">" + row.dj + "</a></span>"
					+ "</div><div class=\"clear\"></div>";
				break;

			case 10: // charts
				if (bNew) {
					sOutput = replaceString(sSectionLink, "dj-charts.aspx", "music", "Charts")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<a href=\"/dj/" + row.djurl + "/top10?chart=" + row.item + "\" class=\"white b\">"
					+ "<img src=\"" + row.img + "\" alt=\"\" width=\"60\" height=\"60\" border=\"0\" class=\"fl mr8\" />"
					+ row.dj + "<br />" + row.chart + " Chart</a>"
					+ "<div class=\"clear\"></div></div>";
				break;

			case 11: // track charted
				if (bNew) {
					sOutput = replaceString(sSectionLink, "dj-charts.aspx", "music", "Charts")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<strong>" + ((row.verified) ? "<a href=\"/track.aspx?" + row.tid + "\" class=\"music\" style=\"padding:0;\">" + row.track + "</a>" : row.track) + "</strong> was recently charted by ";
				$.each(row.djs, function (a, artist) {
					sOutput += "<a href=\"/dj/" + artist.djurl + "/top10\" class=\"white b\">" + artist.dj + "</a>";
					if (a < row.djs.length - 1) sOutput += ", ";
				});
				sOutput += ".</div>";
				break;

			case 12: // podcast
				sOutput = replaceString(sSectionLink, "podcast.aspx", "music", "Podcasts")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\">"
					+ "<a href=\"/podcast-episode.aspx?id=" + row.item + "\" class=\"white b\">"
					+ "<img src=\"" + row.img + "\" alt=\"\" width=\"152\" height=\"152\" border=\"0\" class=\"fl mr8\" />"
					+ row.title + "</a><br />" + row.intro
					+ "</div><div class=\"clear\"></div>";
				break;

			case 14: // friends added
				if (bNew) {
					sOutput = replaceString(sSectionLink, "profile/" + row.user + "/friends", "interact", "Friends")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<a href=\"http://www.residentadvisor.net/profile/" + row.friend + "\" class=\"white b\" style=\"line-height:30px;\">"
					+ "<img src=\"/images/user/av/" + row.img + "\" width=\"36\" height=\"36\" border=\"0\" class=\"fl mr8\" />"
					+ row.friend + "</a> is now your friend."
					+ "<div class=\"clear\"></div></div>";
				break;

			case 15: // friend's roll call (>= 3)
				if (bNew) {
					sOutput = replaceString(sSectionLink, "events.aspx", "local", "Events")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				if (row.img.length > 0) sOutput += "<a href=\"/event.aspx?" + row.item + "\" class=\"white b\"><img src=\"" + row.img + "\" width=\"152\" height=\"76\" border=\"0\" class=\"fl mr8\" /></a>";
				sOutput += "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<a href=\"/event.aspx?" + row.item + "\" class=\"white b\">" + row.event + "</a> at "
					+ "<a href=\"/club-detail.aspx?id=" + row.clubid + "\" class=\"white b\">" + convertThe(row.club) + "</a><br />"
					+ Friends(row.friends) + " are attending."
					+ "<div class=\"clear\"></div></div>";
				break;

			case 16: // friend's add DJs to favs
				if (bNew) {
					sOutput = replaceString(sSectionLink, "djs.aspx", "music", "DJ Pages")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<a href=\"/dj/" + row.djurl + "\" class=\"white b\"><img src=\"" + row.img + "\" alt=\"\" width=\"60\" height=\"60\" border=\"0\" class=\"fl mr8\" /></a>"
					+ Friends(row.friends) + "<br />added <a href=\"/dj/" + row.djurl + "\" class=\"white b\">" + row.dj + "</a> to their favourites.<br />"
					+ "<a href=\"/user-favs.aspx?dj=" + row.item + "\" class=\"f10 grey\">Add to favourites</a>"
					+ "<div class=\"clear\"></div></div>";
				break;

			case 17: // friend's add labels to favs
				if (bNew) {
					sOutput = replaceString(sSectionLink, "labels.aspx", "music", "Labels")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += "<a href=\"/record-label.aspx?id=" + row.item + "\" class=\"white b\"><img src=\"" + row.img + "\" alt=\"\" width=\"100\" height=\"40\" border=\"0\" class=\"fl mr8\" /></a>"
					+ Friends(row.friends) + "<br />added <a href=\"/record-label.aspx?id=" + row.item + "\" class=\"white b\">" + row.title + "</a> to their favourites.<br />"
					+ "<a href=\"/user-favs.aspx?rl=" + row.item + "\" class=\"f10 grey\">Add to favourites</a>"
					+ "<div class=\"clear\"></div></div>";
				break;

			case 18: // friend's add clubs to favs
				if (bNew) {
					sOutput = replaceString(sSectionLink, "clubs.aspx", "local", "Clubs")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				if (row.img > 0) sOutput += "<a href=\"/club-detail.aspx?id=" + row.item + "\" class=\"white b\"><img src=\"/images/links/" + row.img + "\" alt=\"\" width=\"100\" height=\"40\" border=\"0\" class=\"fl mr8\" /></a>";
				sOutput += Friends(row.friends) + "<br />added <a href=\"/club-detail.aspx?id=" + row.item + "\" class=\"white b\">" + convertThe(row.title) + "</a> to their favourites.<br />"
					+ "<a href=\"/user-favs.aspx?vn=" + row.item + "\" class=\"f10 grey\">Add to favourites</a>"
					+ "<div class=\"clear\"></div></div>";
				break;

			case 19: // friend's add promoters to favs
				if (bNew) {
					sOutput = replaceString(sSectionLink, "promoters.aspx", "local", "Promoters")
						+ "&nbsp; <div class=\"update pt4\">";
				} else
					sOutput = "<div class=\"update\">";

				sOutput += Friends(row.friends) + "<br />added <a href=\"/promoter.aspx?id=" + row.item + "\" class=\"white b\">" + row.title + "</a> to their favourites.<br />"
					+ "<a href=\"/user-favs.aspx?pr=" + row.item + "\" class=\"f10 grey\">Add to favourites</a>"
					+ "<div class=\"clear\"></div></div>";
				break;

			case 20: // exchange
				sOutput = replaceString(sSectionLink, "podcast.aspx", "music", "Podcasts")
					+ replaceString(sCommentLink, row.forum, row.comment)
					+ "<span class=\"f10 grey\">" + row.date + "</span><br />"
					+ "<div class=\"update pt4\">"
					+ "<a href=\"/podcast-episode.aspx?exchange=" + row.item + "\" class=\"white b\">"
					+ "<img src=\"" + row.img + "\" alt=\"\" width=\"152\" height=\"152\" border=\"0\" class=\"fl mr8\" />"
					+ row.title + "</a><br />" + row.intro
					+ "</div><div class=\"clear\"></div>";
				break;
		};
		eItem.html(sOutput);
		$("#content").append(eItem);
		sOutput = "";
	});
	$("#content").append($("<br /><br /><div class=\"clear\"></div>"));
	if (iLowCount >= data.updates.length) {
		sOutput = "<div class=\"grey pt16\">"
			+ "<div class=\"pb4\">Would you like to see more updates? It's simple. "
			+ "By adding your favourite <a href=\"/dj.aspx\" class=\"grey\">DJs</a>, <a href=\"/labels.aspx\" class=\"grey\">labels</a>, <a href=\"/clubs.aspx\" class=\"grey\">clubs</a> and <a href=\"/promoters.aspx\" class=\"grey\">promoters</a>, you can stay up-to-date on stuff that matters to you.</div>"
			+ "</div><br />";
		$("#content").append($(sOutput));
	}
	$("#loadingCon").remove();
	$("#content").fadeTo("medium", 1);

	// new events
	if (bNewEvents) {
		$("a.total").toggle(function() {
			var LIST_COUNT = 20;
			var sOutput = "";
			var eList = $($(this).parent().get(0));
			var eData = $("<div class=\"events-list\"></div>");
			var sDate = eList.children("input").val();
			var iAreaID = $("#AreaID").val();
			var bListReached = false;

			($(this)).blur();
			$(eList.parent().get(0)).css("background-color", "#4c5967");
			$.getJSON("/services/myupdates.ashx?d=" + sDate + "&ai=" + iAreaID,
				function(data) {
					sOutput += "<div class=\"pt8\"></div>";
					$.each(data.events, function(i, item) {
						if (i == LIST_COUNT) {
							bListReached = true;
							return false;
						}
						sOutput += "<a href=\"/event.aspx?" + item.id + "\" class=\"white b\">" + item.title + "</a> at <a href=\"/club-detail.aspx?id=" + item.vid + "\" class=\"white b\">" + item.venue + "</a> &nbsp;<span class=\"f10 grey\">" + item.date + "</span><br />";
					});
					sOutput += "<div class=\"grey pt8\"\">";
					if (bListReached) sOutput += "<span class=\"grey\">Showing " + LIST_COUNT + " from " + data.events.length + " events listed.</span><br />";
					sOutput += "<span class=\"local\"><a href=\"/events.aspx\" class=\"local\">Events</a>&nbsp;/&nbsp; "
						+ "<a href=\"/events.aspx?show=all\" class=\"local\">View all regions</a>&nbsp;/&nbsp; "
						+ "<a href=\"/user-events.aspx\" class=\"local\">My Events</a></span></div>";
					eData.append(sOutput);
					eList.append(eData.attr("style", "position:absolute;top:0;left:0;"));
					eData.attr("style", "display:none;");
					$(eList.parent().get(0)).css("background-color", "transparent");

					if (!$.browser.msie)
						eData.slideDown("medium", function() { eData.children("div").css("style", "visibility:visible;float:left;"); });
					else
						eData.show(1, function() { eData.children("div").css("style", "visibility:visible;float:left;"); });
				});
		}, function() {
			($(this)).blur();
			if (!$.browser.msie)
				$($(this).parent().get(0)).children(".events-list").slideUp("medium", function() { $($(this).parent().get(0)).children(".events-list").remove(); });
			else
				$($(this).parent().get(0)).children(".events-list").show(1, function() { $($(this).parent().get(0)).children(".events-list").remove(); });
		});
	}

	function Friends(sFriends) {
		var matches = sFriends.match(/##(.*?)##/g);
		var link = "<a href=\"/profile/##1##\" class=\"white b\">##1##</a>";
		$.each(matches, function(m, match) {
			sFriends = sFriends.replace(match, replaceString(link, match.replace(/##/g, "")));
		});
		return sFriends;
	};
};

function myFriends(data) {
	var sOutput;
	var sConfig;
	var sListingImage;
	if (parseInt(data.status)) {
		var sMulti = (data.friends.length > 1) ? "s" : "";
		sOutput = "<p class=\"grey pb8\">RA recommends approving only people you know.</p>"
			+ "<table cellpadding=0 cellspacing=0 border=0 width=624>"
			+ "<col width=\"84\" /><col width=\"236\" /><col width=\"304\" />"
			+ "<tr valign=\"bottom\" class=\"dark-bg\"><td height=\"42\"></td>"
			+ "<td class=\"white16b\">" + data.friends.length + " friend" + sMulti + "</td>"
			+ "<td class=\"white12b\"><div class=\"fr\" style=\"padding-right:2px;\"><a id=\"removeAll\" href=\"#remove-all\" class=\"f10 grey\">Remove all requests</a></div>Actions</td></tr>"
			+ "<tr><td colspan=3 class=main-bg><img src=/images/clear.gif width=1 height=1 alt=\"\" /></td></tr>";

		$.each(data.friends, function(i, item) {
			sConfig = "<span class=\"hide\">{\"t\":\"1\", \"i\":\"0\", \"a\":\"2\", \"u\":\"" + item.user + "\",\"h\":\"white b\"}</span>";
			sListImage = (item.img.length) ? item.img : "default.jpg";

			sOutput += "<tr class=\"black-bg\" onmouseover=\"this.style.backgroundColor='#363636';\" onmouseout=\"this.style.backgroundColor='';\" valign=\"top\">"
				+ "<td class=\"ptb8\" align=\"right\"><a href=\"/profile/" + item.user + "\"><img src=\"/images/user/av/" + sListImage + "\" border=\"0\" height=\"76\" width=\"76\" /></a></td>"
				+ "<td class=\"p8 pl8\"><br><span class=\"f16\"><a href=\"/profile/" + item.user + "\" class=\"white12b\">" + item.user + "</a></span><br>"
				+ "<div class=\"pb8\"></div><span class=\"f10 grey\"></span></td>"
				+ "<td style=\"vertical-align: bottom;\" class=\"ptb8\"><span class=\"addTo null\"><div class=\"grey b pb4\"><br></div>" + sConfig
				+ "<a href=\"#approve\" onmouseover=\"togTxt(this,'Approve " + item.user + " as a friend');\" onmouseout=\"togTxt(this,'');\" class=\"op-but approve\"><img src=\"/images/interact/icon/fr-approve.gif\" alt=\"Approve\" class=\"mr4\" border=\"0\" height=\"36\" width=\"73\"></a>"
				+ "<a href=\"#deny\" onmouseover=\"togTxt(this,'Deny this request');\" onmouseout=\"togTxt(this,'');\" class=\"op-but deny\"><img src=\"/images/interact/icon/fr-deny.gif\" alt=\"Deny\" class=\"mr4\" border=\"0\" height=\"36\" width=\"73\"></a>"
				+ "<a href=\"/profile/" + item.user + "/friends\" onmouseover=\"togTxt(this,'View " + item.user + "%27s friends');\" onmouseout=\"togTxt(this,'');\" class=\"op-but friends\"><img src=\"/images/interact/icon/fr-friends.gif\" alt=\"Send a message\" class=\"mr4\" border=\"0\" height=\"36\" width=\"73\"></a>"
				+ "<a href=\"#block\" onmouseover=\"togTxt(this,'Block " + item.user + "');\" onmouseout=\"togTxt(this,'');\" class=\"op-but block\"><img src=\"/images/interact/icon/fr-block.gif\" alt=\"Block user\" border=\"0\" height=\"36\" width=\"73\"></a></span></td></tr>"
				+ "<tr><td colspan=3 class=main-bg><img src=/images/clear.gif width=1 height=1 border=0 alt=\"\" /></td></tr>";
		});
		sOutput += "<tr><td><br /><br /></td></tr>";
		$("#content").html(sOutput);
		$("#tabRequests p span").text(" " + data.friends.length + " friend request" + sMulti);
		$("#removeAll").click(function() {
			if (confirm("Are you sure you want to remove all friend requests?")) {
				removeAll("requests"); return false;
			}
		});
	} else {
		$("#tabRequests").remove();
		$("#tabUpdates").removeClass("t-off").addClass("t-on");
		myRA("Updates");
		return;
	}
	$("#loadingCon").remove();
	bindAddClick();
	$("#content").fadeTo("medium", 1);

	function Common(friends) {
		var sCommonFriends = "";
		var sMulti = (iCommonFriends > 1) ? "s" : "";
		if (friends.length > 0) {
			$.each(friends, function(i, item) {
				sCommonFriends += "<a href=\"/profile/" + friends.user.toLowerCase() + "\">" + friends.user + "</a>";
				if (i == 3 && friends.length > 4) {
					sCommonFriends += " and " + (iCommonFriends - (i + 1)) + " other" + ((iCommonFriends - (i + 1) > 1) ? "s" : "");
					return false;
				}
				if (i < friends.length - 1) sCommonFriends += ", ";
			});
			sCommonFriends += (iCommonFriends > 1) ? " are common friends" : " is a common friend";
		}
		return sCommonFriends;
	};
};

function myInvites(data) {
	var sOutput = "";
	var sConfig;
	var sListingImage;
	var sVenue;
	if (parseInt(data.status)) {
		sOutput = "<div class=\"fr pt8 pr8 pb2\"><a id=\"removeAll\" href=\"#remove-all\" class=\"f10 grey\">Remove all invites</a></div>";
		var sMulti = (data.invites.length > 1) ? "s" : "";
		$.each(data.invites, function(i, item) {
			sConfig = "<span class=\"hide\">{\"t\":\"2\", \"i\":\"" + item.eventid + "\", \"a\":\"1\", \"u\":\"" + item.user + "\"}</span>";
			sListImage = (item.img.length) ? item.img : "av/d36.jpg";
			sVenue = (item.venuelive) ? "<a href=\"/club-detail.aspx?id=" + item.venueid + "\" class=\"white b\">" + convertThe(item.venue) + "</a>" : convertThe(item.venue);

			sOutput += "<div class=\"pt8 pb8 mr8 hr-bot fl\" style=\"width:624px;\" onMouseOver=\"this.style.backgroundColor='#363636';\" onMouseOut=\"this.style.backgroundColor='';\">"
				+ "<a href=\"/event.aspx?" + item.eventid + "\"><img src=\"" + sListImage + "\" width=\"152\" height=\"76\" border=\"0\" class=\"fl mr8\" /></a>"
				+ "<div class=\"fl\" style=\"width:306px;\"><img src=\"/images/flags/" + item.ccode + ".gif\" width=\"22\" height=\"15\" border=\"0\" /> <span class=\"grey\">" + item.date + "</span><br />"
				+ "<a href=\"/event.aspx?" + item.eventid + "\" class=\"white b\">" + item.event + "</a> at " + sVenue
				+ "<br /><div class=\"f10 pt4\"><a href=\"/profile/" + item.user.toLowerCase() + "\">" + item.user + "</a> has invited you."
				+ "<br />Send " + item.user + " a <a href=\"/inbox-compose.aspx?sendto=" + item.user.toLowerCase() + "\">message</a>."
				+ "<div class=\"grey\"><a href=\"#sp-remove\" class=\"remove grey\">Remove</a> " + item.user + " from your friends.</div></div></div>"
				+ "<div class=\"addTo null\" style=\"position:absolute;bottom:8px;left:474px;\"><div class=\"grey b pb4\">&nbsp;</div>" + sConfig
				+ "<a href=\"#approve\" onmouseover=\"togTxt(this,'Yes, I will be attending')\" onmouseout=\"togTxt(this,'')\" class=\"op-but\"><img src=\"/images/interact/icon/fr-approve.gif\" width=\"73\" height=\"36\" alt=\"Approve\" border=\"0\" class=\"mr4\" /></a>"
				+ "<a href=\"#deny\" onmouseover=\"togTxt(this,'No thanks')\" onmouseout=\"togTxt(this,'')\" class=\"op-but\"><img src=\"/images/interact/icon/fr-deny.gif\" width=\"73\" height=\"36\" alt=\"Deny\" border=\"0\" /></a></div>"
				+ "</div>";
		});
		sOutput += "<br /><br /><div class=\"clear\"></div><div class=\"grey pt16\">"
			+ "<div class=\"pb4\">Worried about offending your friend? Don't be. The person that invited you will not be notified of your response.</div>"
			+ "<div class=\"pb4\">If you think someone is abusing the event invite system, you can remove them from <a href=\"/profile/" + data.user.toLowerCase() + "/friends\" runat=\"server\" class=\"grey\">your friends</a>.</div>"
			+ "<div class=\"pb4\">Or you can always stop friends from inviting you altogether by changing your <a href=/user-privacy.aspx class=\"grey\">privacy settings</a>.</div>"
			+ "</div><br /><br />";
		$("#loadingCon").remove();
		$("#content").html(sOutput);
		$("#tabInvites p span").text(" " + data.invites.length + " event invite" + sMulti);
		$("#removeAll").click(function() {
			if (confirm("Are you sure you want to remove all event invites?")) {
				removeAll("invites"); return false;
			}
		});
	} else {
		$("#tabInvites").remove();
		$("#tabUpdates").removeClass("t-off").addClass("t-on");
		myRA("Updates");
		return;
	}
	bindAddClick();
	$("#content").fadeTo("medium", 1);
};

function removeAll(sType) {
	$("#content").css("opacity", "0.4");
	$("#content").after($("<div id=\"loadingCon\" style=\"position:absolute;top:50px;left:0;width:669px;text-align:center;\"><div id=\"loading\" style=\"width:100px;height:100px;margin:0 auto;\"></div></div>"));
	if (!$.browser.msie)
		swfobject.embedSWF("/flash/loading/loading.swf", "loading", "100", "100", "9.0.0", "js/expressInstall.swf", { s: 40, c: "white" }, {}, { quality: "height", menu: "false", wmode: "transparent" });
	else
		$("#loadingCon").html($("<div style=\"width:100px;padding:10px;\" class=\"f16 b white dark-bg\">LOADING</div>"));

	$.getJSON("/my-remove-all.aspx?" + sType,
		function(data) {
			if (data.status) {
				if (sType == "requests") $("#tabRequests").remove();
				else $("#tabInvites").remove();
				$("#tabUpdates").removeClass("t-off").addClass("t-on");
				myRA("Updates");
			}
		}
	);
};

function replaceString() {
	var sString = arguments[0];
	for (var i = 1; i < arguments.length; i++) {
		sString = sString.replace(new RegExp("##" + i + "##", "g"), arguments[i]);
	}
	return sString;
};

function convertThe(s) {
	return s = (s.indexOf(", The") != -1) ? "The " + s.replace(", The", "") : s;
};


/*** Messaging ***/

function searchContacts(sValue, iSearchType) {
	switch (iSearchType) {
		case 1: // filter contacts
			var sOutput = "";
			var oReg = new RegExp(sValue, "i");
			var MAX_COUNT = 10;
			var iTotal = 0;
			bIsSearch = true;

			// search data for matches
			$.each(oData.contacts, function(i, item) {
				if (oReg.test(item.username)) {
					iTotal++;
					sOutput += "<div class=\"b\"style=\"padding:4px;\">" + item.username + "</div>";
				}
			});
			$("#contacts").append(sOutput);
			if (iTotal > MAX_COUNT) $("#contacts").height($("#contacts > div:first").outerHeight() * 10);
			if (iTotal > 0) $("#contacts").css("visibility", "visible");

			// set events to each item
			$("#contacts > div").mouseover(function() {
				($(this)).css({ "color": "rgb(255,162,0)", "background-color": "rgb(54,54,54)", "cursor": "pointer" })
			}).mouseout(function() {
				($(this)).css({ "color": "rgb(54,54,54)", "background-color": "rgb(255,162,0)" })
			}).click(function() {
				selectContact($(this).html());
			});
			break;

		case 2: // select single contact
			for (var i = 0; i < oData.contacts.length; i++)
				if (sValue == oData.contacts[i].username)
					return oData.contacts[i].image;
			return "d36.jpg";
			break;

		case 3: // check for existing contact
			var aSentTo = ($("input[name='sendto']").val()).split(",");
			for (var i = 0; i < aSentTo.length; i++)
				if (sValue == aSentTo[i]) return false;
			return true;
			break;
	};
};

function selectContact(sContact) {
	if (typeof sContact == "undefined") {
		removeContacts();
		return;
	}
	var sSendTo;
	var sImage = searchContacts(sContact, 2);
	sImage = (sImage.length > 0) ? sImage : "d36.jpg";
	var sOutput = "<div id=\"" + sContact.replace(/[^a-zA-Z0-9]/, "") + "\" class=\"fl mb4\" style=\"width:144px;/*line-height:32px;*/overfow:auto;\">"
		+ "<a href=\"#\" class=\"cat\" style=\"white-space:nowrap;\" title=\"Click to remove contact\">"
		+ "<img src=\"/images/user/av/" + sImage + "\" width=\"16px\" height=\"16px\" border=\"0\" class=\"fl\" />"
		+ "&nbsp;&nbsp;" + sContact + "</a></div>";

	if (searchContacts(sContact, 3)) {
		$("input[name='addrecipient']").val("").focus();
		$("#recipients").append(sOutput);
		$("#recipients > div:last-child").children("a").click(function() { deleteContact(sContact); $(this).attr("href", "javascript:void(0);"); });

		sSendTo = $("input[name='sendto']").val();
		if (sSendTo.length > 0) $("input[name='sendto']").val(sSendTo + "," + sContact);
		else $("input[name='sendto']").val(sContact);
	}
	
	removeContacts();
	eSelected = null;
	bIsSearch = false;
};

function removeContacts() {
	eSelected = null;
	iSelection = 0;
	$("#contacts").remove();
	$(document).unbind("keyup");
	$("form").unbind("submit");
};

function deleteContact(sContact) {
	var eSendTo = $("input[name='sendto']");
	var aSendTo = (eSendTo.val()).split(",");
	var sValue = "";

	if (aSendTo.length == 1) {
		$("#text").attr("style", "display:block");
		eSendTo.val("");
	} else {
		for (var i = 0; i < aSendTo.length; i++) {
			if (sContact != aSendTo[i]) {
				sValue += aSendTo[i];
				if (i != aSendTo.length - 1) sValue += ",";
			}
		}
		eSendTo.val(sValue);
	}
	$("#" + sContact.replace(/[^a-zA-Z0-9]/, "")).remove();
	$("input[name='addrecipient']").focus();
};

function keySelection(e) {
	var iTotalItems = $("#contacts > div").length;
	var oCss = { "color": "rgb(255,162,0)", "background-color": "rgb(54,54,54)" };

	switch (e.keyCode) {
		case 40: // down
			if (iSelection == 0 || iSelection < iTotalItems) {
				iSelection++;
				eSelected = $($("#contacts > div")[iSelection - 1]);
				$(eSelected).css(oCss);
			}
			if (iSelection == iTotalItems) $($("#contacts > div")[iTotalItems - 1]).css(oCss);
			break;

		case 38: // up
			if (iSelection > 1 || iSelection == iTotalItems) {
				iSelection--;
				eSelected = ($($("#contacts > div")[iSelection - 1]));
				$(eSelected).css(oCss);
			}
			if (iSelection == 1) $($("#contacts > div")[0]).css(oCss);
			break;

		case 13: // enter
			iSelection = 0;
			if (eSelected != null) selectContact($(eSelected).html());
			break;

		case 27: // escape
			break;
	};
};

function submitMessage() {
	document.topicform.submit();
};

function triggerLoad() {
	if (aLoad[iLoad].length) $("." + aLoad[iLoad]).children(":first-child").trigger("click");
	iLoad++;
	if (iLoad == aLoad.length - 1) clearTimeout(oLoadTimer);
	else oLoadTimer = setTimeout("triggerLoad()", 450);
};
