// TODO: Break this file into more modular parts, such as a part for handling the follows, etc.

// TODO: Is this function ever used?  Appears not to be
function getClassName(obj) {
	if (typeof obj !== "object" || obj === null) {
		return false;
	}
	return (/(\w+)\(/.exec(obj.constructor.toString())[1]);
}


/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){jQuery.browser.mobile=/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Ricochet={};

$(document).ready(function() {

	// TODO: We need to get this initialization code (the parts of it that
	// modify the view such as enabling/disabling/hiding/revealing links
	// and so on) into a function that we can call and pass in a context.
	// Then on document load, it can be run on the document, and on sidebar
	// load, it can be run on the sidebar.  Currently, some of that
	// JavaScript code does not get applied to the sidebar, nor on AJAX
	// load of comments (in the mobile site).

        // Fill in user-specific stuff on the page
	if (UserName != "") {
		// TODO: Can some of this code go straight into the page_foot_userdata.tpl, to be run right when the page encounters it?  Or will that slow down the rest of the page?
		$('.user-name').text(UserName);
		$('#user-profile-link a').attr('href', UserProfile);
                $('#user-account-link a').attr('href', "/content/edit/" + UserId);
                if (UserInboxTotal > 0) {
			if (UserInboxNew > 0) {
				$('#user-inbox-count').html("<strong>" + UserInboxNew + "</strong>/" + UserInboxTotal);
			} else {
				$('#user-inbox-count').html("" + UserInboxTotal);
			}
                        $('#user-inbox-link').show();
		}
                if (UserDrafts > 0) {
                        $('#user-drafts-link').show();
		}
                $('#signed-in').show();
		if (UserImage == "") {
			$('img.my_profile_image').attr({
				alt: UserName,
				title: UserName});
		} else {
			$('img.my_profile_image').attr({
				alt: UserName,
				title: UserName,
				src: '/' + UserImage});
		}
        } else {
                $('#signed-out').show();
	}
        $('#user-welcome').show();

	if ( jQuery.browser.mobile ) {
		// Mobile browsers don't usually handle the rich-text editor well,
		// so replace all the rich-text editors with plain-text editors

		// TODO: Use the autoresize plugin from http://james.padolsey.com/javascript/jquery-plugin-autoresize/
		//	 (Expands the text box as you type!)

		// TODO: Improve this code for detecting devices and setting cols and rows appropriately for the display size
		//       For example, perhaps try calculating based on the screen.width and screen.height instead
		/* I think we can actually just use CSS to set the width to 100% or close thereabout
		var cols2 = screen.width, rows2 = screen.height;
		var cols = 28, rows = 15;
		if (navigator.userAgent.match(/Android/i)) {
			cols=38; rows=13;
		} else if (navigator.userAgent.match(/iPad/i)) {
			cols=46; rows=15;
		} else if (navigator.userAgent.match(/iPod/i)) {
			cols=23;
		} else if (navigator.userAgent.match(/iPhone/i)) {
			cols=23;
		} else if (navigator.userAgent.match(/mobile/i)) {
			cols=38; rows=13;
		}
		*/
		$('.oe-window textarea').each(function() {
		        var textarea = $(this);
			var cols = 38, rows = textarea.attr('rows');
			var fieldId = textarea.attr('id').split('ContentObjectAttribute_data_text_').pop();
			textarea.replaceWith(
				'<textarea class="box" cols="' + cols + '" rows="' + rows + '"' +
					' id="mobile-ContentObjectAttribute_data_text_' + fieldId + '"' +
					' name="mobile-ContentObjectAttribute_data_text_' + fieldId + '"' +
					' onkeyup="Ricochet.CountManager.textarea_wc(this)"' +
					' style="width:99%;"></textarea>'
			);
		});
	}

	// Init the lightbox plugin on images with lightbox class
        // We pass in blank images for the "Next" and "Previous" buttons; this is a poor man's way of disabling them
	$('a.lightbox').lightBox({
		imageLoading: '/extension/ricochet/design/ezwebin/images/ajax-loader.gif',
		imageBtnClose: '/extension/ricochet/design/ezwebin/images/lightbox-btn-close.gif',
		imageBtnPrev: '/extension/ricochet/design/ezwebin/images/lightbox-blank.gif',
		imageBtnNext: '/extension/ricochet/design/ezwebin/images/lightbox-blank.gif',
		imageBlank: '/extension/ricochet/design/ezwebin/images/lightbox-blank.gif'
	});

	// Toggle Follow links
	if(typeof UserFollows != "undefined") {
		for(var i in UserFollows) {
			var $followLI = $('.follow-msg-' + UserFollows[i]);
			if ($followLI) {
				$followLI.addClass('link2');
			}
		}
	}
	
	// Toggle Like links
	if(typeof UserLikes != "undefined") {
		for(var i in UserLikes) {
			var $likeA = $('.like-msg-' + UserLikes[i]);
			if ($likeA) {
				$likeA.addClass('link2');
			}
		}
	}

	// Set up Feeds
	Ricochet.FeedManager.init();

	// Show/Hide Counts
	$('.count').each(function() {
		var count=$(this);
		if (parseInt(count.text())>0) count.parent().show();
	});
	
	// Update the user details for any inline New Content forms
	if (typeof UserType != 'undefined') {
		if (typeof UserImage != 'undefined' && UserImage != '') {
			$('.new-content-form').find('.imageblock img').attr('src','/'+UserImage);
		}
		if (UserType != 'guest' && UserType != 'visitor') {
			//if ($('.comments').length) $('.comments .quote-link').show();
			$('.quote-link, .flag-link').show();
			if (UserType=='contributor' || UserType=='editor') {
				$('.new-content-form').find('.member').removeClass('member').addClass('contributor');
			}
		} else {
			// Don't show any forms for posting content
			$('.new-content-form').hide();
		}
	}
	
	// Users with certain rights get to see certain hidden links
	if (typeof UserType != 'undefined' && UserType != 'guest' && UserType != 'visitor') {
		// TODO: Find a better way to discover these than by these
		// complex patterns.  They are necessary to avoid
		// over-selecting due to certain content items containing other
		// content items (Comments under Answers, for example... if not
		// careful, we might select their action links as well as ours).
		// Perhaps put the User ID on the action links item itself, too?
		var myActionLinks = $('div[author_id="' + UserId + '"] > div.ft .action-links, div.comment[author_id="' + UserId + '"] .action-links, div.answer[author_id="' + UserId + '"] .action-links');

		// A user may not "like" or "flag" their own content
		myActionLinks.find('.active-like').hide();    
		myActionLinks.find('.inactive-like').show();
		myActionLinks.find('.flag-link').hide();

		if (UserType == 'editor') {
			// Editors get to see *all* edit links, and other special editor-only features
			$('.edit-link').show();
			$('.editors').show();
		} else {
			// User Enable the current user to edit their own content
			myActionLinks.find('.edit-link').show();
		}
	}

	if (typeof RicochetComments != 'undefined') {
		Ricochet.Comments=RicochetComments;
	} else {
		Ricochet.Comments = [];
	}
	
	var searchText = $('#search_text').text() || 'Search Ricochet';
	$('#SearchText').val(searchText);
	$('#SearchText').focus(function() {
		if ($('#SearchText').val() == searchText) $('#SearchText').val('');
	});
	$('#SearchText').blur(function() {
		if ($('#SearchText').val() == '') $('#SearchText').val(searchText);
	});

	// Add quote to new comment form
        // TODO: Make this happen only if the user is allowed to comment!
	$('.quote-link a').click(function() {
		var node = $(this).parents('[node_id]'),
	            node_id = node.attr('node_id'),
	            text = $('.body', node).html() || $('.bd', node).html(),
		    author = node.find('.author').text(),
		    a = node.find('a.author'),
	            form = node.parent().parent().find('form.new-content-form'),
		    textBox=form.find('.oe-window textarea'),
		    textFieldName;
		if (textBox.length > 0) {
			textBox = textBox[0];
			textFieldName = textBox.getAttribute('id');
			if (textFieldName.indexOf('mobile-') == 0) {
				// Plain textarea (mobile version disables the editor)
//				textFieldName = textFieldName.replace('mobile-', '');
			        // TODO: Implement Quote for plain text field.  For now, just return.
			        return;
			} else {
				// Get the TinyMCE document
				var doc=$('#' + textBox.getAttribute('id') + '_ifr')[0];
				if (doc.contentDocument) {
					doc=doc.contentDocument;
				} else if ( doc.contentWindow ) {
					doc=doc.contentWindow.document;
				} else {
					doc=doc.document;
				}
			}
		}

		$.scrollTo(form, 750);
		var time = '';
		if ($('.time', node).text()) {
			time = $('.time', node).text();
			if (time.trim) {
				time = time.trim();
			}
		}
		
		time=' <sub class="time">' + time + '</sub>';
		
		if (text.trim) {
			text = text.trim();
		}
		
		var quoteHTML = '<div><table class="quote-table"><tr><td class="quote">'+ text + '</td></tr></table></div>',
			quote = $(quoteHTML),
			td=$('td:first',quote),
			authorLink=($('a.author',node).length) ?
						'<a href="' + $('a.author', node).attr('href') + '">' + $('a.author', node).html() + '</a>' :
						$('span.author', node).html();
		
		if ($(':first',td)[0]==$('p:first',td)[0]) {
			$($(':first',td)[0]).prepend(authorLink + ': ');
		} else {
			td.prepend('<p>'+authorLink+'</p>');
		}
		
		if ($('p:last',td).parent()[0]==td[0]) {
			$($('p:last',td)[0]).append(' &middot; ' + time);
		} else {
			td.append('<p>'+time+'</p>');
		}
		
		$('a', quote).each(function () {
			var a = $(this);
			a.attr('mce_href', a.attr('href'));
		});
		
		if (!$(node).find('.member').length) {
			td.removeClass('quote');
			td.addClass('contributor-quote');
		}
		
		quoteHTML = $(quote[0]).html();
		if (quoteHTML.trim) {
			quoteHTML = quoteHTML.trim();	
		}
		$(doc.body).append(quoteHTML);
	
		var p=doc.createElement('p');
		p.innerHTML='<br /><br />';
		doc.body.appendChild(p);

		moveCursorToEnd(tinymce.EditorManager.activeEditor.id);
	});

	// Button for contributors to start a new conversation with the content currently in the new comment box
	$('#newconversation').click(function(){
		// TODO: find a more robust selector?
		var textBox=$('.post-comment .oe-window textarea');
		var doc=$('#' + textBox.attr('id') + '_ifr')[0];
		if (doc.contentDocument) doc=doc.contentDocument;
		else if (doc.contentWindow) doc=doc.contentWindow.document;
		else doc=doc.document;
		var data=doc.body.innerHTML;
		if (data) {
			$.cookie('conversation',data,{ path: '/', expires: new Date().getTime()+10000});
		}
		document.getElementById('newconversation').submit();
	});

	// Search Highlighting
	var search=$('#search_text').text();
	if (search) {
		search=search.split(' ');
		for (var searchIndex=0,len=search.length;searchIndex<len;searchIndex++) {
			$('#search_results .post, #search_results .comment').each(function(){
				var _this=$(this),items;
				if (_this.hasClass('post')) items=_this.find('.author, .title, .bd');
				else items=_this.find('a.author, .title, .body');
				items.each(function(){
					var text=this.innerHTML,textSplit=text.split(new RegExp('\\b'+search[searchIndex]+'\\b','gi'));
					if (textSplit.length>1) {
						var i=0,len=textSplit.length-1,lastBegTag,lastEndTag,highlighted='',orig='',word;
						for (;i<len;i++) {
							lastBegTag=textSplit[i].lastIndexOf('<');
							lastEndTag=textSplit[i].lastIndexOf('>');
							word=text.substring(orig.length+textSplit[i].length,orig.length+textSplit[i].length+search[searchIndex].length);
							if (lastBegTag>lastEndTag) {
								orig=orig+textSplit[i]+word;
								highlighted=highlighted+textSplit[i]+word;
							} else {
								orig=orig+textSplit[i]+word;
								highlighted=highlighted+textSplit[i]+'<span class="search-highlight">'+word+'</span>';
							}
						}
						highlighted=highlighted+textSplit[i];
						this.innerHTML = highlighted;
					}
				});
			});
		}
	}

	/**
	 * Submit AJAX posts when users toggle privacy controls
	 */
	$('.privacy_select').click(function () {
		var sectionIds = [];
		var _this=this;
		var sections = $('.privacy_select:checked').each(function () { sectionIds[sectionIds.length]=$(this).attr('id').substr(8); });
		
		$(this).parent().addClass('loading');
		$.ajax({
			url: "/ricochet/updateprivacy",
			type: "POST",
			data: {'sections[]':sectionIds, 'format': 'json'},
			dataType: 'json',
			success: function(response) {
				$('.privacy_select').attr('checked',false);
				$(_this).parent().removeClass('loading');
				for(var i in response.sections) {
					$('#display_' + response.sections[i]).attr('checked',true);
				}
				$.setAjaxMessage('Your privacy option has been changed',Ricochet.AjaxMessage.OK);
			},
			error: function(response) {
				$(_this).parent().removeClass('loading');
				$.setAjaxMessage('Error updating privacy policy',Ricochet.AjaxMessage.ERROR);
			}
		});
		
		return false;
	});

	
	if (document.getElementById('editor-dialog')) {
		$("#editor-dialog").dialog({autoOpen:false})
		$("#editor-button").click(function(){
			$('#editor-dialog').dialog('open');
		});
	}
/*	if (document.getElementById('join-dialog')) {
		$("#join-dialog").dialog({autoOpen:false,width:'auto'});
		$('.follow-link a, a.follow-link').live('click',function() {
			$('#join-dialog').dialog('open');
		});
	}
*/	
	var welcomecookie = location.pathname.split('/');
	welcomecookie.shift();
	welcomecookie = 'ricochet-welcome-' + welcomecookie[0];
	if (!$.cookie(welcomecookie)) $('#welcome').slideDown().find('.close').click(function(){
		$.cookie(welcomecookie,'1',{expires:365});
		$('#welcome').slideUp();
	});
	Ricochet.Toggles.init();
	Ricochet.ConversationManager.init();
	Ricochet.CommentView.init();
	var path=window.location.pathname;
	if (path.match(/^\/feed(\/+\(page\)\/[0-9]*)?$/)) {
		Ricochet.SidebarView.render({
			title:'Conversations Feed',el:'#sb-feed',url:'/ricochet/feed/conversations'
		});
	} else if (path.match(/^\/(Users)|(Profile)/)) {
	    // None on the user profile
	} else {
		if($('#sb-feed').length > 0) {
			Ricochet.SidebarView.render({
				title:'Contributor Feed',el:'#sb-feed',url:'/ricochet/feed/contributors'
				//title:'Conversations Feed',el:'#sb-feed',url:'/ricochet/feed/conversations'
			        // NOTE: The Comment Feed loads VERY slowly the first time-- until cached!
				//title:'Comment Feed',el:'#sb-feed',url:'/ricochet/feed/comments'
				//title:'Member Feed',el:'#sb-feed',url:'/ricochet/feed/member-feed'
			});
		}
	}
    
/* TODO: Remove after we get rid of this particular approach to doing Facebook buttons (I think they are commented out already)
	// Insert Facebook "Recommend" iframes
	$('.fb-like').each( function() {
		var fb_html = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + $(this).attr('shareurl') + 
			      '&layout=button_count&show_faces=false&width=150&height=21&action=recommend" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>';
		$(this).html(fb_html);
	});
 */
});

Ricochet.FeedManager = function() {
	return {
		init: function(context) {
			if (context == null) {
				context = $("#content");
			}
		        // Set up the "Show more" links
        		context.find('.truncated').each(function() {
				var innerElem = $(this).find('.truncated-inner');
				var fullHeight = innerElem.height();
				var truncatedHeight = parseInt($(this).css('max-height'))||fullHeight;
				var parentElem = $(this).parent();
				if (fullHeight > truncatedHeight * 1.5) {
					parentElem.find('.show-more-gradient').css('display', 'block');
					parentElem.find('.show-more-link').css('display', 'block');
					var linkElem = parentElem.find('.show-more-link a');
					linkElem.attr('href', 'javascript:void(0)');
					linkElem.attr('onclick', 'return false;');
					linkElem.html('<span class="down-arrow"></span>Show more<span class="down-arrow"></span>');
				} else {
					$(this).removeClass('truncated');
					parentElem.find('.show-more-link').remove();
				}
			});
			context.find('.show-more-link').click(function() {
				var truncElem = $(this).closest('.bd').find('.truncated');
				var innerElem = $(truncElem).find('.truncated-inner');
				var fullHeight = innerElem.height();
				var currentHeight = parseInt(truncElem.css('max-height'))||fullHeight;
				truncElem.animate({'max-height': fullHeight}, fullHeight/2, function() {
					truncElem.removeClass('truncated');
					truncElem.css('max-height', 'none');
				});
				$(this).parent().find('.show-more-gradient').hide();
				$(this).hide();
			});
		}
	}
}();

Ricochet.CountManager = function() {
	return {
		textarea_wc : function(textarea) {
			var fieldId = $(textarea).attr('id').split('ContentObjectAttribute_data_text_').pop();
			var wordCount = $('#oe_word_count_' + fieldId);
			if (wordCount.length == 0) return;
			var form = $(textarea).parents('form')[0];
			var wordLimit = $(wordCount.parents('.word_limit')[0]);
			var limit = parseInt(wordLimit.attr('max')) || 200;
			var words = textarea.value.split(/\S\s+/);
			var count = words.length;
			wordCount.text( count );
			if( ! wordLimit.is('.overlimit') && count > limit) {
				wordLimit.addClass('overlimit');
				Ricochet.ConversationManager.disableposting(form);
			}
			if( wordLimit.is('.overlimit') && count <= limit) {
				wordLimit.removeClass('overlimit');
				Ricochet.ConversationManager.enableposting(form);
			}
		}
	}
}();

Ricochet.ConversationManager = function() {
	var timeout, shareEl,
	    contentBeingPosted=false,
	    wordLimitExceeded=false;
	var closepopup=function(){
		$('.pod-popup').hide('fast');
	};
	return {
		follow : function(id,el) {
			if (document.getElementById('join-dialog')) {
			        // The user is not logged in.  Show a Join dialog instead
// I tested for mobile before, because of a width problem causing the mobile layout to be too wide.  Now it doesn't appear to be necessary
//				if ( jQuery.browser.mobile ) {
//					$("#join-dialog").dialog({autoOpen:false, modal:true, width:'300', position:[10, 30]});
//				} else {
					$("#join-dialog").dialog({autoOpen:false, modal:true, width:'auto'});
//				}
				$('#join-dialog').dialog('open');
			} else {
			        // Grab the parent post or comment.  Find out if we're following already
				var con=$(el).parents('.post, .comment'),
			            unfollow=con.find('.follow-link').is('.link2');

				// Because we want the UI to be snappy, we can't wait for the server to respond, saying
				// that the follow was successful.  Instead, we go ahead and update the UI as if it
				// succeeded; then actually try, and if it fails, put everything back the way it was.
				var count=parseInt(con.find('.follow-link .count:first').text());
				if (isNaN(count) || count < 1) count = 0;
/* The count on the My Conversations tab is no longer being used, but this is how it was implemented:
				var totalCountEl=$('#myconversations_count b'),
				    totalCountCon=$('#myconversations_count'),
				    totalCount=parseInt(totalCountEl.text()||0);
   See also the lines commented out below that refer to totalCountEl and totalCountCon
*/
				if (unfollow) {
					con.find('.follow-link').removeClass('link2');
					con.find('.follow-link .count').html(count-1);
					if (count-1==0) con.find('.follow-link').addClass('hide');
//					totalCountEl.text(totalCount-1);
//					if (totalCount-1==0) totalCountCon.addClass('hide');
				} else {
					con.find('.follow-link').removeClass('hide');
					con.find('.follow-link').addClass('link2');
					con.find('.follow-link .count').html(count+1);
//					totalCountEl.text(totalCount+1);
//					totalCountCon.removeClass('hide');
				}
				$.post('/ricochet/follow', {'node':id, 'remove':unfollow, 'format':'json'}, function(response, txtstat, xmlstat) {
					if (!response.success) {
					        // Update failed.  Must revert the UI to what it was before
						if (unfollow) {
							con.find('.follow-link').removeClass('hide');
							con.find('.follow-link').addClass('link2');
							con.find('.follow-link .count').html(count+1);
//							totalCountEl.text(totalCount+1);
//							totalCountCon.removeClass('hide');
						} else {
							con.find('.follow-link').removeClass('link2');
							con.find('.follow-link .count').html(count-1);
							if (count-1==0) con.find('.follow-link').addClass('hide');
//							totalCountEl.text(totalCount-1);
//							if (totalCount-1==0) totalCountCon.addClass('hide');
						}
						alert('Error occurred while updating follows (1)');
					}
				}, 'json');
			}
		},

		share : function(id,type,el) {
			$.post('/ricochet/share', {'node':id, 'type':type, 'format':'json'}, function(response) {
				if (response.success) {
					el=$(el).parent();
					var count=parseInt($(el).find('.count').text());
					$(el).find('.count').html(count+1);
					$(el).addClass('show');
				} else {
					alert('Error occurred while updating shares');
				}
			}, 'json');
		},

		// Submits an inline "new content" form to the server, and handles the response
		// If 'preview' is true, does a preview instead
	        // TODO: Use an approach similar to the preview to edit things in-place!
	        //       Have the "Edit" link put in place an edit box, then when submitted, have it get the content back and display it
		newcontent: function(form, preview) {
			if (contentBeingPosted==true) return;

			// Make sure we are within the word limit
			wordLimitExceeded = false;
			form.find('.word_limit').each(function() {
				var count = parseInt($(this).find('span').text()),
				    limit = parseInt($(this).attr('max')) || 200;
				if (count > limit) {
					alert('Please stay within the word limit.  You are using ' + count + ' of an allowed ' + limit + ' words.');
					wordLimitExceeded=true;
				}
			});

			if (wordLimitExceeded==true) return;
			contentBeingPosted=true;

			// For now, we only know how to handle one XML block textarea on the form
			var textBox=form.find('.oe-window textarea');
			var textFieldName;
			var text, plaintext;
			if (textBox.length > 0) {
				textBox = textBox[0];
				textFieldName = textBox.getAttribute('id');
				if (textFieldName.indexOf('mobile-') == 0) {
					// Get the text from the textbox (mobile version disables the editor)
					plaintext = text = textBox.value;
				        // TODO: This would be a good place to replace double newlines in the 'text' variable with <p> tags or something...
					textFieldName = textFieldName.replace('mobile-', '');
				} else {
					// Get the text from TinyMCE
					var doc=$('#' + textBox.getAttribute('id') + '_ifr')[0];
					doc=doc.contentWindow||doc.contentDocument;
					plaintext = $(doc.document.body).text();
// TODO: Is the following line going to work when there is more than one editor on the page?
					text = tinymce.EditorManager.activeEditor.getContent();
				}
			}
			if (plaintext.replace(/\s/g,'')=='') {
				alert('The text field looks empty.  Please type something before posting.');
				contentBeingPosted=false;
				return false;
			} else if(preview !== true) {
				// Submit the form.  The server will redirect, causing a page load
				// TODO: Consider using AJAX and updating the page, adding the content in-place as with Preview below?
				//       But we have to consider what page we are on...
				form.submit();
			} else {
				// Previewing only.  Load the data from the form and submit it via AJAX.
				var data={};
				for(var i=0; i<form[0].elements.length; i++) {
					data[form[0].elements[i].name]=form[0].elements[i].value;
				}
				data[textFieldName] = text;
				data['Preview']=true;

				// Prepare the preview area
				var className = data['Class'];
				var parentNodeId = data['ParentNodeId'];
				var container = $('#preview-' + parentNodeId);
				if (!container.length) {
					// Get the parent of all the content objects in the list, and add a preview element
					container = $('#' + className + '-list-' + parentNodeId)
					container.append('<div class="inline-content-preview" id="preview-' + parentNodeId + '"><h1>Preview</h1></div>');
					container = container.find('#preview-' + parentNodeId);
				}
				if (container.hasClass('loading') ) return;
				container.children('div').slideUp(500);
				container.addClass('loading');

				// Submit to server as a draft
				$.ajax({
					url: "/layout/set/json/ricochet/newcontent",
					type: "POST",
					data: data,
					cache: false,
					dataType: 'xml',
					success: function(response) {
						$(response).find('node').each(function(){
							container.children('div').remove();
							container.append('<div style="display:none;">' + $(this).text() + '</div>');
							container.children('div').slideDown(500);
						});
						container.removeClass('loading');
					},
					error: function(response) {
						container.removeClass('loading');
						alert('Error Creating Preview');
					}
				});
		
				contentBeingPosted=false;
				return false;
			}
		},
	
		disableposting: function(form) {
			$(form).find('.post-buttons').hide();
			$(form).find('.disabled-post-buttons').show();
		},

		enableposting: function(form) {
			$(form).find('.disabled-post-buttons').hide();
			$(form).find('.post-buttons').show();
		},

		init : function() {
			var _this=this;
			// Setup Comment Counter Popups
			$('.pod-popup a').live('click',closepopup);
			$('.pod-popup').hover(function(){
				clearTimeout(timeout);
			},function(){
				timeout=setTimeout(closepopup,3000);
			});
			$('.comment-count').hover(function(){
				clearTimeout(timeout);
				var pos=$(this).position(),sel=($(this).hasClass('member'))?'.pod-popup.member': ($(this).hasClass('follow')) ? '.pod-popup.follow' : '.pod-popup.contributor';
				$('.pod-popup').hide();
				$(this).parents('.post').find(sel).css({left:pos.left+$(this).outerWidth()-10,top:pos.top-25}).show('fast');
			},function(){
				clearTimeout(timeout);
				timeout=setTimeout(closepopup,3000);
			});
			// Setup Share Popup.  NOTE: Please keep this code in sync with action.tpl and comment.tpl, especially with regards
                        // to the DOM structure that this code relies upon to grab the elements it needs
			$('.share_button').live('click',function(){
				shareEl=this;
				var l=location,
					type=$(shareEl).parents().is('.post')?'post':'comment',
					parent=$(shareEl).parents('.'+type),
					url=l.protocol + '//' + l.host + parent.find('.permalink').attr('href') || l.pathname,
					author=parent.find('a.author').text(),
					title=author + ': ' +
						  $.trim((type=='post') ? parent.find('.hd .title').text() : parent.find('.hd h3').text()),
					desc='on Ricochet.com';
				clearTimeout(timeout);
				$('.pod-popup').hide();
				$('#share').css({left:$(this).offset().left-5,top:$(this).offset().top+$(this).outerHeight()}).show('fast');
			});
			$('.share_button').live('mouseout',function(){
				timeout=setTimeout(closepopup,3000);
			});
		}
	}
}();
Ricochet.UserManager = function(){
	return {
		follow : function(id,el) {
			var remove;
			if (!el) {
				// User icons, element aren't passed in
				el=$('a[person='+id+']');
				remove=true;
			} else {
				// Sidebar button
				if ($(el).hasClass('follow-link')) remove=false;
				else remove=true;
			}
			$.post('/ricochet/follow', {'node':id, 'remove':remove, 'format':'json'}, function(response) {
				var totalCountEl=$('#mypeople_count b'),
					totalCountCon=$('#mypeople_count');
				if (response.success) {
					var totalCount=parseInt(totalCountEl.text()||0);
					if (remove){
						$(el).addClass('follow-link');
						totalCountEl.text(totalCount-1);
						if (totalCount-1==0) totalCountCon.addClass('hide');
					} else {
						$(el).removeClass('follow-link');
						totalCountEl.text(totalCount+1);
						totalCountCon.removeClass('hide');
					}
				} else {
					alert('Error occurred while updating follows (2)');
				}
			}, 'json');
		}
	}
}();
Ricochet.Toggles=function(){
	var hideCls='hide',hideCls2='link2',popup,toggles={'users':{}},hideContributors=false,hideMembers=false,
		ids=['#member-toggles','#contributor-toggles','#popularity-toggles'],
		allNoneTpl=$.template('<div class="all-none">show: <a href="javascript:Ricochet.Toggles.showAllOrNone(1,${isMember});void(0);">all</a> / '+ 
					'<a href="javascript:Ricochet.Toggles.showAllOrNone(0,${isMember});void(0);">none</a></div>'),
		linkTpl=$.template('<a href="javascript:void(0)" onclick="Ricochet.Toggles.${method}(\'${id}\')" toggle="${toggle}">${name}</a> (<span class="count">${count}</span>)'),
		authorLookup=[],
		minimizedClicks={};
	var updatePopup=function(el){
		var s='',s2;
		if ($(el).hasClass(hideCls)) s="show";
		else s='hide';
		s=s+' comments';
		s2='like this';
		$(el).parent('#contributor-toggles,#member-toggles').each(function(){
			s2='by this person';
		});
		s=s+' '+s2;
		$('#toggles-popup span').html(s);
	};
	var updateTotals=function(){
		var count=0,comment,likes;
		for (var i=0,len=Ricochet.Comments.length;i<len;i++) {
			comment=Ricochet.Comments[i];
			if (!toggles['users'][comment.author]) {
				likes=comment.likes;
				if ( ((!toggles['like0']||(toggles['like0'] && likes>4))
				   &&(!toggles['like5']||(toggles['like5'] && (likes<5 || likes>9)))
				   &&(!toggles['like10']||(toggles['like10'] && likes<10)))) {
					count++;
				}
			}
		}
		for (var i in minimizedClicks) {
			if (minimizedClicks[i]) count++;
		}
		$('#filterCount').html('(displaying '+count+' of '+len+')');
		$('.filterCount').each(function(){
			$(this).html('('+count+' of '+len+')');
		});
	};
	var render=function(){
		var contribAuthors=[],memberAuthors=[],allAuthors=[],container,overflow=10;
		$(ids[0]+','+ids[1]+','+ids[2]).html('');
		$(ids[0]).append(allNoneTpl,{isMember:1});
		$(ids[1]).append(allNoneTpl,{isMember:0});
		for (var i=0,len=Ricochet.CommentAuthors.length;i<len;i++) {
			allAuthors[allAuthors.length]=Ricochet.CommentAuthors[i];
			if (Ricochet.CommentAuthors[i].member) memberAuthors[memberAuthors.length]=Ricochet.CommentAuthors[i];
			else contribAuthors[contribAuthors.length]=Ricochet.CommentAuthors[i];
		}
		container=$(ids[1]);
		for (var i=0,len=contribAuthors.length;i<len;i++) {
			var a=contribAuthors[i],
				obj={method:'showHideUser',id:a.id,toggle:a.id,name:a.name,count:a.comments.length||0};
			if (i==overflow) {
				container=container.append('<a href="javascript:void(0)" class="display-more">...plus '+
										   (len-overflow)+
										   ' others</a><div class="toggle-overflow"></div>').find('.toggle-overflow');
			}
			container.append(linkTpl,obj);
			if (i+1<len) container.append('<br />');
		}
		container=$(ids[0]);
		var popularityToggles=[
	 				 		  {id:10,name:'10+ Likes',count:0},
	 				 		  {id:5,name:'5-10 Likes',count:0},
					 		  {id:0,name:'0-5 Likes',count:0}
					 		];
		for (var i=0,len=memberAuthors.length;i<len;i++) {
			var a=memberAuthors[i],
				obj={method:'showHideUser',id:a.id,toggle:a.id,name:a.name,count:a.comments.length||0};
			if (i==overflow) {
				container=container.append('<a href="javascript:void(0)" class="display-more">...plus '+(len-overflow)+' other'+((len-overflow==1)?'':'s')+'</a><div class="toggle-overflow"></div>').find('.toggle-overflow');
			}
			container.append(linkTpl,obj);
		   
			for (var j=0,len2=a.comments.length;j<len2;j++) {
				var count=Ricochet.Comments[a.comments[j]].likes;
				if (count<5) popularityToggles[2].count++;
				else if (count>4 && count<10) popularityToggles[1].count++;
				else if (count>9) popularityToggles[0].count++;
			}
			if (i+1<len) container.append('<br />');
		}
		container=$(ids[2]);
		for (var i=0,len=popularityToggles.length;i<len;i++) {
			var a=popularityToggles[i],
				obj={method:'showHideLikes',id:a.id,toggle:a.id,name:a.name,count:a.count};
			container.append(linkTpl,obj);
			if (i+1<len) container.append('<br />');
		}

		// Add mouseover to toggle links
		$('#toggles .box a:not(.display-more, .all-none a)').hover(function(){
			var pos=$(this).position();
			pos.left=pos.left+$(this).outerWidth()+10;
			pos.top=pos.top-10;
			$('#toggles-popup').css({'left':pos.left,'top':pos.top}).show();
			updatePopup(this);
		},function(){
			$('#toggles-popup').hide();
		});
		$('.display-more').click(function(){
			// Hide the link and show the overflow div
			$(this).hide().parents(ids[0]+','+ids[1]).find('.toggle-overflow').show();
		});
		$('.hide-more').click(function(){
			var parents=$(this).parents(ids[0]+','+ids[1]);
			parents.find('.toggle-overflow').hide();
			parent.find('.display-more').show();
		});
		setTimeout(function(){$('#toggles').slideDown('slow');},1000);
	};
	return {
		showAllOrNone:function(showAll,isMember) {
			var author;
			for (var i=0,len=Ricochet.CommentAuthors.length;i<len;i++) {
				author=Ricochet.CommentAuthors[i];
				if ((isMember && author.member) || (!isMember && !author.member)) {
					toggles['users'][author.id]=(showAll)?true:false;
					this.showHideUser(author.id);
				}
			}
		},
		showHideUser:function(id,showUser) {
			if (typeof showUser!='undefined') toggles['users'][id]=showUser;
			var author=Ricochet.CommentAuthors[authorLookup[id]],
				comments=author.comments,
				el=$(ids[0]+' a[toggle='+id+'], '+ids[1]+' a[toggle='+id+']'),
				show=toggles['users'][id];
			toggles['users'][id]=show?false:true;
			for(var i=0,len=comments.length;i<len;i++) {
				if (show) {
					// Determine if it still should be hidden
					var stillShow=true;
					if (author.member) {
						var likes=Ricochet.Comments[comments[i]].likes;
						if (toggles['like0'] && likes<5) stillShow=false;
						if (toggles['like5'] && likes>4 && likes<10) stillShow=false;
						if (toggles['like10'] && likes>9) stillShow=false;
					}
					if (stillShow) {
						Ricochet.CommentView.show(Ricochet.Comments[comments[i]].id);
						minimizedClicks[Ricochet.Comments[comments[i]].id]=false;
					}
				} else {
					Ricochet.CommentView.minimize(Ricochet.Comments[comments[i]].id);
					minimizedClicks[Ricochet.Comments[comments[i]].id]=false;
				}
			}
			if (el) {
				if (show) $(el).removeClass(hideCls).removeClass(hideCls2);
				else $(el).addClass(hideCls).addClass(hideCls2);
				updatePopup(el);
			}
			$.setJSONCookie('toggles',toggles);
			updateTotals();
		},
		showHideLikes:function(id) {
			var comments=[],show=toggles['like'+id],
				el=$(ids[2]+' a[toggle='+id+']');
			toggles['like'+id]=show?false:true;
			for (var i=0,len=Ricochet.Comments.length;i<len;i++) {
				var comment=Ricochet.Comments[i];
					if (id==0 && comment.likes<5) comments[comments.length]=i;
					else if (id==5 && comment.likes>4 && comment.likes<10) comments[comments.length]=i;
					else if (id==10 && comment.likes>9) comments[comments.length]=i;
			}
			if (show) {
				for (var i=0,len=comments.length;i<len;i++) {
					var stillShow=true;
					if (toggles['users'][Ricochet.Comments[comments[i]].author]) stillShow=false;
					if (stillShow) Ricochet.CommentView.show(Ricochet.Comments[comments[i]].id);
					minimizedClicks[Ricochet.Comments[comments[i]].id]=false;
				}
			} else {
				for (var i=0,len=comments.length;i<len;i++) {
					Ricochet.CommentView.minimize(Ricochet.Comments[comments[i]].id);
					minimizedClicks[Ricochet.Comments[comments[i]].id]=false;
				}
			}
			if (el) {
				if (show) $(el).removeClass(hideCls).removeClass(hideCls2);
				else $(el).addClass(hideCls).addClass(hideCls2);
				updatePopup(el);
			}
			$.setJSONCookie('toggles',toggles);
			updateTotals();
		},
		init:function(){
			if (typeof RicochetComments!='undefined') Ricochet.Comments=RicochetComments;
			if (!$('.comments').length) return;
			var tmpAuthors={},comment;
			for (var i=0,len=Ricochet.Comments.length;i<len;i++) {
				comment=Ricochet.Comments[i];
				if (!tmpAuthors[comment.author]) {
					tmpAuthors[comment.author]={id:comment.author,name:comment.authorName,member:comment.member};
				}
			}
			Ricochet.CommentAuthors=[];
			for (i in tmpAuthors) {
				Ricochet.CommentAuthors[Ricochet.CommentAuthors.length]=tmpAuthors[i];
			}
			if (!toggles['users']) toggles['users']={};
			// Build the author lookup table;
			for (var i=0,len=Ricochet.CommentAuthors.length;i<len;i++) {
				authorLookup[Ricochet.CommentAuthors[i].id]=i;
			}
			// Add comment lookup to author
			for (var i=0,len=Ricochet.Comments.length;i<len;i++) {
				if (Ricochet.Comments[i].author) {
					comment=Ricochet.Comments[i],author=Ricochet.CommentAuthors[authorLookup[comment.author]];
					if (!author.comments) author.comments=[];
					author.comments[author.comments.length]=i;
				}
			}
			render();
			var tempToggles=$.getJSONCookie('toggles');
			for (var i in [0,5,10]) if (tempToggles['like'+i]) this.showHideLikes(i);
			for (i in tempToggles['users']) {
				if (tempToggles['users'][i] && Ricochet.CommentAuthors[authorLookup[i]]) this.showHideUser(i);
			}
			$('.minimized a').live('click',function(){
				var id=$(this).parents('.comment').attr('comment');
				if (id) minimizedClicks[id]=true;
				updateTotals();
			});
			updateTotals();
		}
	}
}();
Ricochet.CommentView=function(){
	var selector="#content .comments .comment";
	var showHideLikes=function(context){
		if (typeof context == 'undefined' || context == null) {
		    context = $('html body');
		}
		// TODO: Accept a parameter to serve as context, to narrow down the number of elements to search?
		$('.like .count', context).not('.show-if-zero').each(function(){
			var count=parseInt($(this).text());
			if (count && count>0) {
				$(this).parent().show();
			} else {
				$(this).parent().hide();
			}
		});
	};
	return {
		hide:function(comment){
			if (typeof comment == 'number') $(selector+'[comment='+comment+']').hide();
			else $(comment).hide();
		},
		show:function(comment){
			if (typeof comment == 'number') comment=$(selector+'[comment='+comment+']');
			$(comment).show().children('.contributor,.member').show();
			$(comment).children('.minimized').hide();
		},
		minimize:function(comment){
			if (typeof comment == 'number') comment=$(selector+'[comment='+comment+']');
			$(comment).children('.contributor,.member').hide();
			$(comment).children('.minimized').show();
		},
		getAuthorComments:function(id){
			return $(selector+'[author='+id+']');
		},
		getContributors:function(){
			var comments=$(selector+'[contributor=true]');
			return comments;
		},
		getMembers:function(){
			var comments=$(selector+'[contributor=false]');
			return comments;
		},
		getLikes:function(count){
			var likes=[],commentCount,comments=$(selector),i=0,len=comments.length;
			for (;i<len;i++){
				commentCount=parseInt($(comments[i]).find('.like-count').text());
				// We didn't let users 'like' Contributor comments in the past, but have now allowed it
				// if ($(comments[i]).find('.contributor').length) continue;
				if (!count && (!commentCount||commentCount<5||commentCount<0)) likes[likes.length]=comments[i];
				else if (count==5 && commentCount<10 && commentCount>4) likes[likes.length]=comments[i];
				else if (count==10 && commentCount>9) likes[likes.length]=comments[i];
			}
			return likes;
		},
		like : function(id,el) {
			if (document.getElementById('join-dialog')) {
				// Must not be a Member.  Show the Join dialog
				$("#join-dialog").dialog({autoOpen:false,width:'auto'});
				$('#join-dialog').dialog('open');
			} else {
				var likeLink = $(el);
				if(likeLink.data('block')) return;
				var con = likeLink.parents('li').eq(0),
				    unlike = likeLink.hasClass('link2');
				likeLink.data('block',true); // block other threads
				// Strategy here is to go ahead and update the UI as if it succeeded;
				// then actually try, and if it fails, put everything back the way it was.
				var countEl = con.find('.count'),
				    count = parseInt(countEl.text());
				if (unlike) {
					likeLink.removeClass('link2');
					countEl.html(count > 0 ? count-1 : 0);
				} else {
					likeLink.addClass('link2');
					countEl.html(count+1);
				}
				$.post('/ricochet/like', {'node':id, 'remove':unlike, 'format':'json'}, function(response) {
					if (!response.success) {
						var count=parseInt(con.find('.count').text());
						if (!unlike) {
							likeLink.removeClass('link2');
							countEl.html(count-1);
						} else {
							likeLink.addClass('link2');
							countEl.html(count+1);
						}
						alert('Error occurred while updating likes');
					}
					likeLink.data('block',false);
					showHideLikes(con.parent());
				}, 'json');
			}
		},
		share : function(id,type,el) {
			$.post('/ricochet/share', {'node':id, 'type':type, 'format':'json'}, function(response) {
				if (response.success) {
					var count=parseInt($(el).find('.count').text());
					$(el).find('.count').html(count+1);
				} else {
					alert('Error occurred while updating shares');
				}
			}, 'json');
		},
		init:function(){
			showHideLikes();
		}
	}
}();

Ricochet.SidebarView=function(){
	var el,url
		tpl=$.template('<h2 style="margin-bottom:0;">${title}</h2><div class="con"></div>'+
			'<div class="scroll"><div class="scroll-down"></div><div class="scroll-up"></div></div>');
	var loadCallback=function(data,status){
		var con=el.find('.con');
		con.html('');
		if (status=='success'){
			$(data.responseXML).find('node').each(function(){
				var s=$(this).text();
				con.append(s);
			});
		}
		$('#sb .video').each(function(){
			var _this=$(this),
				node=_this.parents('.post, .comment'),
				href=node.find('.hd .title').attr('href');
			_this.parent().attr('href',href);
		});
		Ricochet.FeedManager.init($('#sb'));
		/* I think this is obsolete-- was necessary when we used to have /layout/set/json
		   in the urls because of the way we loaded the sidebar
		$('td.quote a').each(function(){
			if($(this).attr('href').indexOf('/layout/set/json') >= 0)
			{
				$(this).attr('href', $(this).attr('href').replace('/layout/set/json',''));
			}
		});
		 */

	};
	$('.scroll-down').live('click',function(){
		$('.sb-view .con').scrollTo({top:'+=250px',left:0},500);
	});
	$('.scroll-up').live('click',function(){
		$('.sb-view .con').scrollTo({top:'-=250px',left:0},500);
	});
	return {
		render:function(opt){
			el=$(opt.el);
			el.addClass('sb-view').append(tpl,opt);
			url=opt.url;
			this.load();

			// TODO: We need to get the initialization code (the
			// one that sets up all the "Like" and "Edit" links and
			// so on) into a function that we can call and pass in
			// a context.  Then on document load, it can be run on
			// the document, and on sidebar load, it can be run on
			// the sidebar.  Currently, some of that JavaScript
			// code does not get applied to the sidebar.

		},
		load:function(){
			var con=el.find('.con');
			con.html('');
			con.append('<div class="sb-view-loader"></div>');
			con.find('.sb-view-loader').height(con.height()).width(con.width());
			$.ajax({type:'GET',url:url,complete:loadCallback});
		}
	};
}();
/**
 * AjaxMessage singleton for displaying messages
 */
Ricochet.AjaxMessage=function(){
	var timeout;
	jQuery('#ajaxMessage .close').live('click',function(){
		Ricochet.AjaxMessage.hideAjaxMessage();
		return false;
	});
	return {
		OK:1,WARNING:2,ERROR:3, // Constants
		setAjaxMessage:function (message, clsType) {
			// Determine css class
			var cls=(clsType==this.ERROR)?'error':(clsType==this.WARNING)?'warning':'feedback',
				msgEl=jQuery('#ajaxMessage');
			jQuery('#ajaxMessage .message').html(message);
			if (msgEl.css('display') == 'none') {
				msgEl.addClass(cls).slideDown('fast');
			} else {
				msgEl.addClass(cls).effect('highlight', {}, 1000);
			}
			clearTimeout(timeout);
			timeout=setTimeout(this.hideAjaxMessage, 10000);
		},
		hideAjaxMessage:function(){
			clearTimeout(timeout);
			jQuery('#ajaxMessage').slideUp('fast');
		}
	}
}();
// Jquery helper methods for AjaxMessage
jQuery.extend({
	setAjaxMessage:function(msg,type){Ricochet.AjaxMessage.setAjaxMessage(msg,type);},
	hideAjaxMessage:function(){Ricochet.AjaxMessage.hideAjaxMessage();}
});
// Set cursor for tinymce
function moveCursorToEnd(editor_id) {
	tinyMCE.execInstanceCommand(editor_id,"selectall", false, null);
	ed = tinyMCE.get(editor_id);
	ed.selection.collapse(false);
}

