/*
 *
 * Trillian Social Panel
 *
 * WebKit embed for Twitter, Facebook, LinkedIn, Foursquare
 *
 * Copyright (C) 2014 Cerulean Studios, LLC
 *
 * Andy Magoon
 * Kevin Kurtz
 *
 */

var a='Trillian Social Panels | Copyright (C) 2014 Cerulean Studios, LLC';

/*****************************************
  Trillian.object callbacks
 *****************************************/

function newsItemMenu (id, x, y)
{      
	/* Show the menu for that id at that location */
	trillian.newsItemMenu(id, x, y);
}
function newsGroupMenu (name, x, y)
{
  	/* Show the menu for that group name at that location */
	trillian.newsGroupMenu(name, x, y);
}

function newsAccountMenu (x, y)
{
	/* Show the menu for the current account at that location */
	trillian.newsAccountMenu(x, y);
}

function newsItemDestroy (id) 
{
	/* The webkit may limit data based on what is visible, so you need to destroy it now on your end 
	   pass it along to the callback you have stored  */
	trillian.newsItemDestroy(id);
}

function newsGroupViewed (name)
{
	/* pass it along to the callback you have stored */
	trillian.newsGroupViewed(name);
}

function newsItemDefaultAction (id) 
{
	/* pass it along to the callback you have stored */
	trillian.newsItemDefaultAction(id);
}

function newsPost (name, post) 
{
	/* pass it along to the callback you have stored */
	trillian.newsPost(name, post);
}

function newsGetImageFromFile()
{
	trillian.newsGetImageFromFile();
}

function newsGetImageFromClipboard()
{
	if (g_pastetarget)
	{
		for (l_itemEnum in g_myPanel.itemList)
		{
			if (g_myPanel.itemList[l_itemEnum].id == g_pastetarget)
			{
				if (g_myPanel.itemList[l_itemEnum].images_allowed)
				{
					trillian.newsGetImageFromClipboard();
				}
			}
		}
	}
	else
	{
		if (g_myPanel.DOMElementList[g_myPanel.groupSelectedID].images_allowed) 
		{
			trillian.newsGetImageFromClipboard();
		}
	}
}

function newsComment (id, post, name) 
{
	/* pass it along to the callback you have stored */
	trillian.newsComment(id, post, name);
}

function newsImageDefaultAction (image_url, parent_id) 
{
	/* pass it along to the callback you have stored */
	trillian.newsImageDefaultAction (image_url, parent_id)
}

function newsItemImageDestroy(image_url, parent_id)
{
    trillian.newsItemImageDestroy (image_url, parent_id)
}

var g_lastUnread = -1;
function newsAccountUnread (amount)
{
	if (amount != g_lastUnread)
	{
		trillian.newsAccountUnread(amount);
		g_lastUnread = amount;
	}
}

function newsPutImage (src)
{
	if (g_pastetarget)
	{
		var l_docEl = $("div.item[item=" + g_pastetarget + "]").find(".richtext:first").contents()[0].documentElement;
		$("div.item[item=" + g_pastetarget + "]").find(".richtext:first")[0].contentWindow.document.execCommand("insertimage", false, "data:image/png;base64," + src);
		$(l_docEl).find("img").css("max-height", "32").css("max-width", "64");
		var l_counter = "";
		var l_limit = g_myPanel.DOMElementList[$("div.item[item=" + g_pastetarget + "]").attr("id")].comment_limit;
		for (var l_shortened=""; l_shortened.length<g_myPanel.DOMElementList[g_myPanel.groupSelectedID].shortened_url_length; l_shortened+="X");
		var l_thislength = l_docEl.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length;
		var l_thislength = l_docEl.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length;
		if (l_limit > l_thislength)
		{
			l_counter = l_limit - l_thislength + " left";
		} else {
			l_counter = l_thislength - l_limit + " over";
		}
		$("div.item[item=" + g_pastetarget + "]").find(".richtext:first").show().end().find(".controls").show().find(".submit input").val(g_myPanel.DOMElementList[$("div.item[item=" + g_pastetarget + "]").attr("id")].comment_button.replace("%edit.count_relative%", l_counter));
	}
	else 
	{
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("insertimage", false, "data:image/png;base64," + src);
		var l_docEl = $("#post").find(".richtext:first").contents()[0].documentElement;
		$(l_docEl).find("img").css("max-height", "32").css("max-width", "64");
		var l_submit = $(".post > .controls > .submit");
		var l_submit_button = l_submit.find("input");
		var l_limit = $(l_submit).data("limit");
		var l_text = $(l_submit).data("text");
		for (var l_shortened=""; l_shortened.length<g_myPanel.DOMElementList[g_myPanel.groupSelectedID].shortened_url_length; l_shortened+="X");
		if (l_limit > l_docEl.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/ig, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length)
		{
			var l_counter = l_limit - l_docEl.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length + " left";
		} else {
			var l_counter = l_docEl.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length - l_limit + " over";
		}
		$(l_submit_button).val(l_text.replace("%edit.count_relative%", l_counter));
	}
}

/*****************************************
 n e w s P a n e l
 *****************************************/

