var addthis_config = {
	username:'ricochetdotcom'
};
var addthis_share = {
	templates: { twitter: '{{title}} on Ricochet.com: {{url}}'}
};

Ricochet={};
$(document).ready(function(){

	// Init the lightbox plugin on images with lightbox class
	//$('a.lightbox').lightBox();
	//http://ricochet.local/extension/ricochet/design/ezwebin/images/lightbox/lightbox-btn-close.gif
	// $('a[@rel*=lightbox]').lightBox({
	// $('a[@rel*=lightbox]').lightBox({
	$('a.lightbox').lightBox({
		imageLoading: '/extension/ricochet/design/ezwebin/images/ajax-loader.gif',
		imageBtnClose: '/extension/ricochet/design/ezwebin/images/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '/extension/ricochet/design/ezwebin/images/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/extension/ricochet/design/ezwebin/images/lightbox/lightbox-btn-next.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');
			}
		}
	}

	// Show/Hide Counts
	$('.count').each(function() {
		var count=$(this);
		if (parseInt(count.text())>0) count.parent().show();
	});
	
	// Update the user details for the Comment area on Conversation pages
	if (typeof UserType != 'undefined') {
		if (UserImage != '') {
			$('#newcomment').find('.imageblock img').attr('src','/'+UserImage);
		}
		if (UserType != 'guest') {
			//if ($('.comments').length) $('.comments .quote-li').show();
			$('.quote-li').show();
			if (UserType=='contributor' || UserType=='editor') {
				$('#newcomment').find('.member').removeClass('member').addClass('contributor');
			}
		} else {
			$('#post-comment').hide();
		}
	}
	
	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
	$('.quote-link').click(function() {
		$.scrollTo('#newcomment',750);
		var node=$(this).parents('.post, .comment'),
			text=$('.body', node).html() || $('.bd', node).html(),
			author=node.find('.author').text(),
			id=node.attr('post')||node.attr('comment'),a=node.find('a.author'),
			doc=$('#comment_ifr')[0];
	
		if (doc.contentDocument) {
			doc=doc.contentDocument;
		} else if ( doc.contentWindow ) {
			doc=doc.contentWindow.document;
		} else {
			doc=doc.document;
		}
		
		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);
	});

	// Add comment to new conversation
	$('#newconversation').click(function(){
		var doc=$('#comment_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();
	});

	// UserEmail set in header template.
	$('.addthis_button_email').mouseout(function(){
		$('#at_from').val((typeof UserEmail != 'undefined')?UserEmail:'');
	});

	// 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;
					}
				});
			});
		}
	}

	$('#preview_comment').click(function () {
		if (parseInt($('oe_word_count').text)>200) {
			alert('Please correct word count error before previewing');
			return;
		}
		var con=$('#comment_preview');
		if (!con.length) {
			$('.comments').append('<div id="comment_preview"></div>');
			con=$('#comment_preview');
			$('#comment_preview').html('<h1>Preview</h1>');
		}
		if ($('#comment_preview').hasClass('load')) return;
		$('#comment_preview_con').slideUp(500);
		con.addClass('loading');
		var form=$('#newcomment')[0];
		var data={};
		for(var i=0; i<form.elements.length; i++) {
			data[form.elements[i].name]=form.elements[i].value;
		}
		data['comment']=tinymce.EditorManager.activeEditor.getContent();
		data['Preview']=true;
		$.ajax({
			url: "/layout/set/json/ricochet/comment",
			type: "POST",
			data: data,
			dataType: 'xml',
			success: function(response) {
				$(response).find('node').each(function(){
					var s=$(this).text();
					$('#comment_preview_con').remove();
					con.append('<div id="comment_preview_con" style="display:none;">'+s+'</div>');
					$('#comment_preview_con').slideDown(500);
				});
				con.removeClass('loading');
			},
			error: function(response) {
				con.removeClass('loading');
				alert('Error Creating Preview');
			}
		});
		
		return false;
	});
	
	/**
	 * 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('follow-dialog')) {
		$("#follow-dialog").dialog({autoOpen:false,width:'auto'});
		$('.follow-link a, a.follow-link').live('click',function() {
			$('#follow-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:'Top Conversations',el:'#sb-feed',url:'/layout/set/json/content/view/json/76'
		});
	} else if (path.match(/^\/(Users)|(Profile)/)) {
	} else {
		if($('#sb-feed').length > 0)
		{
		Ricochet.SidebarView.render({
			title:'Contributor Feed',el:'#sb-feed',url:'/layout/set/json/content/view/json/2'
		});
		}
	}
    
    //Insert facebook like iframes. <iframe src="http://www.facebook.com/plugins/like.php?href=http://ricochet.com/conversations/The-United-States-Treasury-is-Running-Out-of-Suckers&amp;layout=button_count&amp;show_faces=false&amp;width=150&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>
    $('.fb-like').each( function(){
            var fb_html = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + 
                           $(this).attr('ezuri') + 
                           '&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.ConversationManager = function() {
	var timeout,shareEl,commentBeingPosted=false,closepopup=function(){
		$('.pod-popup').hide('fast');
	};
	return {
		follow : function(id,el) {
			var con=$(el).parents('.post, .comment'),remove=$(con).find('.follow-link').hasClass('link2');

			var count=parseInt($(con).find('.follow-link .count:first').text()),
			totalCountEl=$('#myconversations_count b'),
			totalCountCon=$('#myconversations_count'),
			totalCount=parseInt(totalCountEl.text()||0);
			if (remove) {
				$(con).find('.follow-link,.pod-follow').removeClass('link2');
				$(con).find('.follow-link .count').html(count-1);
				if (count-1==0) $(con).find('.follow-link,.pod-follow').addClass('hide');
				totalCountEl.text(totalCount-1);
				if (totalCount-1==0) totalCountCon.addClass('hide');
			} else {
				$(con).find('.follow-link,.pod-follow').removeClass('hide');
				$(con).find('.follow-link,.pod-follow').addClass('link2');
				$(con).find('.follow-link .count').html(count+1);
				totalCountEl.text(totalCount+1);
				totalCountCon.removeClass('hide');
			}
			$.post('/ricochet/follow', {'node':id, 'remove':remove, 'format':'json'}, function(response, txtstat, xmlstat) {
				if (!response.success) {
					if (!remove) {
						$(con).find('.follow-link,.pod-follow').removeClass('link2');
						$(con).find('.follow-link .count').html(count-1);
						if (count-1==0) $(con).find('.follow-link,.pod-follow').addClass('hide');
						totalCountEl.text(totalCount-1);
						if (totalCount-1==0) totalCountCon.addClass('hide');
					} else {
						$(con).find('.follow-link,.pod-follow').removeClass('hide');
						$(con).find('.follow-link,.pod-follow').addClass('link2');
						$(con).find('.follow-link .count').html(count+1);
						totalCountEl.text(totalCount+1);
						totalCountCon.removeClass('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');
		},
		newcomment:function(){
			if (commentBeingPosted==true) return;
			if (parseInt($('oe_word_count').text)>200) {
				alert('Please correct word count error before publishing');
				return;
			}
			commentBeingPosted=true;
			var doc=$('#comment_ifr')[0];
			doc=doc.contentWindow||doc.contentDocument;
			var text=$(doc.document.body).text();
			if ($(doc.document.body).text().replace(/\s/g,'')=='') return;
			document.getElementById('newcomment').submit();
		}, 
		newmobilecomment:function(){
			if (commentBeingPosted==true) return;
			commentBeingPosted=true;
			var $text=$('#mobile-comment')[0].value;

			if ($text.replace(/\s/g,'')=='')
			{
				return;
			}
			document.getElementById('newcomment').submit();
		},
		disableposting:function(){
			$('#postCommentButtons').hide();
			$('#disabledPostCommentButtons').show();
		},
		enableposting:function(){
			$('#disabledPostCommentButtons').hide();
			$('#postCommentButtons').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
			$('.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 + 
						((type=='post') ? parent.find('.hd .title').attr('href') || l.pathname : parent.find('.comment-jump a').attr('href')),
					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';
				$('#share .addthis_toolbox').attr({'addthis:url':url,'addthis:title':title,'addthis:description':desc});
				ReinitializeAddThis();
				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);
			});
			$('.addthis_toolbox a').click(function(){
				var el=(shareEl)?shareEl:this;
				var type=$(el).parents().is('.post')?'post':'comment';
				var id=$(el).parents('.'+type).attr(type);
				type=$(this).attr('title');
				_this.share(id,type,el);
			});
			
		}
	}
}();
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=allAuthors.length;i<len;i++) {
			var a=allAuthors[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(){
		$('.like .count').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($(el).data('block')) return;
			var con=$(el).parent(),remove=$(el).hasClass('link2');
			$(el).data('block',true);
			var count=parseInt($(con).find('.count').text());
			if (remove) {
				$(el).removeClass('link2');
				$(con).find('.count').html(count-1);
			} else {
				$(el).addClass('link2');
				$(con).find('.count').html(count+1);
			}
			$.post('/ricochet/like', {'node':id, 'remove':remove, 'format':'json'}, function(response) {
				if (!response.success) {
					var count=parseInt($(con).find('.count').text());
					if (!remove) {
						$(el).removeClass('link2');
						$(con).find('.count').html(count-1);
					} else {
						$(el).addClass('link2');
						$(con).find('.count').html(count+1);
					}
					alert('Error occurred while updating likes');
				}
				$(el).data('block',false);
				showHideLikes();
			 }, '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('<div class="sb-view-hd"><h2>${title}</h2></div><div class="hr clear"></div><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);
		});
		$('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();
		},
		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,cache:false});
		}
	};
}();
/**
 * 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();}
});
function ReinitializeAddThis(){
	if (window.addthis){
	   window.addthis.ost = 0;
	   window.addthis.ready();
	}
 }
// Set cursor for tinymce
function moveCursorToEnd(editor_id) {
	tinyMCE.execInstanceCommand(editor_id,"selectall", false, null);
	ed = tinyMCE.get(editor_id);
	ed.selection.collapse(false);
}
