﻿var oData;
var sValue;
var oReg;
var oMatch;
var iSelection = 0;
var eSelected = null;
var bIsSearch = false;
var bLoading = false;

$(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) {
			var aLoad = ($("#load").val()).split(",");
			for (var i = 0; i < aLoad.length; i++)
				$("." + aLoad[i]).children(":first-child").trigger("click");
		}
	}

	// new events
	$(".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><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(); });
	});

	// friend requests on My RA
	if ($("#eFriends").length) {
		$("#showrequests").toggle(function() {
			$("#content").fadeOut("fast", function() {
				$("#eUpdates").css("display", "none");
				$("#eFriends").css("display", "block");
				$("#content").fadeIn("fast", function() {
					sIFR.replace(helv, { selector: "h1.titleblk", css: ".sIFR-root {background-color:#3F3F3F;color:#FFFFFF;font-weight:bold;}" });
				});
			});
		}, function() {
			$("#content").fadeOut("fast", function() {
				$("#eUpdates").css("display", "block");
				$("#eFriends").css("display", "none");
				$("#content").fadeIn("fast", function() {
					sIFR.replace(helv, { selector: "h1.titleblk", css: ".sIFR-root {background-color:#3F3F3F;color:#FFFFFF;font-weight:bold;}" });
				});
			});
		});
		if (location.search.length) {
			if (location.search == "?friends")
				$("#showrequests").trigger("click");
		}
		$("#backTo").bind("click", function() {
			$("#showrequests").trigger("click");
			return false;
		});
	};

	// 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").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;

		if (bLoading) return false;
		if ($(eAdd).attr("href").indexOf("#") > -1) sHref = ($(eAdd).attr("href")).replace("#", "");
		else return true;

		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) {
			bRemove = confirm("Are you sure you want to remove " + oConfig.u + "?");
			if (!bRemove) return false;
		}
		if (oConfig.t == 1 && oConfig.a == 5) {
			bRemove = confirm("Are you sure you want to block " + oConfig.u + "?");
			if (!bRemove) 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) {
					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");
								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(".deny").css("opacity", 0.5).attr("onmouseover", "").attr("onmouseout", "").unbind("click");
										break;
									case "3":
										sMsg = "Request has been denied";
										sImg = "/images/interact/icon/fr-denied.gif";
										$(eContainer).children(".approve").css("opacity", 0.5).attr("onmouseover", "").attr("onmouseout", "").unbind("click");
										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); //.attr("href", "javascript:void(0);");
										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);
							}
							$(eSrc).css("opacity", 1);
							break;
					};
				});
		}
	});
};

function togTxt(eLink, sMsg) {
	if (sMsg.length == 0) sMsg = "<br />";
	$($($(eLink).parent().get(0)).children().get(0)).html(sMsg);
}

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 + "\" class=\"mb4\" style=\"max-width:144px;line-height:32px;overfow:auto;\">"
		+ "<a href=\"#\" class=\"cat\" title=\"Click to remove contact\">"
		+ "<img src=\"/images/user/av/" + sImage + "\" width=\"32px\" height=\"32px\" border=\"0\" class=\"fl\" />"
		+ "&nbsp;&nbsp;" + sContact + "</a></div>";

	if (searchContacts(sContact, 3)) {
		$("#text").attr("style", "display:none");
		$("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).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();
};