function newsPanel()
{
	// constructor
}
newsPanel.prototype = 
{
	constructor: newsPanel,
	accountList: [],
	groupList: [],
	itemList: [],
	updateScheduled: null,
	updating: false,
	DOMElementList: [],
	DOMElementNextID: 1,
	groupSelectedID: -1,
	itemSelected: -1,
	contacts: new Object(),
	dirty: false,
    visible: true,
	setDirty: function(a_item)
	{
		a_item.dirty = true;
		this.dirty = true;
		return;
	},
	addAccount: function(a_newsAccount) 
	{
		a_newsAccount.DOMElementID = this.DOMElementNextID++;
		this.DOMElementList[a_newsAccount.DOMElementID] = a_newsAccount;
		this.accountList.push(a_newsAccount);
		this.setDirty(a_newsAccount);
		this.scheduleUpdate();
		return;
	},
	addGroup: function (a_newsGroup)
	{
		var l_enum;
		for (l_enum=0; l_enum<this.groupList.length; l_enum++)
			if (this.groupList[l_enum].name == a_newsGroup.name && this.groupList[l_enum].header == a_newsGroup.header)
				return;
		a_newsGroup.DOMElementID = this.DOMElementNextID++;
		this.DOMElementList[a_newsGroup.DOMElementID] = a_newsGroup;
		this.groupList.push(a_newsGroup);
		this.setDirty(a_newsGroup);
		this.scheduleUpdate();
		return;
	},
	addItem: function (a_newsItem)
	{
		if (a_newsItem.item) 
			if (this.contacts[a_newsItem.display_name]) 
				this.contacts[a_newsItem.display_name]++;
			else
				this.contacts[a_newsItem.display_name]=1;
		a_newsItem.DOMElementID = this.DOMElementNextID++;
		this.DOMElementList[a_newsItem.DOMElementID] = a_newsItem;
		this.itemList.push(a_newsItem);
		this.setDirty(a_newsItem);
		for (l_group in a_newsItem.groups)
		{
			for (l_enum=0; l_enum<this.groupList.length; l_enum++)
			{
				if (this.groupList[l_enum].name == a_newsItem.groups[l_group])
				{
					if (a_newsItem.longitude) 
					{
						this.groupList[l_enum].hasmap = true;
					}
					if (this.groupList[l_enum].unread < 100)
					{
					       if (a_newsItem.unread)
					       {
						       this.groupList[l_enum].unread++;
					       }
					}
				}
			}
		}
		this.scheduleUpdate();
		return;
	},
	addImage: function (a_id, a_url, a_imageID)
	{
		//
		for (l_itemEnum in this.itemList)
		{
			if (this.itemList[l_itemEnum].id == a_id)
			{
                this.itemList[l_itemEnum].image_url = a_url;
                this.itemList[l_itemEnum].image_id = a_imageID;
				this.setDirty(this.itemList[l_itemEnum]);
				this.scheduleUpdate();
				return true;
			}
		}
	},
	removeGroup: function (a_header, a_name)
	{
		var l_enum;
		for (l_enum=0; l_enum<this.groupList.length; l_enum++)
		{
			if (this.groupList[l_enum].name == a_name && this.groupList[l_enum].header == a_header)
			{
				var id = this.groupList[l_enum].DOMElementID;
				$('#'+id).remove();
				if ($('li.header[header='+this.groupList[l_enum].header+']').find("li.group").length==0) $('li.header[header='+this.groupList[l_enum].header+']').remove();
				this.groupList.splice(l_enum,1)
				delete this.DOMElementList[id];
				break;
			}
		}
		this.scheduleUpdate();
		return;
	},
	tock: function ()
	{
		/* Update every timestamp on the screen */
		var l_now = new Date().getTime();
		for (l_itemEnum in this.itemList)
		{
			if (this.DOMElementList[this.groupSelectedID])
			{
				if (this.itemList[l_itemEnum].groups.indexOf(this.DOMElementList[this.groupSelectedID].name) != -1)
				{
					var l_element = $("#"+this.itemList[l_itemEnum].DOMElementID+"")
					if (l_element)
					{
						var l_first = l_element.find(".time:first");
						if (l_first.length)
						{
							if (this.itemList[l_itemEnum].timestamp > 31337)
							{
								l_first.html(relativeTime(this.itemList[l_itemEnum].timestamp, l_now));
							} else {
								l_first.html("");
							}
						}
					}
				}
			}
		}
		if (this.dirty) this.scheduleUpdate();
		resize();
	},
	update: function (a_force)
	{
		if (this.updating && !a_force)
			return this.scheduleUpdate();
		if (g_editing && !a_force)
		{
			//trillian.log("delaying update - user is typing a post");
			return this.scheduleUpdate(5000);
		}
		if (g_replying && !a_force)
		{
			//trillian.log("delaying update - user is typing a reply");
			return this.scheduleUpdate(5000);
		}
		g_replying = false;
		this.updating = true;
		if (this.updateScheduled) 
			this.updateScheduled = clearTimeout(this.updateScheduled);
		this.itemList.sort(function(a,b)
		{
			if (a.timestamp < b.timestamp) return 1;
			if (a.timestamp > b.timestamp) return -1;
			if (a.id < b.id) return 1;
			if (a.id > b.id) return 1;
			return 0;
		})			
		//> Are any items dirty?
		$("#items > .empty").remove();
		if (this.dirty)
		{
			//> Yes.  First remove any empty_string
			//> Process each dirty item:
			this.dirty = false;
			var l_targetElement = $('#accounts');
			for (l_dirtyEnum in this.accountList)
			{
				if (this.accountList[l_dirtyEnum].dirty)
				{
					this.accountList[l_dirtyEnum].dirty = false;
					l_targetElement.append(this.accountList[l_dirtyEnum].getHTML());
				}
			}
			l_targetElement = null;
			for (l_dirtyEnum in this.groupList)
			{
				if (this.groupList[l_dirtyEnum].dirty)
				{
					this.groupList[l_dirtyEnum].dirty = false;
					//> remove any existing item this may be replacing
					if ($("#groups > .header > li.group[group=" + escape(this.groupList[l_dirtyEnum].name) + "]").length)
					{
						$("#groups > .header > li.group[group=" + escape(this.groupList[l_dirtyEnum].name) + "]").remove();
					}
					if ($('li[header='+this.groupList[l_dirtyEnum].header+']').length < 1)
					{
						var l_header = $('<li></li>').addClass('header').attr('header',this.groupList[l_dirtyEnum].header)
						var l_priority = this.groupList[l_dirtyEnum].priority;
						if (l_priority)
						{
							l_header.attr("priority", l_priority);
							var l_insert_after=-1;
							$(".header[priority]").each(function()
							{
								if (l_priority > $(this).attr("priority"))
									l_insert_after = $(this).attr("priority");
							});
							if (l_insert_after == -1)
							{
								l_header.prependTo('#groups');
							} else {
								l_header.insertAfter($(".header[priority=" + l_insert_after + "]"));
							}
									
						} else {
							l_header.appendTo('#groups');
						}
						$("<div></div>").addClass("label").html(this.groupList[l_dirtyEnum].header).appendTo(l_header);
						$("<div></div>").addClass("showhide").append($("<div></div>").addClass("label").text("Hide").hide()).appendTo(l_header);
						
					}
					l_targetElement = $('li[header='+this.groupList[l_dirtyEnum].header+']');
					if (this.groupList[l_dirtyEnum].dfault && this.groupSelectedID==-1) this.groupSelectedID=this.groupList[l_dirtyEnum].DOMElementID;
					l_targetElement.append(this.groupList[l_dirtyEnum].getHTML());
				}
			}
			for (l_dirtyEnum in this.itemList)
			{
				// Process parents first
				if (this.itemList[l_dirtyEnum].parent_id) continue;
				if (this.itemList[l_dirtyEnum].dirty)
				{
					this.itemList[l_dirtyEnum].dirty = false;
					//> Is this dirty item in selected group?
					if (this.groupSelectedID != -1)
					{
						if (this.itemList[l_dirtyEnum].groups.indexOf(this.DOMElementList[this.groupSelectedID].name) != -1)
						{
							//> remove any existing item this may be replacing
							var l_element = $("#items").find("#"+this.itemList[l_dirtyEnum].DOMElementID);
							if (l_element.length)
							{
								$("div.item[item=" + this.itemList[l_dirtyEnum].id + "]").replaceWith(this.itemList[l_dirtyEnum].getItemHTML());
							} else {
								$("#items").append(this.itemList[l_dirtyEnum].getItemHTML());
							}
							l_element = null;
						}
					}
				}
			}	
			for (l_dirtyEnum in this.itemList)
			{
				// Process only children
				if (!this.itemList[l_dirtyEnum].parent_id) continue;
				if (this.itemList[l_dirtyEnum].dirty)
				{
					this.itemList[l_dirtyEnum].dirty = false;
					//> Is this dirty item in selected group?
					if (this.groupSelectedID != -1)
					{
						if (this.itemList[l_dirtyEnum].groups.indexOf(this.DOMElementList[this.groupSelectedID].name) != -1)
						{
							//> remove any existing item this may be replacing
							var l_element = $("#items").find("#"+this.itemList[l_dirtyEnum].DOMElementID);
							if (l_element.length)
							{
								$("div.subitem[item=" + this.itemList[l_dirtyEnum].id + "]").replaceWith(this.itemList[l_dirtyEnum].getCommentHTML());
							} else {
								var l_parentitem = $("div.item[item=" + this.itemList[l_dirtyEnum].parent_id + "]");
								if (l_parentitem.length)
								{

									var l_subitems = l_parentitem.find("div.subitems:first");
									if (!l_subitems.length)
									{
										l_subitems = this.DOMElementList[l_parentitem.attr("id")].getSubitemsHTML();
										l_subitems.appendTo(l_parentitem);
									}
									l_targetElement = l_subitems.show().find(".comments");
									if (l_targetElement.children().length)
									{
										var l_newSeparator = $("<div></div>").addClass("separator");
										l_newSeparator.appendTo(l_targetElement);
										l_newSeparator = null;
									}
									if (l_subitems.find(".reply").length && !(l_subitems.find(".reply").find(".separator").length))
									{
										var l_newReplySeparator = $("<div></div>").addClass("separator").css("margin-left", "-4px");
										l_newReplySeparator.prependTo(l_subitems.find(".reply"));
										l_newReplySeparator = null;
									}
									var l_newItem = this.itemList[l_dirtyEnum].getCommentHTML();
									l_newItem.appendTo(l_targetElement);
									var l_reply = l_subitems.find(".reply");
									if (l_reply.length && g_myPanel.accountList[0].medium == "TWITTER")
									{
										l_reply.richReply();
									}
									l_reply = null;
									l_newItem = null;
									l_subitems = null;
									l_targetElement = null;

								}
							}
						}
					}
				}
			}
			l_targetElement = null;
		}
		//> Are we changing which group is selected?  compare groupSelectedID to $("div[group].selected").attr("id");
		if (this.groupSelectedID != $("#groups > .header > li[group].selected").attr("id") && this.DOMElementList[this.groupSelectedID])
		{
			$("#groups > .header > li[group].selected").removeClass("selected");
			$("#"+this.DOMElementList[this.groupSelectedID].DOMElementID).addClass("selected");
			//> Erase the item collection:
			$("#items").children().remove();
			setTimeout(function(){g_myPanel.drawGroup()}, 10);
			return this.updating=false;

		}
		$("#groups > .header > li.group").each(function()
		{
			var l_unread = $(this).find(".unread");
			var l_group = g_myPanel.DOMElementList[$(this).attr("id")];
			if ($(this).hasClass("selected") && g_myPanel.visible)
				l_group.unread = 0;
			var l_unread_count = l_group.unread;
			l_unread.find(".count").text(l_unread_count);
			if (l_unread_count > 0) 
			{
				l_unread.show();
				$(this).find(".label").addClass("limited");
			} else {
				l_unread.hide();
				$(this).find(".label").removeClass("limited");
			}
			l_unread = null;
			l_group = null;
			l_unread_count = null;
		});
		$("div.reply").find(".richtext").each(function(){
			if ($(this)[0].contentWindow.document.designMode == "on")
			{
				$(this).addClass("restore_design_mode");
				$(this).data("restore", $(this).contents()[0].documentElement.innerHTML)
				$(this)[0].contentWindow.document.designMode = "off";
			}
		});
		$("div.item[item]").tsort({attr:"timestamp",order:"desc"});
		$("div.item[item]").each(function()
		{
			$(this).find("div.subitem[item]").sortElements(function(a,b){
				return $(a).attr("timestamp") < $(b).attr("timestamp") ? -1 : 1;
			});
		});		
		$(".restore_design_mode").each(function(){
			$(this).parent().parent().parent().richReply();
			if ($(this).data("restore"))
			{
			//	$(this).contents()[0].documentElement.innerHTML = $(this).data("restore");
				$(this).data("restore",null);
			}
		});
		for (; $("div.item[item]").length > 100; )
			{
                var l_item = $("div.item[item]:last");
                  
                $(l_item).find(".subitem[item]").each(function()
                {
                     newsItemRemove($(this).attr("item"))
                });
                                                                                                                                                  
                newsItemRemove(l_item.attr("item"))
                  
			}
		//> display the empty tag if there is nothing here
		if (!$("#items").children().length)
		{
			if (this.DOMElementList[this.groupSelectedID] && !this.DOMElementList[this.groupSelectedID].stats)
			{
				$("<div></div>").addClass("empty").append($("<p></p>").html(this.DOMElementList[this.groupSelectedID].empty_string)).appendTo($("#items"));
			}
			
		}
		this.updating = false;
		resize();
		unread();
	},
	drawGroup: function()
	{
			this.dirty = false;
			if (this.DOMElementList[this.groupSelectedID].hasmap)
			{
				var l_iframe = $("<iframe></iframe").attr("id", "map").attr("name", "map").attr("src", "social-location.html").load(function(){window.frames['map'].initialize()});
				$("#view").append(l_iframe);
				$("#view").show();
			} else {
				$("#view").html("");
				$("#view").hide();
			}

			//> Process parents
			var l_targetElement = $("#items");
			for (l_itemEnum in this.itemList)
			{

				if (this.itemList[l_itemEnum].groups.indexOf(this.DOMElementList[this.groupSelectedID].name) != -1)
				{
					if (this.itemList[l_itemEnum].parent_id < 1)
					{
						l_targetElement.append(this.itemList[l_itemEnum].getItemHTML());
					} 
				}
			}

			//> Process children
			for (l_itemEnum in this.itemList)
			{
				var l_item = this.itemList[l_itemEnum];
				if (l_item.groups.indexOf(this.DOMElementList[this.groupSelectedID].name) != -1)
				{
					if (l_item.parent_id > 0)
					{
						var l_parentitem = $("div.item[item=" + l_item.parent_id + "]");
						if (l_parentitem.length)
						{
							
							var l_subitems =l_parentitem.find(".subitems:first")
							if (!l_subitems.length)
							{
								l_subitems = g_myPanel.DOMElementList[l_parentitem.attr("id")].getSubitemsHTML();
								l_subitems.appendTo(l_parentitem);
							}
							l_targetElement = l_subitems.show().find(".comments");
							if (l_targetElement.children().length)
							{
								var l_newSeparator = $("<div></div>").addClass("separator");
								l_newSeparator.appendTo(l_targetElement);
								l_newSeparator = null;
							}
							if (l_subitems.find(".reply").length && !(l_subitems.find(".reply").find(".separator").length))
							{
								var l_newReplySeparator = $("<div></div>").addClass("separator").css("margin-left", "-4px");
								l_newReplySeparator.prependTo(l_subitems.find(".reply"));
								l_newReplySeparator = null;

							}
							var l_newItem = l_item.getCommentHTML();
							l_newItem.appendTo(l_targetElement);
							var l_reply = l_subitems.find(".reply");
							if (l_reply.length && g_myPanel.accountList[0].medium == "TWITTER")
							{
								l_reply.richReply();

							}
							l_newItem = null;
							l_reply = null;
							l_subitems = null;
							l_targetElement = null;
						}
						l_parentitem = null;
					}
				}
				l_item = null;
			}
		//> Draw the post area
		$("#post").html("");
		$("#post").append(this.DOMElementList[this.groupSelectedID].getPostHTML());
		var l_richtext = $("#post").find(".richtext:first");
		if (l_richtext.length)
		{	
			l_richtext[0].contentWindow.document.designMode = "on";
			$(l_richtext.contents()[0].documentElement).attr("spellcheck", "false");
			$(l_richtext.contents()[0].documentElement).html($("#post").find(".richtext:first").data("helper"));
			$(l_richtext.contents()[0].documentElement).css("font-size", '14px').css("font-family", "Helvetica").css("color", '#acacac')
			if ($.browser.version > "534.48.") 
		    		$(l_richtext.contents()[0].documentElement).css("margin-top", "-7px");
			l_richtext[0].contentWindow.document.onpaste = function(e) 
			{
				e.preventDefault();
				if (e.clipboardData.types)
				{
					if (e.clipboardData.types.length)
					{
						if (e.clipboardData.types[1] == "text/plain" || e.clipboardData.types[0] == "text/rtf")
						{
							var paste = e.clipboardData.getData("text/plain");
						}
					}
				}
				if (paste) 
				{
					paste = decodeURIComponent(encodeURIComponent(paste.stripHtml()).replace(/%0D%0A/g,"").replace(/%0D/g,""));
					$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, paste);
					$($("#post").find(".richtext:first").contents()[0].documentElement).keyup();
				} else {
					newsGetImageFromClipboard();
				}
				return false;
			}
	
			$(l_richtext.contents()[0].documentElement).keydown(function(event)
			{
				if (event.which==9 || event.which==39 || event.which==13 || event.which==32)
				{
					var l_selected = $(".post > .autocomplete").find(".hover");
					if (l_selected.length)
					{
						l_selected.click();
						return false;
					}
				}
				if (event.which==9)
				{
					if ($(".post > .autocomplete").length);
					{
						$(".post > .autocomplete").find(".entry:first").click();
						return false;
					}
				}
				else if (event.which==40)
				{
					var l_selected = $(".post > .autocomplete").find(".hover");
					if (l_selected.length) 
					{
						if (l_selected.next().length)
						{
							for (var i=0; i<1 || ((event.metaKey || event.ctrlKey) && i<5); i++)
							{
								if (i>1) var l_selected = $(".post > .autocomplete").find(".hover");
								l_selected.next().addClass("hover").siblings().removeClass("hover");
								if ($(".post > .autocomplete").height() - $(".hover:first").position().top < l_selected.height()) $(".post > .autocomplete").scrollTop($(".hover:first").height()+8 + $(".post > .autocomplete").scrollTop());
							}
						}
						return false;
					} 
					else if ($(".post > .autocomplete").length) 
					{
						$(".post > .autocomplete").data("entered", "true").find(".entry:first").addClass("hover");
						return false;
					}
				}	
				else if (event.which==38)
				{
					var l_selected = $(".post > .autocomplete").find(".hover");
					if (l_selected.length) 
					{
						if (l_selected.prev().length)
						{
							for (var i=0; i<1 || ((event.metaKey || event.ctrlKey) && i<5); i++)
							{
								if (i>1) var l_selected = $(".post > .autocomplete").find(".hover");
								l_selected.prev().addClass("hover").siblings().removeClass("hover");
								if ($(".hover:first").position().top < 0) $(".post > .autocomplete").scrollTop($(".post > .autocomplete").scrollTop() - $(".hover:first").height() - 8);
							}
						} else {
							l_selected.removeClass("hover");
						}	
						return false;
					}
					if ($(".post > .autocomplete").length)
					{
						if ($(".post > .autocomplete").data("entered")) return false;
						else $(".post > .autocomplete").remove();
					}
				} 
				else if (event.which==27)
				{
					if ($(".post > .autocomplete").length)
						$(".post > .autocomplete").remove();
					else
						$(".post > .controls > .cancel > input").click();
					return false;
				}
				if (event.which==9 || event.which == 13) return false;
			});
			$(l_richtext.contents()[0].documentElement).keyup( function(event)
			{
				if (event.which==17 || event.which==91 || event.which==27) return true;
				var l_submit = $(".post > .controls > .submit");
				var l_submit_button = l_submit.find("input");
				var l_limit = $(l_submit).data("limit");
				var l_text = $(l_submit).data("text");
				for (var l_shortened=""; l_shortened.length<g_myPanel.DOMElementList[g_myPanel.groupSelectedID].shortened_url_length; l_shortened+="X");
				if (l_limit > this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/ig, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length)
				{
					var l_counter = l_limit - this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length + " left";
				} else {
					var l_counter = this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length - l_limit + " over";
				}
				$(l_submit_button).val(l_text.replace("%edit.count_relative%", l_counter));
				if (g_myPanel.accountList[0].medium == "TWITTER")
				{
					if (l_matches = this.innerHTML.stripHeadBody().stripHtml().match(/(^|[^a-zA-Z0-9])(@[a-zA-Z_]+)$/)) 
					{
						if (event.which==9 || event.which==13 || event.which==38 || event.which==39 || event.which==40) return false;
						$(".post > .autocomplete").remove();
						var l_post_autocomplete = $("<div></div>").addClass("autocomplete").width($(".post").width()).data("typed", l_matches[2]).hide();
						l_post_autocomplete.appendTo($(".post"));
						for (l_contact in g_myPanel.contacts)
						{
							if (l_contact.toLowerCase().indexOf(l_matches[2].toLowerCase().substr(1)) == 0)
				       			{
								$("<div></div>").addClass("entry").html(l_contact).appendTo(l_post_autocomplete);
							}
						}
						if (l_post_autocomplete.children().length)
						{
							l_post_autocomplete.children().sortElements(function(a,b) 
							{
								return $(a).text().toLowerCase() < $(b).text().toLowerCase() ? -1 : 1;
							}).end().show();	
						}	
					} else {
						$(".post > .autocomplete").remove();
					}
				}
			});
			$(l_richtext.contents()[0].documentElement).click( function()
			{
				if (!g_editing)	
					$(l_richtext.contents()[0].documentElement).focus();
			});
			$(l_richtext.contents()[0].documentElement).focus( function()
			{ 
				g_editing = true;
				g_pastetarget = 0;
				$("#post").find(".richtext:first")[0].contentWindow.document.designMode = "on";
				$($("#post").find(".richtext:first").contents()[0].documentElement).css("font-size", '14px').css("font-family", "Helvetica").css("color", '#000000').css("overflow-x"," none").css("word-break", "break-word").css("padding-right", "5px");
				$("#post").find(".richtext:first").addClass("focus expanded");
				$("#post").find(".richtext:first").parent().addClass("expanded");
				$(".post > .controls").show();
				if (this.innerHTML.indexOf($("#post").find(".richtext:first").data("helper")) != -1) 
				{
					$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("selectall");
					$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("delete");
				}
				resize();
				return false;
			});
			l_richtext[0].contentWindow.addEventListener("blur",function()
			{
				g_editing = false;
				$(this).removeClass("focus");
				setTimeout(function(){$(".post > .autocomplete").remove();}, 500);
			});
		}
		this.update();
	},		
	scheduleUpdate: function(a_timer)
	{
		clearTimeout(this.updateScheduled)
		this.updateScheduled = setTimeout(function(){g_myPanel.update();}, (a_timer?a_timer:250));
	}
}

/*****************************************
 n e w s A c c o u n t
 *****************************************/

function newsAccount()
{
	// constructor
}
newsAccount.prototype = 
{
	constructor: newsAccount,
	account: "",
	display_name: "",
	medium: "",
	stats: "",
	avatar_url: "",
	DOMElementID: -1,
	dirty: false,
	getHTML: function()
	{
		/* Assemble the identity panel components into l_identity */
		var l_avatar = $("<img></img>").addClass("account-avatar").attr("src",this.avatar_url);
		var l_name = $("<div></div>").addClass("account-display-name").html(this.display_name);
		var l_status = $("<div></div>").addClass("account-status").html(this.stats);
		var l_identity = $("<div></div>").addClass("account-identity-panel").append(l_avatar).append(l_name).append(l_status);

		return $('<div></div>').addClass("account").attr("account",this.account).attr("id",this.DOMElementID).append(l_identity);
	}
}

/*****************************************
 n e w s G r o u p
 *****************************************/

function newsGroup()
{
	// constructor
}
newsGroup.prototype =
{
	constructor: newsGroup,
	header: "",
	name: "",
	display_name: "",
	dfault: "",
	empty_string: "",
	post_on: 0,
	unread: 0,
	post_button: "Submit (%edit.count_relative%)",
	post_helper: "Share something ...",
	post_limit: 999,
	view: null,
	hasmap: false,
	stats: null,
	DOMElementID: -1,
	shortened_url_length: 23,
	images_allowed: null,
	dirty: false,
	icon: null,
	priority: null,
	getHTML: function()
	{
		var l_group = $('<li></li>').addClass('group hasmenu');
		var l_group_icon = $("<div></div>").addClass('icon');
		var l_group_label = $("<div></div>").addClass('label');
		var l_unread = $('<div></div>').addClass('unread');
		var l_unread_count = $('<div></div>').addClass('count');

		l_group.attr("group",this.name);
		l_group.attr("id",this.DOMElementID);
		if (this.icon)
			l_group_icon.addClass(this.icon);
		else
			l_group_icon.addClass("feed");
		l_group_icon.appendTo(l_group);
		l_group_label.html(this.display_name);
		l_group_label.attr("text", this.display_name);
		l_group_label.appendTo(l_group);
		l_unread.hide();
		l_unread_count.text("0");
		l_unread_count.appendTo(l_unread);
		l_unread.appendTo(l_group);
		return l_group;
	},
	getPostHTML: function()
	{
		if (this.post_on)
		{
			var l_post = $("<div></div>").addClass("post");
			var l_post_entry = $("<div></div>").addClass("entry");
			var l_post_entry_icon = $("<div></div>").addClass("icon");
			var l_post_entry_edit = $("<div></div>").addClass("edit");
			var l_post_entry_edit_textarea = $("<iframe></iframe>").addClass("richtext").attr("src", "forced404.html");
			var l_post_controls = $("<div></div>").addClass("controls");
			var l_post_controls_picture = $("<div></div>").addClass("picture");
			var l_post_controls_picture_button = $("<input></input>");
			var l_post_controls_cancel = $("<div></div>").addClass("cancel");
			var l_post_controls_cancel_button = $("<input></input>");
			var l_post_controls_submit = $("<div></div>").addClass("submit");
			var l_post_controls_submit_button = $("<input></input>");
	
			/* Assign attributes to subitem */
			l_post.data("id", this.DOMElementID);
			l_post_entry_icon.text("+");
			l_post_entry_edit_textarea.data("id", this.DOMElementID);
			l_post_entry_edit_textarea.attr("id", "iframe_post");
			l_post_entry_edit_textarea.attr("designMode", true);
			l_post_entry_edit_textarea.data("helper",this.post_helper);
			l_post_controls_cancel_button.data("id", this.DOMElementID);
			l_post_controls_picture_button.data("id", this.DOMElementID);
			l_post_controls_submit_button.data("id", this.DOMElementID);
			l_post_controls_submit.data("limit", this.post_limit);
			l_post_controls_submit.data("text", this.post_button);
			$(l_post, l_post_entry_edit_textarea, l_post_controls_cancel_button, l_post_controls_submit_button).data("item", this.id);
			l_post_controls.hide();
			l_post_controls_picture_button.attr("type", "button");
			l_post_controls_picture_button.val("Insert Picture...");
			l_post_controls_cancel_button.attr("type", "button");
			l_post_controls_cancel_button.val("Cancel");
			l_post_controls_submit_button.attr("type", "button");
			l_post_controls_submit_button.val(this.post_button.replace("%edit.count_relative%", this.post_limit + " left"));
			/* Assemble item by combining it with its pieces */
			l_post_entry_icon.appendTo(l_post_entry);
			l_post_entry_edit_textarea.appendTo(l_post_entry_edit);
			l_post_entry_edit.appendTo(l_post_entry);
			l_post_entry.appendTo(l_post);
			l_post_controls_submit_button.appendTo(l_post_controls_submit);
			l_post_controls_submit.appendTo(l_post_controls);
			l_post_controls_cancel_button.appendTo(l_post_controls_cancel);
			l_post_controls_cancel.appendTo(l_post_controls);	
			l_post_controls_picture_button.appendTo(l_post_controls_picture);
			if (this.images_allowed)
				l_post_controls_picture.appendTo(l_post_controls);	
			l_post_controls.appendTo(l_post);
			return l_post;
		} else {
			return $('<div></div>');
		}
	}
}

/*****************************************
 n e w s I t e m
 *****************************************/

function newsItem()
{
	// constructor
}
newsItem.prototype = 
{
	constructor: newsItem,
	id: -1,
	parent_id: 0,
	type: 0,
	name: null,
	display_name: null,
	item: null,
	groups: [],
	unread: null,
	hide: false,
	avatar_url: null,
	timestamp: 0,
	comments_on: 0,
	comment_button: "Reply (%edit.count_relative%)",
	comment_helper: "", 
	comment_limit: 999,
	link_url: null,
	link_title: null,
	link_site: null,
	link_description: null,
	latitude: null,
	longitude: null,
	person: null,
	image_url: null,
    image_id: 0,
	DOMElementID: -1,
	initial_text: null,
	images_allowed: null,
	getItemHTML: function() 
	{
		/* Create item and its pieces */
		var l_item = $("<div></div>").addClass("item hasmenu");
		var l_item_container = $("<div></div>").addClass("container");
		var l_item_avatar = $("<div></div>").addClass("avatar");
		var l_item_avatar_img = $("<img></img>");
		var l_item_message = $("<div></div>").addClass("message");
		var l_item_name = $("<div></div>").addClass("name");
		var l_item_time = $("<div></div>").addClass("time");
		var l_item_text = $("<div></div>").addClass("text");
	
		/* Assign attributes to item and its pieces */
		l_item.attr("id",this.DOMElementID);
		l_item.attr("item",this.id);
		l_item.attr("timestamp",this.timestamp);
		l_item.attr("parent_id", this.parent_id);
		l_item_avatar_img.attr("src", this.avatar_url);
		l_item_name.html(this.display_name);
		if (this.timestamp > 31337)
		{
			l_item_time.html(relativeTime(this.timestamp, new Date().getTime()));
		} else {
			l_item_time.html("");
		}
		if (this.item)
		{

			l_item_text.html((this.display_name.length>20?"<br/>":"")+this.item);
		} else {
			l_item_text.html((this.display_name.length>20?"<br/>":"")+"&nbsp;");
		}
		/* Assemble item by combining it with its pieces */
		l_item_avatar_img.appendTo(l_item_avatar);
		l_item_avatar.appendTo(l_item_container);
		l_item_time.appendTo(l_item_message);
		l_item_name.appendTo(l_item_message);
		l_item_text.appendTo(l_item_message);
		l_item_message.appendTo(l_item_container);
		l_item_container.appendTo(l_item);
		if (this.link_url)
		{
			this.getLinkHTML().appendTo(l_item_message).show();
		} else {
			if (this.image_url)
			{
				this.getImage().appendTo(l_item_message).show();
			}
		}
		return l_item;
	},
	getLinkHTML: function()
	{
		/* Append link in item message */
		var l_link = $("<div></div>").addClass("link");
		var l_content = $("<div></div>").addClass("content");
		var l_content_a = $("<a></a>").addClass("title");
		var l_content_site = $("<div></div>").addClass("site");
		var l_content_description = $("<div></div>").addClass("description");

		/* Set attributes */
		l_content_a.attr("href", this.link_url);
		l_content_a.attr("target", "_new");
		if (this.link_title) 
			l_content_a.html(this.link_title);
		else 
		{
			l_content_a.html(this.link_site);
			l_content_site.hide();
		}
		if (this.link_site.indexOf("apps.facebook.com") != -1)
			l_content_site.hide();
		l_content_site.html(this.link_site);
		if (this.link_description)
			l_content_description.html(this.link_description);
		else
			l_content_description.hide();

		/* Assemble */
		if (this.image_url) 
			this.getLinkImage().appendTo(l_link);
		l_content_a.appendTo(l_content);
		l_content_site.appendTo(l_content);
		l_content_description.appendTo(l_content);
		l_content.appendTo(l_link);
		return l_link;
	},
	getLinkImage: function()
	{      
		/* Prepend linkimage to an item link */
		var l_image = $("<div></div>").addClass("image");
		var l_image_border = $("<div></div>").addClass("border");
		var l_image_fill = $("<div></div>").addClass("fill");
		var l_image_img = $("<img></img>");

		/* Attributes */
		l_image_img.attr("src", this.image_url);

		/* Assemble */
		l_image_img.appendTo(l_image_fill);
		l_image_fill.appendTo(l_image_border);
		l_image_border.appendTo(l_image);
		l_image_img.load(function()
		{
			var l_h = $(this).height();
			$(this).parent().height(l_h);
			$(this).parent().width($(this).width());
			resize();
		});
		return l_image;
	},
	getImage: function()
	{    
		/* Append image in item messages */
		var l_image = $("<div></div>").addClass("image");
		var l_image_border = $("<div></div>").addClass("border");
		var l_image_fill = $("<div></div>").addClass("fill");
		var l_image_img = $("<img></img>");

		/* Attributes */
		l_image_img.attr("src", this.image_url);

		/* Assemble */
		l_image_img.appendTo(l_image_fill);
		l_image_fill.appendTo(l_image_border);
		l_image_border.appendTo(l_image);
		l_image_img.load(function()
		{
			$(this).parent().parent().parent().css("opacity", 1);
			var l_h = $(this).height();
			$(this).parent().height(l_h);
			$(this).parent().width($(this).width());
			resize();
		});
		return l_image;
	},
	getSubitemsHTML: function()
	{
		var l_subitems = $("<div></div>").addClass("subitems");
		var l_subitems_envelope = $("<div></div>").addClass("envelope");
		var l_subitems_envelope_contents = $("<div></div>").addClass("contents");
		var l_subitems_arrow = $("<div></div>").addClass("arrow");
		var l_subitems_arrow_border = $("<div></div>").addClass("border");
		var l_subitems_arrow_fill = $("<div></div>").addClass("fill");
		var l_comments = $("<div></div>").addClass("comments");
		l_subitems.hide();
		l_subitems_arrow.appendTo(l_subitems);
		l_subitems_arrow_border.appendTo(l_subitems_arrow);
		l_subitems_arrow_fill.appendTo(l_subitems_arrow_border);
		l_comments.appendTo(l_subitems_envelope_contents);
		if (this.comments_on) 
		{
			//l_comments.append($("<div></div>").addClass("separator"));
			this.getReplyHTML().appendTo(l_subitems_envelope_contents);
			l_subitems.show();
		}
		l_subitems_envelope_contents.appendTo(l_subitems_envelope);
		l_subitems_envelope.appendTo(l_subitems);
		return l_subitems;
	},
	getCommentHTML: function() 
	{
		/* Create this subitem and its pieces */
		var l_subitem = $("<div></div>").addClass("subitem hasmenu");
		var l_comment = $("<div></div>").addClass("comment");
		var l_comment_content = $("<div></div>").addClass("content");
		var l_comment_avatar = $("<div></div>").addClass("avatar");
		var l_comment_avatar_img = $("<img></img>");
		var l_comment_name = $("<div></div>").addClass("name");
		var l_comment_name_text = $("<div></div>").addClass("text");
		var l_comment_time = $("<div></div>").addClass("time");
		var l_comment_text = $("<div></div>").addClass("text");

		/* Assign attributes to subitem */
		l_subitem.attr("id",this.DOMElementID);
		l_subitem.attr("item",this.id);
		l_subitem.attr("parent_id", this.parent_id);
		l_subitem.attr("timestamp",this.timestamp);
		l_comment_avatar_img.attr("src", this.avatar_url);
		if (!this.avatar_url) l_comment_avatar.css("opacity", 0.01);
		l_comment_name_text.html(this.display_name);
		if (this.timestamp > 31337)
		{
			l_comment_time.html(relativeTime(this.timestamp, new Date().getTime()));
		} else {
			l_comment_time.html("");
		}
		if (l_comment_text.length)
		{
			l_comment_text.html(this.item);
		} else {
			l_comment_text.html("&nbsp;");
		}
		/* Assemble subitem by combining it with its pieces */
		l_comment_avatar_img.appendTo(l_comment_avatar);
		l_comment_avatar.appendTo(l_comment);
		l_comment_name_text.appendTo(l_comment_name);
		l_comment_name.appendTo(l_comment_content);
		l_comment_time.appendTo(l_comment_content);
		l_comment_text.appendTo(l_comment_content);
		l_comment_content.appendTo(l_comment);
		l_comment.appendTo(l_subitem);
		return l_subitem;
	},
	getReplyHTML: function()
	{
		var l_reply = $("<div></div>").addClass("reply");

		var l_reply_entry = $("<div></div>").addClass("entry");
		var l_reply_entry_edit = $("<div></div>").addClass("edit");
		if (g_myPanel.accountList[0].medium == "TWITTER")
			var l_reply_entry_edit_textarea = $("<iframe></iframe>").addClass("richtext").attr("src", "forced404.html");
		else
			var l_reply_entry_edit_textarea = $("<textarea></textarea>");
		var l_reply_controls = $("<div></div>").addClass("controls");
		var l_reply_controls_picture = $("<div></div>").addClass("picture");
		var l_reply_controls_picture_button = $("<input></input>");
		var l_reply_controls_cancel = $("<div></div>").addClass("cancel");
		var l_reply_controls_cancel_button = $("<input></input>");
		var l_reply_controls_submit = $("<div></div>").addClass("submit");
		var l_reply_controls_submit_button = $("<input></input>");

		/* Assign attributes to subitem */
		l_reply.data("id", this.DOMElementID);
		l_reply_entry_edit_textarea.data("id", this.DOMElementID);
		l_reply_entry_edit_textarea.attr("designMode", "on");
		l_reply_controls_cancel_button.data("id", this.DOMElementID);
		l_reply_controls_submit_button.data("id", this.DOMElementID);
		$(l_reply, l_reply_entry_edit_textarea, l_reply_controls_cancel_button, l_reply_controls_submit_button).data("item", this.id);
		l_reply_controls.hide();
		l_reply_controls_picture_button.attr("type", "button");
		l_reply_controls_picture_button.val("Insert Picture...");
		l_reply_controls_picture_button.data("full-label", "Insert Picture...");
		l_reply_controls_picture_button.data("smaller-label", "Picture...");
		l_reply_controls_submit.data("limit", this.comment_limit);
		l_reply_controls_submit.data("text", this.comment_button);
		l_reply_controls_cancel_button.attr("type", "button");
		l_reply_controls_cancel_button.val("Cancel");
		l_reply_controls_submit_button.attr("type", "button");
		l_reply_entry_edit_textarea.data("helper",this.comment_helper);
		l_reply_entry_edit_textarea.data("initial",this.initial_text);
		if (g_myPanel.accountList[0].medium != "TWITTER")
			l_reply_entry_edit_textarea.val(this.comment_helper);

		/* Assemble item by combining it with its pieces */
		l_reply_entry_edit_textarea.appendTo(l_reply_entry_edit);
		l_reply_entry_edit.appendTo(l_reply_entry);
		l_reply_entry.appendTo(l_reply);
		l_reply_controls_submit_button.appendTo(l_reply_controls_submit);
		l_reply_controls_submit.appendTo(l_reply_controls);
		l_reply_controls_cancel_button.appendTo(l_reply_controls_cancel);
		l_reply_controls_cancel.appendTo(l_reply_controls);
		l_reply_controls_picture_button.appendTo(l_reply_controls_picture);
		if (this.images_allowed)
			l_reply_controls_picture.appendTo(l_reply_controls);	
		l_reply_controls.appendTo(l_reply);
		return l_reply;
	}
}

/*****************************************
 n e w s F o c u s e d ()
 *****************************************/

function newsFocused()
{
	/* Called when window comes into focus.  We instantly notify plugin that
	 * group has been viewed & read; after 1 sec clear group's visible unread count.
	 */
	var l_group = g_myPanel.DOMElementList[g_myPanel.groupSelectedID];
	if (!l_group) return;
	newsGroupViewed(g_myPanel.DOMElementList[g_myPanel.groupSelectedID].name)
	if (l_group.unread > 0) {
		l_group.unread = 0;
		unread();
	} else {
	l_group.unread = 0;
	}
    g_myPanel.visible=true;
	setTimeout(function()
	{
		$("#"+l_group.DOMElementID).find(".count").text(0).parent().hide().parent().find(".label").removeClass("limited");
	}, 1000);

}

/*****************************************
 n e w s B l u r ()
 *****************************************/

function newsBlur()
{
    /* Called when we are no longer in focus.
     * When out of focus, we're not going to mark the active group read.
     */
   g_myPanel.visible=false;
}
/*****************************************
 n e w s A c c o u n t A d d ()
 *****************************************/

function newsAccountAdd(a_account, a_display_name, a_medium, a_status, a_avatar_url)
{
	var l_account = new newsAccount();
	l_account.account = a_account;
	l_account.display_name = decodeURIComponent(a_display_name);
	l_account.medium = a_medium;
	l_account.stats = decodeURIComponent(a_status);
	l_account.avatar_url = a_avatar_url;
	g_myPanel.addAccount(l_account);

}

/*****************************************
 n e w s A c c o u n t U p d a t e ()
 *****************************************/

function newsAccountUpdate(a_account, a_status)
{
}

/*****************************************
 n e w s A c c o u n t R e m o v e ()
 *****************************************/

function newsAccountRemove(a_name)
{
	g_myPanel.removeAccount(a_name);
}

/*****************************************
 n e w s G r o u p A d d ()
 *****************************************/

function newsGroupAdd(a_header, a_name, a_display_name, a_default, a_empty_string, a_post_on, a_post_button, a_post_helper, a_post_limit, a_status, a_shortened_url_length, a_images_allowed, a_icon, a_priority)
{
	var l_group = new newsGroup();
	if (a_header == null)
		l_group.header = getMediumDisplayName();
	else 
		l_group.header = decodeURIComponent(a_header);
	l_group.name = decodeURIComponent(a_name);
	l_group.display_name = decodeURIComponent(a_display_name);
	l_group.dfault = a_default;
	l_group.empty_string = decodeURIComponent(a_empty_string);
	l_group.post_on = a_post_on;
	if (a_post_button) l_group.post_button = a_post_button;
	l_group.post_helper = a_post_helper;
	l_group.post_limit = a_post_limit;
	l_group.stats = a_status;
	if (a_priority) l_group.priority = a_priority;
	if (a_shortened_url_length)
		l_group.shortened_url_length = a_shortened_url_length;
	g_myPanel.addGroup(l_group);
	if (a_images_allowed != null) 
		l_group.images_allowed = a_images_allowed;
	if (a_icon != null)
		l_group.icon = a_icon;
}

function getMediumDisplayName()
{
	switch (g_myPanel.accountList[0].medium)
	{
		case "TWITTER": return "Twitter";
		case "FACEBOOK": return "Facebook";
		case "FOURSQUARE": return "Foursquare";
		case "LINKEDIN": return "LinkedIn";
		default: return g_myPanel.accountList[0].medium;
	}
}

/*****************************************
 n e w s G r o u p U p d a t e ()
 *****************************************/

function newsGroupUpdate(a_header, a_name, a_display_name, a_default, a_empty_string, a_post_on, a_post_button, a_post_helper, a_post_limit, a_status)
{
	if (a_status != null)
	{
		for (var l_enum in g_myPanel.groupList)
		{
			if (g_myPanel.groupList[l_enum].name == a_name)
			{
				g_myPanel.groupList[l_enum].stats = a_status;
				g_myPanel.scheduleUpdate();
			}
		}
	}
}

/*****************************************
 n e w s G r o u p R e m o v e ()
 *****************************************/

function newsGroupRemove(a_header, a_name, a_display_name, a_default, a_empty_string, a_post_on, a_post_button, a_post_helper, a_post_limit, a_status)
{
	g_myPanel.removeGroup(a_header, a_name);
}

/*****************************************
 n e w s I t e m A d d ()
 *****************************************/

function newsItemAdd(a_id, a_parent_id, a_type, a_name, a_display_name, a_item, a_groups, a_unread, a_hide, a_avatar_url, a_timestamp, a_comments_on, a_comment_button, a_comment_helper, a_comment_limit, a_link_url, a_link_title, a_link_description, a_latitude, a_longitude, a_person, a_images_allowed)
{
	if (a_hide) return;
	var l_item = new newsItem();
	l_item.id = a_id;
	l_item.parent_id = a_parent_id;
	l_item.type = a_type;
	l_item.name = a_name;
	if (a_display_name)
		l_item.display_name = decodeURIComponent(a_display_name);
	else
		l_item.display_name = a_name;
	l_item.item = a_item;
	l_item.item = replaceURLWithHTMLLinks(a_item);
	var l_groupitems = a_groups.split(";");
	for (var l_groupitem in l_groupitems) 
	{ 
		l_groupitems[l_groupitem] = decodeURIComponent(l_groupitems[l_groupitem]); 
	}
	l_item.groups = l_groupitems;
	l_item.unread = a_unread;
	l_item.hide = a_hide;
	l_item.avatar_url = a_avatar_url;
	l_item.timestamp = a_timestamp*1000;
	l_item.comments_on = a_comments_on;
	if (a_comment_button) l_item.comment_button = a_comment_button;
	l_item.comment_helper = a_comment_helper;
	if (a_comment_limit) l_item.comment_limit = a_comment_limit;
	l_item.link_url = a_link_url;
	l_item.link_title = a_link_title;
	if (!a_item && a_link_title) 
		l_item.item = a_link_title;
	l_item.link_site = replaceURLWithDomain(a_link_url);
	l_item.link_description = a_link_description;
	l_item.longitude = a_longitude;
	l_item.latitude = a_latitude;
	l_item.person = a_person;
	if (a_images_allowed != null) l_item.images_allowed = a_images_allowed;
	g_myPanel.addItem(l_item);

}

/*****************************************
 n e w s I t e m U p d a t e ()
 *****************************************/

function newsItemUpdate(a_id, a_parent_id, a_type, a_name, a_display_name, a_item, a_groups, a_unread, a_hide, a_avatar_url, a_timestamp, a_comments_on, a_comment_button, a_comment_helper, a_comment_limit, a_link_url, a_link_title, a_link_description, a_latitude, a_longitude, a_person)
{
	for (var l_newsItem in g_myPanel.itemList)
	{
		if (g_myPanel.itemList[l_newsItem].id == a_id)
		{
			var l_item = g_myPanel.itemList[l_newsItem];
			break;
		}
	}
	if (!l_item) return false;
	
	if (a_parent_id) 
		l_item.parent_id = a_parent_id;
	if (a_type)
		l_item.type = a_type;
	if (a_name) 
		l_item.name = a_name;
	if (a_display_name)
		l_item.display_name = decodeURIComponent(a_display_name);
	else if (a_name) 
		l_item.display_name = a_name;
	if (a_item)
		l_item.item = replaceURLWithHTMLLinks(a_item);
	if (a_groups.length)
	{
		var l_groupitems = a_groups.split(";");
		for (var l_groupitem in l_groupitems) 
		{ 
			l_groupitems[l_groupitem] = decodeURIComponent(l_groupitems[l_groupitem]); 
		}
		l_item.groups = l_groupitems;
	}
	if (a_unread)
		l_item.unread = a_unread;
	if (a_hide)
		l_item.hide = a_hide;
	if (a_avatar_url)
		l_item.avatar_url = a_avatar_url;
	if (a_timestamp)
		l_item.timestamp = a_timestamp*1000;
	if (a_comments_on)
		l_item.comments_on = a_comments_on;
	if (a_comment_button) 
		l_item.comment_button = a_comment_button;
	if (a_comment_helper)
		l_item.comment_helper = a_comment_helper;
	if (a_comment_limit) 
		l_item.comment_limit = a_comment_limit;
	if (a_link_url)
		l_item.link_url = a_link_url;
	if (a_link_title)
		l_item.link_title = a_link_title;
	if (a_link_url)
		l_item.link_site = replaceURLWithDomain(a_link_url);
	if (a_link_description)
		l_item.link_description = a_link_description;
	g_myPanel.setDirty(l_item);
	g_myPanel.scheduleUpdate();
	return true;
}

/*****************************************
 n e w s I t e m C h i l d r e n C l e a r ()
 *****************************************/

function newsItemChildrenClear(a_parent)
{
  	for (var l_newsItem in g_myPanel.itemList)
	{
		if (g_myPanel.itemList[l_newsItem].parent_id == a_parent)
		{
           var l_destroyid = g_myPanel.itemList[l_newsItem].id;
           g_myPanel.itemList[l_newsItem] = null;
           delete g_myPanel.itemList[l_newsItem];
           newsItemDestroy(l_destroyid);	

        }
        else if (g_myPanel.itemList[l_newsItem].id == a_parent)
        {
           if (g_myPanel.itemList[l_newsItem].image_id)
               newsItemImageDestroy(g_myPanel.itemList[l_newsItem].image_url, g_myPanel.itemList[l_newsItem].id);
           g_myPanel.itemList[l_newsItem].image_id = 0;
            g_myPanel.setDirty(g_myPanel.itemList[l_newsItem]);
        }
	}
                                                                                                                                                       
	g_myPanel.scheduleUpdate();
	return true;
}
/*****************************************
 n e w s I t e m R e m o v e ()
 *****************************************/

function newsItemRemove(a_id)
{
	for (var l_newsItem in g_myPanel.itemList)
	{
		if (g_myPanel.itemList[l_newsItem].id == a_id)
		{
			var l_destroyid = g_myPanel.itemList[l_newsItem].id;
			if (g_myPanel.contacts[g_myPanel.itemList[l_newsItem].name])
				if (g_myPanel.contacts[g_myPanel.itemList[l_newsItem].name] == 1) 
					delete g_myPanel.contacts[g_myPanel.itemList[l_newsItem].name];
				else
					g_myPanel.contacts[g_myPanel.itemList[l_newsItem].name]--;
			g_myPanel.DOMElementList[g_myPanel.itemList[l_newsItem].DOMElementID] = null;
			delete g_myPanel.DOMElementList[g_myPanel.itemList[l_newsItem].DOMElementID]
                                                                                                                                                       
           
           if (g_myPanel.itemList[l_newsItem].image_id)
                   newsItemImageDestroy(g_myPanel.itemList[l_newsItem].image_url, g_myPanel.itemList[l_newsItem].id);

           g_myPanel.itemList[l_newsItem].image_id = 0;
                                                                                                                                                       
			g_myPanel.itemList[l_newsItem] = null;
			delete g_myPanel.itemList[l_newsItem];
			newsItemDestroy(l_destroyid);			

            break;
		}
	}
	$("div.item[item=" + a_id + "]").remove();
	return true;
}

/*****************************************
 n e w s I t e m I m a g e A d d ()
 *****************************************/

function newsItemImageAdd(a_id, a_url, a_imageID)
{
	g_myPanel.addImage(a_id, a_url, a_imageID)
}

/*****************************************
 n e w s I t e m I m a g e C l e a r ()
 *****************************************/

function newsItemImageClear(a_id, a_url) 
{ 
	g_myPanel.addImage(a_id, null)
}

/*****************************************
 n e w s I t e m C o m m e n t F o c u s ()
 *****************************************/

function newsItemCommentFocus(a_id, a_comment_limit, a_comment_button, a_comment_helper, a_initial_text, a_images_allowed)
{
	/* Keep in mind my terminology differs from this function name:
	 * I usually say "reply" when referring to the ability to add a 
	 * comment.  I refer to existing items w/ parent ids as "comments."
	 */ 
	var l_item = $("div.item[item="+a_id+"], div.subitem[item="+a_id+"]").first();
	if (a_comment_limit != null) g_myPanel.DOMElementList[l_item.attr("id")].comment_limit = a_comment_limit;
	if (a_comment_button != null) g_myPanel.DOMElementList[l_item.attr("id")].comment_button = a_comment_button;
	if (a_comment_helper != null) g_myPanel.DOMElementList[l_item.attr("id")].comment_helper = a_comment_helper;
	if (a_initial_text != null) g_myPanel.DOMElementList[l_item.attr("id")].initial_text = a_initial_text;
	if (a_images_allowed != null) g_myPanel.DOMElementList[l_item.attr("id")].images_allowed = a_images_allowed;

	var l_parent_id = parseInt(l_item.attr("parent_id"));
	if (l_parent_id > 0 && l_parent_id != "NaN")
	{
		l_item = $("div.item[item="+l_parent_id+"]");
	}
	if (l_item.length)
	{
		var l_subitems = l_item.find("div.subitems:first");
		if (!l_subitems.length)
		{
			l_subitems = g_myPanel.DOMElementList[l_item.attr("id")].getSubitemsHTML();

			l_subitems.appendTo(l_item);
		}
		var l_reply = l_subitems.find("div.reply");
		if (l_reply.length)
		{
			var l_controls = l_reply.find(".controls");
			l_reply.show();
			l_controls.show();
			if (g_myPanel.accountList[0].medium == "TWITTER")
			{
				l_reply.richReply();
				l_reply.find(".richtext:first").contents()[0].documentElement.focus();
				setTimeout(function(){ 
					l_reply.find(".richtext:first").contents()[0].documentElement.focus();
				}, 2000);
				l_controls = null;
			} else {			
				l_reply.find(".entry > .edit > textarea").focus();
			}
		} else {
			if (l_subitems.find("div.envelope > div.contents > div.comments").children().length)
			{
				var l_newSeparator = $("<div></div>").addClass("separator");
				l_newSeparator.appendTo(l_subitems.find("div.comments"));
			}	
			var l_reply = g_myPanel.DOMElementList[l_item.attr("id")].getReplyHTML();
			l_reply.appendTo(l_subitems.find(".contents:first"));
			l_subitems.show();
			var l_reply = l_subitems.find(".reply");
			if (l_reply.length)
			{
				if (g_myPanel.accountList[0].medium == "TWITTER")
				{
					l_reply.richReply();
					l_reply.find(".richtext:first").contents()[0].documentElement.focus();
					setTimeout(function(){ 
						l_reply.find(".richtext:first").contents()[0].documentElement.focus();
					}, 2000);
				} else {
					l_reply.find(".entry > .edit > textarea").focus();
				}			
			}											
		}
	}
}

/*****************************************
 n e w s I t e m R e p l y ()
 *****************************************/

function newsItemReply(a_id)
{
	newsItemCommentFocus(a_id, null, null, null, null, null);
	return;
}

/*****************************************
 n e w s M e n u A d d ()
 *****************************************/

function newsMenuAdd(a_menu)
{
	$("#menu").children().remove();
	$('#menu').data('item', a_menu.id);
	$('#menu').css({
		top: a_menu.Y,
		left: a_menu.X
	}).show();
	for (l_enum=0; l_enum<a_menu.choices.length; l_enum++)
	{
		switch (a_menu.choices[l_enum].type)
		{
			case "text":
				var l_item = $("<div></div>").html(a_menu.choices[l_enum].label).addClass("choice").attr("choice", a_menu.choices[l_enum].id);
				$("#menu").append(l_item);
				break;
			case "separator":
				var l_item = $("<div></div>").addClass("separator");
				$("#menu").append(l_item);
				break;
		}
	}
}

/*****************************************
 r e l a t i v e T i m e ()
 *****************************************/

var g_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function relativeTime(a_time, a_epoch)
{
	var l_diff = a_epoch/1000 - a_time/1000;
	if (l_diff > 86400)
	{
		var l_then = new Date(a_time);
		return g_months[l_then.getMonth()] + " " + l_then.getDate();
	}
	if (l_diff > 3600) 
		return parseInt(l_diff/3600) + "h";
	if (l_diff > 60) 
		return parseInt(l_diff/60) + "m";
	return "<1m";
}	

/*****************************************
 t i c k ()
 *****************************************/
function tick()
{
	g_myPanel.tock();
}
setInterval(tick, 15000);

/*
 * Document Ready
 */

var g_editing = false;
var g_replying = false;
var g_pastetarget = 0;
var g_myPanel = new newsPanel();
$(document).ready(function()
{
	if (($.browser.webkit || $.browser.safari) && $.browser.version < "533")
	{
		$("#groups > .header > li.group").addClass("compatible");
	}
	$("#groups > .header > li.group").live("click",function()
	{
		g_myPanel.groupSelectedID = $(this).attr("id");
		viewed();
		g_myPanel.update(true);
	});
	$(".subitem.hasmenu, .item.hasmenu").live("contextmenu", function(e)			// Right-click invokes context menu
	{
		var l_Y = e.pageY;
		var l_X = e.pageX;
		newsItemMenu($(this).attr('item'), l_X, l_Y);
		return false;
	});
	$("#groups > .header > li.group.hasmenu").live("contextmenu", function(e)			// Right-click invokes context menu
	{
		var l_Y = e.pageY;
		var l_X = e.pageX;
		newsGroupMenu(unescape($(this).attr('group')), l_X, l_Y);
		return false;
	});
	$(".account.hasmenu").live("contextmenu", function(e)			// Right-click invokes context menu
	{
		var l_Y = e.pageY;
		var l_X = e.pageX;
		newsAccountMenu(l_X, l_Y);
		return false;
	});

	$("#menu > .choice").live("mouseenter", function(e)			// Menu choice hover state
	{
		$(this).addClass("hovered");
	});
	$("#menu > .choice").live("mouseleave", function(e)			// Menu choice unhover state
	{
		$(this).removeClass("hovered");
	});
	$('#menu').live("contextmenu", function(e){ $("#menu").hide(); return false; });// Right-clicking menu hides it
	//$('#menu > .choice').live("contextmenu", function(e){ $(this).click()});	// Right-clicking choice clicks it
	$('#menu > .choice').live("click", function(e) 				// Left-clicking a choice handles it:
	{
		var l_itemnum = $('#menu').data('item');
		var l_choicenum = $(this).attr("choice");
		var l_itemtext = $(this).html();
		$('#menu').hide();
		switch (l_itemtext)
		{
			case "Reply...":
				newsItemReply(l_itemnum);
				break;
		}
	});
	$(".item").live("dblclick", function()
	{
		if (!$(this).find(".reply > .entry > .edit > richtext.focus").length)
		{
			$(this).addClass("selected");
			var l_id = $(this).attr("item");
			newsItemDefaultAction(l_id);
			return false;	
		}
	});	
	$(".item > .container > .message > .link > .content > .title").live("click", function()
	{
		trillian.openURL($(this).attr("href"));
	});

	$(".item:not(.subitem)").live("click", function()
	{
		//trillian.log("click item=" + $(this).attr("item") + " text=" + $(this).find(".text").html());
		if ($(this).hasClass("selected"))
		{
			$(this).removeClass("selected");
		} else {
			$(".item, .subitem").removeClass("selected");
			if (!$(this).find(".reply > .entry > .edit > .richtext.focus").length)
			{
				$(this).addClass("selected");
				g_replying = false;
				$("#items").find(".richtext").removeClass("focus");
			}
		}
		if (g_myPanel.DOMElementList[$(this).attr("id")].longitude)
		{
			window.frames['map'].showPoint(g_myPanel.DOMElementList[$(this).attr("id")].latitude,g_myPanel.DOMElementList[$(this).attr("id")].longitude);
		}
	});
;
	$(".post > .controls > .submit > input").live("click", function()					// Clicking the post cancel
	{ 
		$(".post > .autocomplete").remove();
		var l_name = g_myPanel.DOMElementList[g_myPanel.groupSelectedID].name
		var l_post = $("#post").find(".richtext:first").contents()[0].documentElement.innerHTML;
		if (l_post != "")
		{
			var l_num=1;
			if (l_post.indexOf("javascript:")===0)
				return setTimeout(function(){trillian.log(eval(l_post.substr(11)));},1000);
			l_post = l_post.stripHeadBody();
			if (l_post.indexOf('<img src="data:image/png;base64,') != -1)
			{
				var l_matches = [];
				while (l_post.indexOf('<img src="data:image/png;base64,') != -1 && l_num < 50)
				{
					l_matches = l_post.match(/(.*)(\<img src="data:image\/png;base64,([a-zA-Z0-9+\/]+={0,2})"[^>]*\>)(.*)/i);
					if (!l_matches) break;
					l_post = l_post.replace(/(.*)(\<img src="data:image\/png;base64,([a-zA-Z0-9+\/]+={0,2})"[^>]*\>)(.*)/i,"$1<IMG ID=\""+l_num+"\" SRC=\"image"+l_num+".jpg\">$4<DATA ID=\""+l_num+"\" TYPE=\"base64\">$3</DATA>");
					l_num++
					if (l_num == 50) trillian.log("matchfail");
				}
				//l_post = l_post.replace(/^(.*)(\<data[^>]*\>)$/i,"<html>$1</html>$2");
				l_post = "<HTML>" + l_post.substr(0,l_post.indexOf("<DATA")) + "</HTML><BINARY>" + l_post.substr(l_post.indexOf("<DATA")) + "</BINARY>";
				l_post = l_post.stripTags();
			} else {
				l_post = l_post.stripHtml().htmlentities();
			}
			if (l_post.length) 
				newsPost(l_name, l_post);
		}
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("selectall");
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("delete");
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, $(".post > .entry > .edit > .richtext:first").data("helper"));
		$($("#post").find(".richtext:first").contents()[0].documentElement).css("font-size", '14px').css("font-family", "Helvetica").css("color", '#acacac');
		$(".post > .entry > .edit > .richtext:first").removeClass("expanded");
		$(".post > .entry > .edit").removeClass("expanded");
		$(".post > .controls").hide();
		resize(); 
		return false;
	});
	$(".post > .controls > .cancel > input").live("click", function()					// Clicking the post cancel
	{ 
		$(".post > .autocomplete").remove();
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("selectall");
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("delete");
		$($("#post").find(".richtext:first").contents()[0].documentElement).css("font-size", '14px').css("font-family", "Helvetica").css("color", '#acacac');
		$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, $(".post > .entry > .edit > .richtext:first").data("helper"));
		$(".post > .entry > .edit > .richtext:first").removeClass("expanded");
		$(".post > .entry > .edit").removeClass("expanded");
		$(".post > .controls").hide();
		$($("#post").find(".richtext:first").contents()[0].documentElement).blur();
		resize(); 
		return true;
	});
	$(".post > .controls > .picture > input").live("click", function()
	{
		newsGetImageFromFile();
	});
	$(".reply > .entry > .edit > textarea").live("keyup", function()					// Typing a reply
	{
		var l_item = $(this).parent().parent().parent().parent().parent().parent().parent();
		var l_submit = l_item.find(".reply > .controls > .submit input");
		if (g_myPanel.DOMElementList[l_item.attr("id")].comment_limit > $(this).val().length)
		{
			var l_counter = g_myPanel.DOMElementList[l_item.attr("id")].comment_limit - $(this).val().length + " left";
		} else {
			var l_counter = $(this).val().length - g_myPanel.DOMElementList[l_item.attr("id")].comment_limit + " over";
		}
		l_submit.val(g_myPanel.DOMElementList[l_item.attr("id")].comment_button.replace("%edit.count_relative%", l_counter));
	});
	$(".reply > .entry > .edit > textarea").live("focus", function()		// Clicking into the reply input 
	{
		//> Add focus class to textarea
		//> 
		$(this).addClass("focus");
		this.setSelectionRange($(this).val().length * 2);
		var l_item = $(this).parent().parent().parent().parent().parent().parent().parent();
		l_item.find(".reply > .controls").show();
		if ($(this).val() == g_myPanel.DOMElementList[l_item.attr("id")].comment_helper) $(this).val((g_myPanel.DOMElementList[l_item.attr("id")].initial_text?g_myPanel.DOMElementList[l_item.attr("id")].initial_text:""));
		var l_submit = l_item.find(".reply > .controls > .submit input");
		if (g_myPanel.DOMElementList[l_item.attr("id")].comment_limit > $(this).val().length)
		{
			var l_counter = g_myPanel.DOMElementList[l_item.attr("id")].comment_limit - $(this).val().length + " left";
		} else {
			var l_counter = $(this).val().length - g_myPanel.DOMElementList[l_item.attr("id")].comment_limit + " over";
		}
		l_submit.val(g_myPanel.DOMElementList[l_item.attr("id")].comment_button.replace("%edit.count_relative%", l_counter));
		resize();
		return true;
	});
	$(".reply > .controls > .picture > input").live("click", function()
	{
		newsGetImageFromFile();
	});
	$(".reply > .controls > .cancel > input").live("click", function()						// Clicking the reply cancel
	{ 
		if (g_myPanel.accountList[0].medium == "TWITTER")
		{
			var l_item = $(this).parent().parent().parent().parent().parent().parent().parent();
			if (g_myPanel.DOMElementList[$(this).data("id")].comments_on)
			{
				l_item.find(".reply > .controls").hide();
				l_item.find(".richtext:first")[0].contentWindow.document.execCommand("");
				l_item.find(".richtext:first").contents()[0].documentElement.innerHTML = l_item.find(".richtext:first").height(18).data("helper");
				$(l_item.find(".richtext:first").contents()[0].documentElement).css("color", "acacac").css("font-style", "italic").css("font-size", "12px");
				if ($.browser.version > "534.48.") 
					$(l_item.find(".richtext:first").contents()[0].documentElement).css("margin-top", "-7px");
				$(l_item.find(".richtext:first").contents()[0].documentElement).blur();
			} else {
				l_item.find(".reply").remove();
				l_item.find(".comments > .separator:last").remove();
				if (l_item.find(".comments").children().length == 0)
				{
					l_item.find(".subitems").hide();
				}
			}
		} else {
			var l_item = $(this).parent().parent().parent().parent().parent().parent().parent();
			if (g_myPanel.DOMElementList[$(this).data("id")].comments_on)
			{
				l_item.find(".reply > .controls").hide();
				l_item.find(".reply > .entry > .edit > textarea").val(g_myPanel.DOMElementList[l_item.attr("id")].comment_helper).removeClass("focus");
			} else {
				l_item.find(".reply").remove();
				l_item.find(".comments > .separator:last").remove();
				if (l_item.find(".comments").children().length == 0)
				{
					l_item.find(".subitems").hide();
				}
			}
		}
		g_replying = false;
		resize(); 
		return false;
	});
	$(".reply > .controls > .submit > input").live("click", function()						// Clicking the reply cancel
	{ 
		var l_id = g_pastetarget;
		if (l_id)
		{
			$(".subitems > .autocomplete").remove();
			var l_item = $("div.item[item=" + l_id + "]")
			var l_richtext = l_item.find(".richtext:first");
			var l_name = g_myPanel.DOMElementList[l_item.attr("id")].name;
			var l_post = l_richtext.contents()[0].documentElement.innerHTML;
			if (l_post != "")
			{
				var l_num=1;
				l_post = l_post.stripHeadBody();
				if (l_post.indexOf('<img src="data:image/png;base64,') != -1)
				{
					var l_matches = [];
					while (l_post.indexOf('<img src="data:image/png;base64,') != -1 && l_num < 50)
					{
						l_matches = l_post.match(/(.*)(\<img src="data:image\/png;base64,([a-zA-Z0-9+\/]+={0,2})"[^>]*\>)(.*)/i);
						if (!l_matches.length) break;
						l_post = l_post.replace(/(.*)(\<img src="data:image\/png;base64,([a-zA-Z0-9+\/]+={0,2})"[^>]*\>)(.*)/i,"$1<IMG ID=\""+l_num+"\" SRC=\"image"+l_num+".jpg\">$4<DATA ID=\""+l_num+"\" TYPE=\"base64\">$3</DATA>");
						l_num++
						if (l_num == 50) trillian.log("matchfail");
					}
					l_post = "<HTML>" + l_post.substr(0,l_post.indexOf("<DATA")) + "</HTML><BINARY>" + l_post.substr(l_post.indexOf("<DATA")) + "</BINARY>";
					l_post = l_post.stripTags();
				} else {
					l_post = l_post.stripHtml().htmlentities();
				}
				if (l_post.length) 
					newsComment(l_id, l_post, l_name);
			}
			l_richtext.contents()[0].documentElement.innerHTML = l_richtext.height(18).data("helper");
			$(l_richtext.contents()[0].documentElement).css("color", "acacac").css("font-style", "italic").css("font-size", "12px");
		} else {
			var l_item = $(this).parent().parent().parent().parent().parent().parent().parent();
			var l_id = l_item.attr("item");
			var l_name = g_myPanel.DOMElementList[l_item.attr("id")].name;
			var l_post = l_item.find(".reply > .entry > .edit > textarea").val();
			if (l_post != "" && l_post != g_myPanel.DOMElementList[l_item.attr("id")].initial_text+" ")
			{
				newsComment(l_id, l_post, l_name);
			}
		}			
		if (g_myPanel.DOMElementList[l_item.attr("id")].comments_on)
		{
			l_item.find(".reply > .controls").hide();
			l_item.find(".reply > .entry > .edit > .richtext").removeClass("focus");
			l_item.find(".reply > .entry > .edit > textarea").val(g_myPanel.DOMElementList[l_item.attr("id")].comment_helper).removeClass("focus");
		} else {
			l_item.find(".reply").remove();
			l_item.find(".comments > .separator:last").remove();
			if (l_item.find(".comments").children().length == 0)
			{
				l_item.find(".subitems").hide();
			}
		}
		g_replying = false;
		resize(); 
		return false;
	});


	$(".post > .controls").find("input").live("mouseenter", function()
	{
		$(".post > .entry > .edit > .richtext:first").css("outline", "none");
	});
	$(".post > .controls").find("input").live("mouseleave", function()
	{
		$(".post > .entry > .edit > .richtext:first").css("outline", "");
	});
	$(".reply > .controls").find("input").live("mouseenter", function()
	{
		//$(this).parent().parent().parent().parent().parent().find("textarea").css("outline", "none");
	});
	$(".reply > .controls").find("input").live("mouseleave", function()
	{
		//$(this).parent().parent().parent().parent().parent().find("textarea").css("outline", "");
	});
	$(".post > .autocomplete > .entry").live("mouseenter", function()
	{
		$(this).addClass("hover").siblings().removeClass("hover");
	});
	$(".post > .autocomplete > .entry").live("mouseleave", function()
	{
		$(this).removeClass("hover");
	});
	$(".post > .autocomplete > .entry").live("click", function()
	{
			$("#post").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, $(this).text().substr($(this).parent().data("typed").length-1) + " ");
			$(".post > .autocomplete").remove();
			$("#post").find(".richtext:first").focus();
	});

	$(".subitems > .autocomplete > .entry").live("mouseenter", function()
	{
		$(this).addClass("hover").siblings().removeClass("hover");
	});
	$(".subitems > .autocomplete > .entry").live("mouseleave", function()
	{
		$(this).removeClass("hover");
	});
	$(".subitems > .autocomplete > .entry").live("click", function()
	{
			$("div.item[item=" + g_pastetarget + "]").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, $(this).text().substr($(this).parent().data("typed").length-1) + " ");
			$(".subitems > .autocomplete").remove();
			$("div.item[item=" + g_pastetarget + "]").find(".richtext:first").focus();
	});


	$(".item").find(".fill > img").live("click dblclick", function()
	{
		newsImageDefaultAction($(this).attr("src"), $(this).parent().parent().parent().parent().parent().parent().attr("item"));
		return false;
	});
	$(".item > .container > .message > .name").live("click", function()
	{
		newsItemDefaultAction($(this).parent().parent().parent().attr("item"));
		return false;
	});
	$(".comment > .content > .name > .text").live("click", function()
	{
		newsItemDefaultAction($(this).parent().parent().parent().parent().attr("item"));
		return false;
	});
	$(".comment > .avatar").live("click", function()
	{
		newsItemDefaultAction($(this).parent().parent().attr("item"));
		return false;
	});
	$("li.header > .showhide").live("mouseenter", function()
	{	
		$(this).find(".label").show();
		$(this).parent().find(".label").addClass("shortened");
	});
	$("li.header > .showhide > .label").live("mouseenter", function() 
	{
		$(this).addClass("over");
		$(this).parent().find(".label").removeClass("shortened");
		if ($(this).hasClass("down")) $(this).addClass("highlighted");
	});
	$("li.header > .showhide").live("mouseleave", function()
	{	
		if (!$(this).find(".label").hasClass("down")) $(this).find(".label").hide();
		$(this).parent().find(".label").removeClass("shortened");
	});
	$("li.header > .showhide > .label").live("mouseleave", function() 
	{
		$(this).removeClass("over").removeClass("highlighted");
	});
	$("li.header > .showhide").live("mousedown", function()
	{
		$(this).find(".label").addClass("down");
		if ($(this).find(".label").hasClass("over")) $(this).find(".label").addClass("highlighted");
		return true;
	});
	
	$("li.header > .showhide").live("dblclick", function()
	{	
		if ($(this).find(".label").text() == "Hide")
		{
			$(this).parent().find(".group").hide();
			$(this).find(".label").text("Show");
			resize();
		} else {
			$(this).parent().find(".group").show();
			$(this).find(".label").text("Hide");
			resize();
		}
	});	
	$("li.header > .showhide").live("mouseup", function()
	{	
		$(this).find(".label").removeClass("down").removeClass("highlighted");
		if ($(this).find(".label").hasClass("over"))
		{
			if ($(this).find(".label").text() == "Hide")
			{
				$(this).parent().find(".group").hide();
				$(this).find(".label").text("Show");
				resize();
			} else {
				$(this).parent().find(".group").show();
				$(this).find(".label").text("Hide");
				resize();
			}
		}
		return false;
	});	
	$("*").live("mouseup", function()
	{
		if (!$(this).hasClass("showhide")) $("li.header > .showhide > .label").removeClass("down").hide();
	});
	resize();
	$("#items").click(viewed);
	$("#items").scroll(viewed);
	$("#items").scroll(viewed);
	$("body").live("selectstart",function(){ if (!g_editing && !g_replying) return false; });
});
function resize()
{
	var l_window_height = $(window).height();
	var l_accounts_height = $("#accounts").height();
	var l_post_height = $("#post").height();
	var l_panel_height = l_window_height;
	var l_view_height = $("#view").height();
	var l_items_height = l_window_height - l_accounts_height - l_post_height - l_view_height;
	var l_left_height = l_window_height;
	var l_right_height = l_window_height;
	$("#items").height(l_items_height);
	$("#panel").height(l_panel_height);
	$("#right").height(l_left_height);
	var l_right_width = $("#panel").width()-$("#left").width()-1;
	$("#items").width(l_right_width);
	$("#view").width(l_right_width);
	$(".post").width(l_right_width);
	$(".post > .controls").width(l_right_width);
	$("div.message").each(function(){
		if ($(this).height() < 52) $(this).css("margin-top", (($(this).height()/2)+35)*-1 + "px").css("padding-bottom", (52-$(this).height())/4);
		else $(this).css("margin-top", -52);
	});
	if (l_right_width < 333) 
		$(".reply > .controls > .picture > input").each(function(){ $(this).val($(this).data("smaller-label"))});
	else 
		$(".reply > .controls > .picture > input").each(function(){ $(this).val($(this).data("full-label"))});
	if ($("#left").hasScrollBar()) 
		$("#groups").addClass("scrollable");
	else
		$("#groups").removeClass("scrollable");
}
function viewed()
{
	var l_group = g_myPanel.DOMElementList[g_myPanel.groupSelectedID];
	if (!l_group) return;
	newsGroupViewed(g_myPanel.DOMElementList[g_myPanel.groupSelectedID].name)
	if (l_group.unread > 0) {
		l_group.unread = 0;
		unread();
	} else {
		l_group.unread = 0;
	}
	$("#"+l_group.DOMElementID).find(".count").text(0).parent().hide().parent().find(".label").removeClass("limited");
}	

function unread()
{
	var l_totalunread = 0;
	for (l_enum in g_myPanel.groupList)
	{
		if (g_myPanel.groupList[l_enum].unread > 0 && g_myPanel.groupList[l_enum].unread != "NaN")
		{
			l_totalunread += g_myPanel.groupList[l_enum].unread;
		}
	}
	newsAccountUnread(l_totalunread);
}

/* 
 * Bindings
 */

$(window).bind("resize", resize);			// Call the "resize" function
$(document).bind("click",function() 			// Clicking outside of the menu closes it
{
	$('#menu').hide();
});
$(document).bind("contextmenu", function()		// Right-clicking outside of a menu closes it
{
	$('#menu').hide();
	return false;					// Prevents browser right-click menu
});

function replaceURLWithHTMLLinks(text) 
{
	if (text)
	{
		return text.replace(/(<a href=")?((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))(">([^<]+)<\/a>)?/ig, function($0,$1,$2,$3,$4,$5,$6,$7){ return $7?'<a href="'+$2+'" title="'+$2+'+">'+$7+'</a>':'<a href="'+$2+'" title="'+$2+'">'+$2+'</a>'; });
	}
}

function replaceURLWithDomain(text)
{
	if (text)
	{
		var exp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?='~_|!:,.;]*)([\/]?[-A-Z0-9+&@?#\/%=~_|]*))/ig;
		return text.replace(exp,"$3"); 
	}
}

function replaceTwitterTagsWithLinks(text)
{
	if (text)
	{
		var namified = text.replace(/<a href="twitter_[a-zA-Z0-9_]:\/\/([a-zA-Z0-9_]+)">([^<]+)<\/a>/ig, '<a href="http://twitter.com/$1">$2</a>');
		return namified.replace(/\B(#[a-zA-Z0-9_]+)/ig, "<a href='http://search.twitter.com/search?q=$1'>$1</a>");
	}
}

String.prototype.stripHtml = function() { return this.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ').replace(/\<br ?\/?\>/ig,'').replace(/\<\/?(div|span)\>/ig,'').replace(/\t/ig, ''); };
String.prototype.stripHeadBody = function() { return this.replace(/<head><\/head><body>(.*)<\/body>/, '$1'); };
String.prototype.stripTags = function() { return this.replace(/&nbsp;/g, ' ').replace(/\<br ?\/?\>/ig,'').replace(/\<\/?(div|span)\>/ig,'').replace(/\t/ig, ''); };
String.prototype.htmlentities = function() { return this.replace(/&/g, '&amp;').replace(/\</g, '&lt;').replace(/\>/g, '&gt;'); };

String.prototype.linkifyTwitter = function() { return this.replace(/([^\>])(@[a-zA-Z0-9_]+)([^a-zA-Z0-9])/, "$1<span style='color: blue'>$2</span>$3"); };

/*
* jQuery TinySort - A plugin to sort child nodes by (sub) contents or attributes.
*
* Version: 1.0.4
*
* Copyright (c) 2008 Ron Valstar
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* description
*   - A plugin to sort child nodes by (sub) contents or attributes.
*
* Usage:
*   $("ul#people>li").tsort();
*   $("ul#people>li").tsort("span.surname");
*   $("ul#people>li").tsort("span.surname",{order:"desc"});
*   $("ul#people>li").tsort({place:"end"});
*
* Change default like so:
*   $.tinysort.defaults.order = "desc";
*
* in this update:
*	- changed setArray to pushStack
*
* in last update:
*	- tested with jQuery 1.4.1
*	- correct isNum return
*
* Todos
*   - fix mixed literal/numeral values
*   - determine if I have to use pushStack or pushStack
*
*/
;(function($) {
	// default settings
	$.tinysort = {
		 id: "TinySort"
		,version: "1.0.4"
		,defaults: {
			 order: "asc"	// order: asc, desc or rand
			,attr: ""		// order by attribute value
			,place: "start"	// place ordered elements at position: start, end, org (original position), first
			,returns: false	// return all elements or only the sorted ones (true/false)
		}
	};
	$.fn.extend({
		tinysort: function(_find,_settings) {
			if (_find&&typeof(_find)!="string") {
				_settings = _find;
				_find = null;
			}

			var oSettings = $.extend({}, $.tinysort.defaults, _settings);

			var oElements = {}; // contains sortable- and non-sortable list per parent
			this.each(function(i) {
				// element or sub selection
				var mElm = (!_find||_find=="")?$(this):$(this).find(_find);
				// text or attribute value
				var sSort = oSettings.order=="rand"?""+Math.random():(oSettings.attr==""?mElm.text():mElm.attr(oSettings.attr));
				// to sort or not to sort
				var mParent = $(this).parent();
				if (!oElements[mParent]) oElements[mParent] = {s:[],n:[]};	// s: sort, n: not sort
				if (mElm.length>0)	oElements[mParent].s.push({s:sSort,e:$(this),n:i}); // s:string, e:element, n:number
				else				oElements[mParent].n.push({e:$(this),n:i});
			});
			//
			// sort
			for (var sParent in oElements) {
				var oParent = oElements[sParent];
				oParent.s.sort(
					function zeSort(a,b) {
						var x = a.s.toLowerCase?a.s.toLowerCase():a.s;
						var y = b.s.toLowerCase?b.s.toLowerCase():b.s;
						if (isNum(a.s)&&isNum(b.s)) {
							x = parseFloat(a.s);
							y = parseFloat(b.s);
						}
						return (oSettings.order=="asc"?1:-1)*(x<y?-1:(x>y?1:0));
					}
				);
			}
			//
			// order elements and fill new order
			var aNewOrder = [];
			for (var sParent in oElements) {
				var oParent = oElements[sParent];
				var aOrg = []; // list for original position
				var iLow = $(this).length;
				switch (oSettings.place) {
					case "first": $.each(oParent.s,function(i,obj) { iLow = Math.min(iLow,obj.n) }); break;
					case "org": $.each(oParent.s,function(i,obj) { aOrg.push(obj.n) }); break;
					case "end": iLow = oParent.n.length; break;
					default: iLow = 0;
				}
				var aCnt = [0,0]; // count how much we've sorted for retreival from either the sort list or the non-sort list (oParent.s/oParent.n)
				for (var i=0;i<$(this).length;i++) {
					var bSList = i>=iLow&&i<iLow+oParent.s.length;
					if (contains(aOrg,i)) bSList = true;
					var mEl = (bSList?oParent.s:oParent.n)[aCnt[bSList?0:1]].e;
					mEl.parent().append(mEl);
					if (bSList||!oSettings.returns) aNewOrder.push(mEl.get(0));
					aCnt[bSList?0:1]++;
				}
			}
			//
			return this.pushStack(aNewOrder); // pushStack or pushStack?
		}
	});
	// is numeric
	function isNum(n) {
		var x = /^\s*?[\+-]?(\d*\.?\d*?)\s*?$/.exec(n);
		return x&&x.length>0?x[1]:false;
	};
	// array contains
	function contains(a,n) {
		var bInside = false;
		$.each(a,function(i,m) {
			if (!bInside) bInside = m==n;
		});
		return bInside;
	};
	// set functions
	$.fn.TinySort = $.fn.Tinysort = $.fn.tsort = $.fn.tinysort;
})(jQuery);

/* from http://james.padolsey.com/javascript/sorting-elements-with-jquery/ */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

function buildMap()
{
	$("#view").show();
	for (var l_enum in g_myPanel.itemList)
	{
		var l_item = g_myPanel.itemList[l_enum];
		if (l_item.groups.indexOf(g_myPanel.DOMElementList[g_myPanel.groupSelectedID].name) != -1)
		{
			if (l_item.person)
			{
				window.frames['map'].addFriend(l_item.id,l_item.latitude,l_item.longitude,l_item.display_name,l_item.item,l_item.avatar_url);
			} else {
				window.frames['map'].addVenueDot(l_item.id,l_item.latitude,l_item.longitude,l_item.display_name);
			}
		}
	}
	window.frames['map'].showFriends();
	window.frames['map'].refit(1);
	g_myPanel.DOMElementList[g_myPanel.groupSelectedID].view = window.frames['map'];
}


/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
*		- A percentage of the container's dimension/s, for example: 50% to go to the middle.
 *		- The string 'max' for go-to-end. 
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

/* Rich edit box for reply area */
(function( $ ){

  $.fn.richReply = function( type ) {  

    return this.each(function() {
	
      var $this = $(this);

	var l_reply = $this;
	var l_restore_mode = false;
	var l_item = g_myPanel.DOMElementList[l_reply.parent().parent().parent().parent().attr("id")];

	l_reply.find(".richtext:first")[0].contentWindow.document.designMode = "on";
 	var l_docEl = $(l_reply.find(".richtext:first").contents()[0].documentElement);
	l_docEl.attr("spellcheck", "false");
	l_docEl.css("margin", "0px").css("padding", "2px").css("font-size", '12px').css("font-family", 'Lucida Grande, sans-serif').css("color", '#989898').css("background-color", "#ffffff").css("font-style", "italic").css("overflow-y", "hidden");
	if (l_reply.find(".richtext:first").data("helper"))
	{
		l_docEl.html(l_reply.find(".richtext:first").data("helper"));
	}
	if (l_reply.find(".richtext:first").data("restore"))
	{
		l_restore_mode = true;
		l_docEl.html(l_reply.find(".richtext:first").data("restore"));
		if (l_docEl.text() != l_reply.find(".richtext:first").data("helper")) l_docEl.css("font-size", '12px').css("font-family", "Helvetica").css("color", '#000000').css("overflow-x"," none").css("word-break", "break-word").css("padding-right", "5px").css("font-style", "normal").css("overflow-y", "hidden");
	}
	l_docEl.data("parent_id", l_item.id);
	l_docEl.click( function()
	{
		if (!g_replying) 
			l_docEl.focus();
	});
	l_docEl.focus( function()
	{ 
		if (g_replying) 
			return;
		g_replying = true;
		g_pastetarget = $(this).data("parent_id");
		var l_parent = $("div.item[item=" + $(this).data("parent_id") +"]");
		var l_richtext = l_parent.find(".richtext");
		$(this).css("font-size", '12px').css("font-family", "Helvetica").css("color", '#000000').css("overflow-x"," none").css("word-break", "break-word").css("padding-right", "5px").css("font-style", "normal").css("overflow-y", "hidden");

		l_richtext.height(48);
		var l_counter = "";
		var l_limit = g_myPanel.DOMElementList[l_parent.attr("id")].comment_limit;
		for (var l_shortened=""; l_shortened.length<g_myPanel.DOMElementList[g_myPanel.groupSelectedID].shortened_url_length; l_shortened+="X");
		var l_thislength = this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length;
		if (l_limit > l_thislength)
		{
			l_counter = l_limit - l_thislength + " left";
		} else {
			l_counter = l_thislength - l_limit + " over";
		}
		if (this.innerHTML.stripHeadBody().stripHtml().indexOf(l_richtext.data("helper")) != -1 || !l_richtext.data("helper")) 
		{
			l_counter = l_limit - g_myPanel.DOMElementList[l_parent.attr("id")].initial_text.length + " left";
			l_richtext[0].contentWindow.document.execCommand("selectall");
			l_richtext[0].contentWindow.document.execCommand("delete");
			l_richtext.contents()[0].documentElement.innerHTML = "&nbsp;";
			setTimeout(function(){ 
				var l_richtext = $("div.item[item="+g_pastetarget+"]").find(".richtext:first");
				l_richtext[0].contentWindow.document.execCommand("selectall"); 
				l_richtext[0].contentWindow.document.execCommand("delete"); 
				if (l_richtext.data("initial")) 
					l_richtext[0].contentWindow.document.execCommand("inserttext", false, l_richtext.data("initial"));
				// fix attempt from http://stackoverflow.com/questions/8111003/set-focus-on-iframe-in-chrome
				try{ 
					var win = l_richtext[0].contentWindow;
					var range = win.document.createRange();
					range.setStart(win.document.body, 0);
					range.setEnd(win.document.body, 0);
					win.document.body.focus();
					win.getselection().addrange(range);
				}catch(err){}
			}, 200);
		}
 		l_richtext.addClass("focus expanded one"); //iframe.richtext
		l_parent.find(".controls").show().find(".submit input").val(g_myPanel.DOMElementList[l_parent.attr("id")].comment_button.replace("%edit.count_relative%", l_counter));
		if (!l_richtext.hasClass("animated") && l_richtext.position().top + ((g_myPanel.accountList[0].medium == "TWITTER")?300:l_parent.find(".reply").height()-10) > $("#items").height())
		{
			var l_offset = -75;
			if ($("#items").height() > 400)
			{
				var l_offset = ($("#items").height() - (g_myPanel.accountList[0].medium == "TWITTER"?330:l_parent.find(".reply").height()+10)) * -1;
			}
			$("#items").scrollTo("[item=" + g_pastetarget + "] > .subitems > .envelope > .contents > .reply", 800, {easing: 'swing', offset: l_offset});
			l_richtext.addClass("animated");
		}
		resize();
		return false;
	});
	l_docEl[0].addEventListener("blur",function()
	{
		var l_iframe = $(this.ownerDocument.defaultView.frameElement);
		var l_html = $(l_iframe.contents()[0].documentElement);
		var l_parent = $("div.item[item=" + g_pastetarget +"]");
		var l_richtext = l_parent.find(".richtext");
		l_richtext.removeClass("focus");
		g_replying = false;
		setTimeout(function(){$("div.item[item=" + g_pastetarget + "]").find(".autocomplete").remove();}, 500);
	});
	l_reply.find(".richtext:first")[0].contentWindow.document.onpaste = function(e) 
	{
		e.preventDefault();
		if (e.clipboardData.types)
		{
			if (e.clipboardData.types.length)
			{
				if (e.clipboardData.types[1] == "text/plain" || e.clipboardData.types[0] == "text/rtf")
				{
					var paste = e.clipboardData.getData("text/plain");
				}
			}
		}
		if (paste) 
		{
			paste = decodeURIComponent(encodeURIComponent(paste.stripHtml()).replace(/%0D%0A/g,"").replace(/%0D/g,""));
			$("div.item[item=" + g_pastetarget + "]").find(".richtext:first")[0].contentWindow.document.execCommand("inserttext", false, paste);
			$($("div.item[item=" + g_pastetarget + "]").find(".richtext:first").contents()[0].documentElement).keyup();
		} else {
			newsGetImageFromClipboard();
		}
		//trillian.log($("#post").find(".richtext:first")[0].contentWindow.document.innerHTML);
		return false;
	}	
	l_docEl.keydown(function(event)
	{
		var l_parent = $("div.item[item=" + $(this).data("parent_id") +"]");
		var l_richtext = l_parent.find(".richtext");
		var l_autocomplete = l_parent.find(".autocomplete");
		if (event.which==9 || event.which==39 || event.which==13 || event.which==32)
		{
			var l_selected = l_autocomplete.find(".hover");
			if (l_selected.length)
			{
				l_selected.click();
				return false;
			}
		}
		if (event.which==9)
		{
			if (l_autocomplete.length);
			{
				l_autocomplete.find(".entry:first").click();
				return false;
			}
		}
		else if (event.which==40)
		{
			var l_selected = l_autocomplete.find(".hover");
			if (l_selected.length) 
			{
				if (l_selected.next().length)
				{
					for (var i=0; i<1 || ((event.metaKey || event.ctrlKey) && i<5); i++)
					{
						if (i>1) var l_selected = l_autocomplete.find(".hover");
						l_selected.next().addClass("hover").siblings().removeClass("hover");
						if (l_autocomplete.height() - $(".hover:first").position().top < l_selected.height()) l_autocomplete.scrollTop($(".hover:first").height()+8 + l_autocomplete.scrollTop());
					}
				}
				return false;
			} 
			else if (l_autocomplete.length) 
			{
				l_autocomplete.data("entered", "true").find(".entry:first").addClass("hover");
				return false;
			}
		}	
		else if (event.which==38)
		{
			var l_selected = l_autocomplete.find(".hover");
			if (l_selected.length) 
			{
				if (l_selected.prev().length)
				{
					for (var i=0; i<1 || ((event.metaKey || event.ctrlKey) && i<5); i++)
					{
						if (i>1) var l_selected = l_autocomplete.find(".hover");
						l_selected.prev().addClass("hover").siblings().removeClass("hover");
						if ($(".hover:first").position().top < 0) l_autocomplete.scrollTop(l_autocomplete.scrollTop() - $(".hover:first").height() - 8);
					}
				} else {
					l_selected.removeClass("hover");
				}	
				return false;
			}
			if (l_autocomplete.length)
			{
				if (l_autocomplete.data("entered")) return false;
				else l_autocomplete.remove();
			}
		} 
		else if (event.which==27)
		{
			if (l_autocomplete.length)
				l_autocomplete.remove();
			else
				
				l_parent.find(".controls > .cancel > input").click();
			return false;
		}
		if (event.which==9 || event.which == 13 || event.altKey && (event.which!=37 && event.which!=39) || ((event.ctrlKey || event.metaKey) && (event.which!=86 && event.which!=65 && event.which!=88 && event.which!=37 && event.which!=39 && event.which!=81))) return false; 
	});

	l_docEl.keyup( function(event)
	{
		if (event.which==17 || event.which==91 || event.which==27) return false;
		var l_submit = $(".reply > .controls > .submit");
		var l_submit_button = l_submit.find("input");
		var l_limit = $(l_submit).data("limit");
		var l_text = $(l_submit).data("text");
		for (var l_shortened=""; l_shortened.length<g_myPanel.DOMElementList[g_myPanel.groupSelectedID].shortened_url_length; l_shortened+="X");
		if (l_limit > this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/ig, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length)
		{
			var l_counter = l_limit - this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length + " left";
		} else {
			var l_counter = this.innerHTML.stripHeadBody().stripHtml().replace(/\<img[^>]+\>/g, l_shortened).replace(/((https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?='~_|!:,.;]*)([-A-Z0-9+&@#\/%=~_|]))/ig,l_shortened).length - l_limit + " over";
		}
		$(l_submit_button).val(l_text.replace("%edit.count_relative%", l_counter));
		if (g_myPanel.accountList[0].medium == "TWITTER")
		{
			var l_parent = $("div.item[item=" + $(this).data("parent_id") +"]");
			var l_richtext = l_parent.find(".richtext");
			var l_autocomplete = l_parent.find(".autocomplete");
			if (l_matches = this.innerHTML.stripHeadBody().stripHtml().match(/(^|[^a-zA-Z0-9])(@[a-zA-Z_]+)$/)) 
			{
				if (event.which==9 || event.which==13 || event.which==38 || event.which==39 || event.which==40) return false;

				l_autocomplete.remove();
				var l_reply_autocomplete = $("<div></div>").addClass("autocomplete").width(l_parent.find(".edit").width()).data("typed", l_matches[2]).hide();
				l_reply_autocomplete.appendTo(l_parent.find(".subitems"));
				for (l_contact in g_myPanel.contacts)
				{
					if (l_contact.toLowerCase().indexOf(l_matches[2].toLowerCase().substr(1)) == 0)
					{
						$("<div></div>").addClass("entry").html(l_contact).appendTo(l_reply_autocomplete);
					}
				}
				if (l_reply_autocomplete.children().length)
				{
					l_reply_autocomplete.children().sortElements(function(a,b) 
					{
						return $(a).text().toLowerCase() < $(b).text().toLowerCase() ? -1 : 1;
					}).end().show();
					l_reply_autocomplete.css("margin-bottom", -1 * l_reply_autocomplete.height() + "px");
 					setTimeout(function(){
						var l_reply_autocomplete = $("div.item[item=" + g_pastetarget + "]").find(".autocomplete");
						if (l_reply_autocomplete.length)
						{
							if (l_reply_autocomplete.position().top + l_reply_autocomplete.height() > $("#items").height())
							{
								$("#items").scrollTo("+=" + (l_reply_autocomplete.position().top + l_reply_autocomplete.height() - $("#items").height()) + "px",  500, {easing: 'swing'});
							}
						}
					}, 500);

				}	
			} else {
				l_autocomplete.remove();
			}
		}
	});
	if (g_myPanel.accountList[0].medium == "TWITTER" && !l_restore_mode)
		l_docEl.focus();
    });
  };
})( jQuery );

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);



