 /**
 * @author swannc
 * 1.1.1 fixes duplication bug
 * 1.2.0 adds report violation and paused indicator
 */

var ccmb_populate_queue = function(obj){}
var ccmb_populate_popular_conversations = function(obj){}
var ccmb_populate_popular_blog_comments = function(obj){}
var ccmb_populate_popular_message_board = function(obj){}
var ccmb_change_data_src = function(cat_list, count){}

var __espn_realtime__ = function()
{	
	var CCMB = Class.create();
	CCMB.prototype = {
		initialize: function()
		{
			this.options = this.construct_options();
			this.options.ccmb_include_images = true;
			var mapped_only = this.options.ccmb_cat == 'Conversations' ? 'true' : 'false';
			var cat_list = this.options.ccmb_cat == 'Conversations' ? 'Conversations^Blogs' : this.options.ccmb_cat;
			
			this.html = '';
			this.number_seen = 0;
			this.check_timer = null;
			this.data_src = 'http://mb.espn.go.com/dir-app/acx/activeContent.aspx?mappedOnly=' + mapped_only + '&webtag=espnmb&type=messagelist&fmt=json&timeout=10&catList=' + cat_list + '&count=' + this.options.ccmb_show;
			this.popular_data_src = 'http://mb.espn.go.com/dir-app/acx/activeContent.aspx?webtag=espnmb&fmt=json&activityHours=' + this.options.ccmb_hours + '&count=25&timeout=10&mappedOnly=False';
			this.is_paused = false;
			this.hot_only = false;
			this.queue = [];
			this.message_board_only = false;
			this.id = 'ccmb_script';
			this.popular_id_conversations = 'ccmb_popular_script_conversations';
			this.popular_id_message_board = 'ccmb_popular_script_message_board';
			this.popular_id_blog_comments = 'ccmb_popular_script_blog_comments';
			this.className = "ccmb-odd";
			this.message_board_url_template = new Template('http://boards.espn.go.com/boards/mb/mb?rls=#{sport}&tid=#{tid}&lid=#{lid}');
			this.conversation_url_template = new Template('http://myespn.go.com/conversation/story?id=#{contentId}'); //if Discussion has contentId
			this.blog_url_template = new Template('#{url}'); //if contentId has true-hoop or blog then use content url
			this.game_package_url_template = new Template('#{url}'); //if contentId has true-hoop or blog then use content url
			this.popular = {};
			this.seen_items = {};
			this.checks_with_no_items = 0;
			this.store_in_buffer = this.options.ccmb_attach_point != null;
			this.is_cloud_open = this.options.ccmb_start_with_cloud_open;
			
			this.handle_filter_click = this.send_data_src.bindAsEventListener(this);
			this.handle_play_pause_click = this.change_play_pause.bindAsEventListener(this);
			this.handle_hot_click = this.change_hot_toggle.bindAsEventListener(this);
			this.handle_violation_click = this.toggle_violation_form.bindAsEventListener(this);
			this.handle_toggle_click = this.toggle_tag_cloud.bindAsEventListener(this);
			
			try{ this.populate_popular(ProsperoResponse_ccmb_popular_convesations); } catch(e){  }
			try{ this.populate_popular(ProsperoResponse_ccmb_popular_message_board); } catch(e){ }
			try{ this.populate_popular(ProsperoResponse_ccmb_popular_blog_comments); } catch(e){ }
			
			var data = this.load_data();
			var items = [];
			try{ var items = this.collect_items( data.ContentElement.Forum[0] ); }
			catch(e) { var items = []; }
			
			
			
			this.render(this.parse_data(items),items);
			
			if(!this.options.ccmb_search_type && !this.options.ccmb_search_text)
			{
				setTimeout( function(){ this.check_queue(); }.bind(this), this.options.ccmb_freq );
				setTimeout( function(){ this.fetch_popular('conversations'); }.bind(this), 60000*2 );
				setTimeout( function(){ this.fetch_popular('message_board'); }.bind(this), 60000*2 );
				setTimeout( function(){ this.fetch_popular('blog_comments'); }.bind(this), 60000*2 );
			}
			
			setInterval(function(){ this.seen_items = {}; }.bind(this), 20 * 60 * 1000); ///clear up some memory every 20 minutes
		},
		change_hot_toggle: function(evt)
		{
			$('ccmb-indicator').show();
			this.hot_only = Event.element(evt).value;
		},
		change_play_pause: function(evt)
		{
			var element = Event.element(evt);
			
			if(element.id == 'ccmb-pause')
			{
				this.pause_stream();
			}
			else
			{
				this.start_stream();
			}
			
			Event.stop(evt);
		},
		activate_violation_links: function(elem)
		{
			var nodes = elem ? $(elem).getElementsBySelector('.ccmb-violation') : $$('#ccmb a.ccmb-violation');
			
			nodes.each(function(node)
			{
				$(node).observe('click',this.handle_violation_click);
			}.bind(this));
		},
		apply_behaviors: function()
		{
			try{$("ccmb-play").observe('click',this.handle_play_pause_click);}catch(e){}
			try{$("ccmb-pause").observe('click',this.handle_play_pause_click);}catch(e){}
			["ccmb-all-filter","ccmb-conversation-filter","ccmb-message-board-filter","ccmb-blog-comment-filter"].each(function(id)
			{
				try{$(id).observe('click',this.handle_filter_click);}catch(e){}
			}.bind(this));
			try{ $("ccmb-hot-filter").observe('click',this.handle_hot_click);}catch(e){}
			try{ $("ccmb-toggle-tag-cloud").observe('click',this.handle_toggle_click);}catch(e){}
			this.activate_violation_links();
		},
		toggle_tag_cloud: function(evt)
		{
			$('ccmb-tag-cloud-container').toggle();
			
			if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
			{
				var child = $($('ccmb-root').firstChild);
				
				child.remove();
				$('ccmb-root').insertBefore(child,$('ccmb-root').firstChild);
			}
			
			if($('ccmb-toggle-tag-cloud').innerHTML.indexOf('Show') > -1)
			{
				$('ccmb-toggle-tag-cloud').update('Hide Conversation Cloud');
				this.is_cloud_open = false;
			}
			else
			{
				$('ccmb-toggle-tag-cloud').update('Show Conversation Cloud');
				this.is_cloud_open = false;
			}
			Event.stop(evt);
		},
		apply_filters: function()
		{
			//this.prune_queue_by_time();
			if(!this.options.ccmb_search_type) this.prune_queue_by_staleness();
			if(this.message_board_only) this.prune_queue_by_message_board_only();
			this.prune_queue_by_unique();
			if(this.hot_only) this.prune_queue_by_hottness();
			this.adjust_comment_count();
		},
		send_data_src: function(evt)
		{
			$('ccmb-indicator').show();
			if(Event.element(evt).value == 'general')
			{
				this.message_board_only = true;
				this.change_data_src('all');
			}
			else
			{
				this.message_board_only = false;
				this.change_data_src(Event.element(evt).value);
			}
		},
		prune_queue_by_message_board_only: function()
		{
			this.queue.each(function(item)
			{
				if( item['@contentId'] )
				{
					this.queue = this.queue.without(item);
				}
			}.bind(this));
		},
		change_data_src: function(cat_list,count)
		{
			clearTimeout(this.check_timer);
			cat_list = cat_list || this.options.ccmb_cat;
			count = count || this.options.ccmb_show;
			
			var mapped_only = this.options.ccmb_cat == 'Conversations' ? 'true' : 'false';
			
			cat_list = this.options.ccmb_cat == 'Conversations' ? 'Conversations^Blogs' : cat_list;
			
			this.timestamp = null;
			this.data_src = 'http://mb.espn.go.com/dir-app/acx/activeContent.aspx?mappedOnly=' + mapped_only + '&webtag=espnmb&type=messagelist&activityHours=' + this.options.ccmb_hours + '&fmt=json&timeout=1&catList=' + cat_list + '&count=' + count;
			this.emtpy_queue();
			this.check_queue();
		},
		dump_queue: function()
		{
			var item;
			while(item = this.queue.shift())
			{
				this.add_rows(item);
			}
		},
		toggle_violation_form: function(evt) 
		{
			var elem = $(Event.findElement(evt,'a'));
			var li = $(Event.findElement(evt,'li'));
			var params = elem.href.split('?')[1].toQueryParams();
			var rgb = li.getStyle('backgroundColor');
			var color = (rgb == 'transparent') ? 'ffffff' : rgb.parseColor().replace('#','');
			var iframe_url = 'http://mb.espn.go.com/n/pfx/forum.aspx?webtag=espnmb&folderId=1&bgcolor=' + color + '&style=conversation&catList=Conversations^Blogs&fromUID=' + params.from_user_id + '&toUserId=' + params.to_user_id + '&nav=TosReportMaster&quoted=true&tid=' + params.tid + '&tsn=' + params.tsn + '&replyToTid=' + params.reply_to_id + '&replyToTsn=' + params.reply_to_tsn + '&url=' + encodeURIComponent(location.href);
			var iframe_html = '<iframe style="clear:both; zoom:1;" src="' + iframe_url + '" width="510" height="200" border="0" frameborder="0" marginheight="0" marginheight="0" scrolling="no"></iframe>';
			var iframes = li.getElementsByTagName('iframe');
			
			
			if(iframes.length)
			{
				$A(iframes).each(function(iframe){ $(iframe).remove(); })
				li.setStyle({height:'100px'});
				elem.update('Report Violation');
				this.start_stream();
			}
			else
			{
				li.setStyle({height:'300px'});
				new Insertion.Bottom(li.getElementsBySelector('.ccmb-info-inner')[0], iframe_html);
				elem.update('Cancel');
				this.pause_stream();	
			}
			
			Event.stop(evt);
		},
		check_queue: function()
		{
			if(this.is_paused){ this.check_timer = setTimeout(function(){ this.check_queue(); }.bind(this), this.options.ccmb_freq); return; }
			
			var item = this.queue.shift();
			var check_back_in = this.checks_with_no_items > 0 ? this.checks_with_no_items * this.options.ccmb_freq : this.options.ccmb_freq
			
			if(item)
			{
				$('ccmb-indicator').hide();
				this.add_rows(item);
				if($("ccmb-root").childNodes.length > this.options.ccmb_show + 1)
				{
					this.remove_rows('last');
				}
			}
			else
			{
				this.fetch_data();
			}
			this.check_timer = setTimeout(function(){ this.check_queue(); }.bind(this), this.options.ccmb_freq);
		},
		add_rows: function(type)
		{
			var div = $(document.createElement('div'));
			var count = $("ccmb-root").childNodes.length-1;
			
			//li.hide();
			//li.className = 'ccmb-entry ' + this.className
			
			this.parse_item(type,this.className);
			
			div.update(this.empty_buffer());
			
			var li = $(div.firstChild);
			li.hide(); 
			
			$("ccmb-root").insertBefore(li,$("ccmb-header").nextSibling);
			
			this.add_item_to_tag_cloud(type);
			
			new Effect.Appear(li);
			
			this.className = this.className == 'ccmb-odd' ? 'ccmb-even' : 'ccmb-odd';
			this.activate_violation_links(li);
			
			//Help out IE's garbage collector
			delete(li);
			delete(div);
			
		},
		remove_rows: function(type)
		{
			if(type == 'last') new Effect.Fade($($("ccmb-root").lastChild), {afterFinish: function(obj){$(obj.element).remove();}});
		},
		load_data: function()
		{
			try{ return ProsperoResponse_ccmb; }
			catch(e){ try { return ProsperoResponsePTRead; } catch(e){ return {}; }}
		},
		pagination_markup: function()
		{
			var html = '';
			var context = ProsperoResponsePTRead.ContentElement.DirectoryContext;
			var num_results = context['@totalHits'];
			var hits_per_page = context['@pageSize'];
			var num_pages = Math.ceil(num_results/hits_per_page);
			
			for(var i=0; i<num_pages; i++)
			{
				var current_index = (i * hits_per_page + 1)
				var next_index = current_index + hits_per_page;
				if( current_index == context['@firstIndex'] )
				{
					html += '<strong>' + (i+1) + '</strong>, ';
				}
				else
				{
					html += '<a href="?ccmb_search_index=' + current_index + '&ccmb_search_type=keyword&ccmb_search_text=' + this.options.ccmb_search_text + '">' + (i + 1) + '</a>, ';
				}
			}
			
			html = html.replace(/, $/,'');
			
			return html;
		},
		fetch_data: function()
		{
			try{$(this.id).remove();}catch(e){}
			this.in_count = this.in_count || 1;

			var s_tag = document.createElement('script');
			var hours = this.options.ccmb_hours;
			//var extra = /Konqueror|Safari|KHTML/.test(navigator.userAgent) ? '&ran=' + this.in_count : '';
			var extra = '&ran=' + this.in_count;

			s_tag.id = this.id;
			s_tag.type = 'text/javascript';
			s_tag.src = this.data_src + '&callback=ccmb_populate_queue&callbackparam=local&activityHours=' + hours + extra;
			this.in_count++;
			$$('head')[0].appendChild(s_tag);
		},
		populate_queue: function(obj)
		{
			try{ this.queue = this.collect_items( obj.ContentElement.Forum[0] ); }
			catch(e) { this.queue = []; }
			this.apply_filters();
			this.queue = this.queue.reverse();
			if(!this.queue.length)
			{
				this.checks_with_no_items++;
			}
			else
			{
				this.checks_with_no_items = 0;
			}
		},
		prune_queue_by_staleness: function()
		{
			this.queue.each(function(item)
			{
				if( this.is_stale(item) )
				{
					this.queue = this.queue.without(item);
				}
			}.bind(this));
		},
		is_stale: function(item)
		{
			var _20_minutes = 60 * 60 * 20;
			return !item.Message[0]['@datePosted'].is_within(_20_minutes);
		},
		prune_queue_by_time: function()
		{
			if( this.queue.length < 1 ){ return; }
			if( !this.timestamp ){ this.timestamp = new Date(this.queue.first().Message[0]['@datePosted']); return; }
			
			this.queue.each(function(item)
			{
				if( new Date(item.Message[0]['@datePosted']) <= this.timestamp )
				{
					this.queue = this.queue.without(item);
				}
			}.bind(this));
			if( this.queue.length < 1 ) return;
			this.timestamp = new Date(this.queue.first().Message[0]['@datePosted']);
		},
		has_seen_item: function(item)
		{
			var guid = item['@tid'] + '' + item.Message[0]['@tsn'];
			
			return this.seen_items[guid] != null;
		},
		adjust_comment_count: function(items)
		{
			this.count = this.count || {};
			items = items || this.queue.reverse(false);
			
			items.each(function(item)
			{
				var adjusted_count = parseInt(item['@messageCount']);
				var stored_item = this.count[item['@subject']];
				
				if(!stored_item)
				{
					stored_item = {
						message_count: adjusted_count,
						times_seen: 0
					}	
				}
				
				if(stored_item.message_count == adjusted_count)
				{
					adjusted_count -= stored_item.times_seen;
					stored_item.times_seen++;
					item['@messageCount'] = adjusted_count;
				}
				this.count[item['@subject']] = stored_item;
				
			}.bind(this));
			this.count = {};
		},
		prune_queue_by_unique: function()
		{
			this.queue.each(function(item)
			{
				if( this.has_seen_item(item) )
				{
					this.queue = this.queue.without(item);
				}
			}.bind(this));
		},
		prune_queue_by_hottness: function()
		{						
			this.queue.each(function(item)
			{
				if( !this.popular[item['@subject']] )
				{
					this.queue = this.queue.without(item);
				}
			}.bind(this));
		},
		emtpy_queue: function()
		{
			this.queue = [];
		},
		item_url: function(item)
		{
			var message = item.Message[0];
			for( var i in item )
			{
				if( i != 'Message' )
				{
					message[i] = item[i];
				}
			}
			return conversation_url( message );
		},
		item_author: function(item)
		{
			if(item['@fromDisplayName']){ return item['@fromDisplayName']; }
			
			
			var user = ProsperoResponsePTRead.ContentElement.UserDictionary.User.find(function(u)
			{
				return u['@userId'] == item['@fromUserId'];
			});
			
			return user ? user['@displayName'] : '';
		},
		add_item_to_tag_cloud: function(item)
		{
			if(this.options.ccmb_include_tag_cloud && !this.options.ccmb_search_text)
			{
				var tag_cloud_id = 'tag-cloud-' + item['@tid'];
				var subject = item['@subject'] ? item['@subject'] : 'NO SUBJECT';
				var message_count = parseInt(item['@messageCount']);
				var starting_size = 10 + Math.round(message_count/100);
				
				starting_size = 10;
				if($(tag_cloud_id))
				{
					var font_size = (parseInt($(tag_cloud_id).getStyle('fontSize'))+1) + 'px';
					
					if(parseInt(font_size) < 40) $(tag_cloud_id).setStyle({fontSize:font_size});
					/*if(parseInt(font_size) > 24)
					{
						$(tag_cloud_id).removeClassName('ccmb-tag-cloud-item-low');
						$(tag_cloud_id).removeClassName('ccmb-tag-cloud-item-med');
						$(tag_cloud_id).addClassName('ccmb-tag-cloud-item-high');
					}
					else if(parseInt(font_size) > 17)
					{
						$(tag_cloud_id).removeClassName('ccmb-tag-cloud-item-low');
						$(tag_cloud_id).addClassName('ccmb-tag-cloud-item-med');
					}*/
				}
				else
				{
					//var el_s = '<a id="' + tag_cloud_id + '" target="_new" class="ccmb-tag-cloud-item-low ccmb-tag-cloud-item" style="font-size:' + starting_size + 'px;" href="' + this.item_url(item) + '" id="' + tag_cloud_id + '">' + subject + '</a>'; 
					
					var el = $(document.createElement('a'));
					el.id = tag_cloud_id
					el.target = '_new';
					
					el.addClassName('ccmb-tag-cloud-item');
					el.setStyle({fontSize:starting_size});
					el.href = this.item_url(item);
					el.appendChild(document.createTextNode(subject));
					
					try{ var child_node = Math.round(Math.random() * $('ccmb-tag-cloud-container').childNodes.length - 1); } catch(e){ var child_node = 0; }
					
					child_node = child_node + 1;
					
					if(child_node > $('ccmb-tag-cloud-container').length - 1)
					{
						child_node = $('ccmb-tag-cloud-container').length - 1;
					}
					
					
					try
					{
						if(child_node <= 0)
						{
							$('ccmb-tag-cloud-container').appendChild(el);
						}
						else
						{
							$('ccmb-tag-cloud-container').insertBefore(el,$('ccmb-tag-cloud-container').childNodes[child_node]);
						}
					}
					catch(e)
					{
						$('ccmb-tag-cloud-container').appendChild(el);
					}
					
					$A($('ccmb-tag-cloud-container').childNodes).each(function(node,count)
					{
						var className = count % 2 == 0 ? 'ccmb-tag-cloud-item-off' : 'ccmb-tag-cloud-item-on';
						
						$(node).removeClassName('ccmb-tag-cloud-container-off');
						$(node).removeClassName('ccmb-tag-cloud-container-on');
						$(node).addClassName(className);
					});
					
					//new Insertion.Bottom($('ccmb-tag-cloud-container'),el_s)
					
				}
				new Effect.Highlight(tag_cloud_id, {duration:4, queue: {position: 'end', scope: 'tagcloud', limit:2}});
			}
		},
		write_to_buffer: function(html)
		{
			if(this.store_in_buffer)
			{
				this.html += html;
			}
			else
			{
				document.write(html);
			}
		},
		empty_buffer: function()
		{
			var html = this.html;
			this.html = '';
			
			return html;
		},
		parse_item: function(item,item_count,exclude_li)
		{
			var subject = item['@subject'] ? item['@subject'] : 'NO SUBJECT';
			var time_ago_in_words = item.Message[0]['@datePosted'].time_ago_in_words();
			var replyTo = item.Message[0]['@toDisplayName'] && item.Message[0]['@toDisplayName'] != 'All' ? '@<a title="In response to ' + item.Message[0]['@toDisplayName'] + '" href="?ccmb_search_type=user&ccmb_search_text=' + item.Message[0]['@toDisplayName'] + '">' + item.Message[0]['@toDisplayName'] + '</a>: ' : '';
			var message = item.Message[0];
			var className = item_count % 2 == 0 ? 'ccmb-even' : 'ccmb-odd';
			var hot_class = this.popular[item['@subject']] ? 'ccmb-hot' : '';
			//var hot_icon = this.popular[item['@subject']] ? '&nbsp;&nbsp;' : '';
			var text = '';
			var author = this.item_author(item.Message[0]);
			var date_text = this.options.ccmb_search_type ? ' | ' + time_ago_in_words : '';
			var guid = item['@tid'] + '' + item.Message[0]['@tsn']; 
			var html_id = 'item' + item['@tid'] + '-' + item['@messageCount'];
			
			if(typeof(item_count) == 'string') className = item_count;
			
			if($(html_id))
			{
				item['@messageCount'] = (parseInt(item['@messageCount']) + 1);
				html_id = 'item' + item['@tid'] + '-' + item['@messageCount']; 
			}
			
			if($(html_id))
			{
				item['@messageCount'] = (parseInt(item['@messageCount']) + 1);
				html_id = 'item' + item['@tid'] + '-' + item['@messageCount']; 
			}

			var count = item['@messageCount'];
			var moderation_link = this.options.ccmb_include_moderation ? ' | <a href="?from_user_id=' + message['@fromUserId'] + '&to_user_id=' + message['@toUserId'] + '&tid=' + item['@tid'] + '&tsn=' + message['@tsn'] + '&reply_to_tsn=' + message['@replyToTsn'] + '&reply_to_id=' + item['@tid'] + '" class="ccmb-violation">Report Violation</a>' : '';
			
			this.number_seen++;
			
			try{ $('ccmb-number-seen').update(this.number_seen+'');} catch(e){}
			
			if(item.Message[0]['@messageText'])
			{
				this.seen_items[guid] = 1;
				item.Message[0]['@messageText'] = replyTo + item.Message[0]['@messageText'].truncate((this.is_cloud_open ? this.options.ccmb_characters_allowed_with_cloud : this.options.ccmb_characters_allowed));
			}
			else if(item.Message[0].SearchResultInfo)
			{
				item.Message[0]['@messageText'] = item.Message[0].SearchResultInfo['@excerpt'];
			}
			
			text = conversation_body( item.Message[0] );
			
			
			var link_base = (this.options.ccmb_link_to == 'profile') ? 'http://myespn.go.com/' : '?ccmb_search_type=user&ccmb_search_text=';
			
			this.write_to_buffer(exclude_li ? '' : '<li id="' + html_id + '" class="ccmb-entry ' + className + '">');
			
			if( this.options.ccmb_include_images )
			{
				var image_html = '<div class="ccmb-image-container">\
							<a target="_new" title="' + author + '" href="' + link_base + author + '"><img alt="" src="http://avatars.espn.go.com/avatars/' + author.toLowerCase() + '/48/' + author.toLowerCase() + '.jpg" onerror="this.src=\'http://assets.espn.go.com/i/profile/default/silo1_guy_35x48.jpg\'; this.onerror=null;" /></a>\
						</div>'
				moderation_link = this.options.ccmb_include_moderation ? ' <a href="?from_user_id=' + message['@fromUserId'] + '&to_user_id=' + message['@toUserId'] + '&tid=' + item['@tid'] + '&tsn=' + message['@tsn'] + '&reply_to_tsn=' + message['@replyToTsn'] + '&reply_to_id=' + item['@tid'] + '" class="ccmb-violation"><img src="http://assets.espn.go.com/profile/i/trans/icon_report_lo.gif" alt="" /></a>' : '';
				
				this.write_to_buffer('<div class="ccmb-count"><div class="ccmb-count-inner"><span class="' + hot_class + '">' + count + '</span></div></div>\
					<div class="ccmb-info"><div class="ccmb-info-inner">\
						<h3><a href="' + this.item_url(item) + '">' + subject + '</a> | <a title="' + author + '" href="' + link_base + author + '">' + author.truncate(20,'...') + '</a></h3>\
						<p>' + image_html + text + moderation_link + '</p>\
					</div></div>\
					<div class="ccmb-type"><div class="ccmb-type-inner">' + this.item_category(item) + '</div></div>');
			}
			else
			{
				this.write_to_buffer('<div class="ccmb-count"><div class="ccmb-count-inner"><span class="' + hot_class + '">' + count + '</span></div></div>\
					<div class="ccmb-info"><div class="ccmb-info-inner">\
						<h3><a href="' + this.item_url(item) + '">' + subject + '</a></h3>\
						<cite><a target="_new" href="' + link_base + author + '">' + author + '</a></cite>' + date_text + moderation_link + '\
						<p>' + text + '</p>\
					</div></div>\
					<div class="ccmb-type"><div class="ccmb-type-inner">' + this.item_category(item) + '</div></div>');
			}
			this.write_to_buffer(exclude_li ? '' : '</li>');
		},
		pause_stream: function()
		{
			this.is_paused = true;
			try{ $('ccmb-pause-indicator').setStyle({visibility:'visible'}); } catch(e){}
		},
		start_stream: function()
		{
			this.is_paused = false;
			$('ccmb-pause-indicator').setStyle({visibility:'hidden'});
		},
		parse_data: function(items)
		{
			this.adjust_comment_count(items);
			
			this.write_to_buffer('<div id="ccmb">');
			
			if(this.options.ccmb_include_play_pause && !this.options.ccmb_search_type && !this.options.ccmb_search_text) this.write_to_buffer('<div id="ccmb-pause-indicator" style="visibility:hidden;"><strong>Paused</strong></div><a id="ccmb-pause" href=""></a> <a id="ccmb-play" href=""></a>');
			
			if(this.options.ccmb_include_title)
			{
				this.write_to_buffer('<h2>');
				if(!this.options.ccmb_search_type && !this.options.ccmb_search_text)
				{
					this.write_to_buffer('A Real-Time view of Conversations on ESPN.com');
				}
				else
				{
					var link = location.href.split('?')[0];
					this.write_to_buffer(this.options.ccmb_search_type.capitalize() + ' search results for: ' + this.options.ccmb_search_text);
					if(this.options.ccmb_search_type == 'keyword') this.write_to_buffer(' <small>[' + this.pagination_markup() + ']</small>');
					this.write_to_buffer('<small> | <img id="ccmb-backto-icon" alt="" src="http://assets.espn.go.com/profile/ccmb/images/hot.gif"/> <a href="' + link + '">Back to Real-Time</a></small>');
				}
				if(this.options.ccmb_include_tag_cloud && !this.options.ccmb_search_text)  
				{
					var text = this.options.ccmb_start_with_cloud_open ? 'Hide Conversation Cloud' : 'Show Conversation Cloud';
					this.write_to_buffer(' <small id="ccmb-toggle-tag-cloud-wrapper"><a title="Headlines grow with the number of times you have seen them." href="#" id="ccmb-toggle-tag-cloud">' + text + '</a></small>');
				}
				this.write_to_buffer('</h2>');
			}
			else if(this.options.ccmb_include_tag_cloud && !this.options.ccmb_search_text)  
			{
				var text = this.options.ccmb_start_with_cloud_open ? 'Hide Tag Cloud' : 'Show Tag Cloud';
				this.write_to_buffer('<a href="#" id="ccmb-toggle-tag-cloud">' + text + '</a>');
			}
			
			var style = this.options.ccmb_start_with_cloud_open ? '' : 'display:none;';
			if(this.options.ccmb_include_tag_cloud && !this.options.ccmb_search_text) this.write_to_buffer('<div id="ccmb-tag-cloud-container" style="' + style + '">');
			if(this.options.ccmb_show_number_seen) this.write_to_buffer('<div id="ccmb-number-seen-container">You have seen <span id="ccmb-number-seen">' + this.number_seen + '</span> comments.</div>');
			if(this.options.ccmb_include_tag_cloud && !this.options.ccmb_search_text) this.write_to_buffer('</div>');
			this.write_to_buffer('<small id="ccmb-indicator" style="display:none;">Applying filter</small>');
			this.write_to_buffer('<ul id="ccmb-root">');
			this.write_to_buffer('<li id="ccmb-header">');
			this.write_to_buffer('<div class="ccmb-header-comments"><label>Comments</label></div>');
			this.write_to_buffer('<div class="ccmb-header-info">');
			
			if(this.options.ccmb_include_search && this.options.ccmb_include_search_in_header) this.write_to_buffer(this.search_markup());
			
			if(this.options.ccmb_include_filter && !this.options.ccmb_search_type && !this.options.ccmb_search_text)
			{
					this.write_to_buffer('<form action="#">\
								<p><label>Conversations</label><input id="ccmb-conversation-filter" name="type" type="radio" value="Conversations" /></p>\
								<p><label>Message Boards</label><input id="ccmb-message-board-filter" name="type" type="radio" value="general" /></p>\
								<p><label>Blog Comments</label><input id="ccmb-blog-comment-filter" name="type" type="radio" value="Blogs" /></p>\
								<p><label>All</label><input checked="checked" id="ccmb-all-filter" name="type" type="radio" value="all" /></p>\
								<p><label class="ccmb-hot">HOT Topics Only</label><input selected="selected" id="ccmb-hot-filter" type="checkbox" value="1" /></p>\
							</form>');
			}
			
			this.write_to_buffer('</div><div class="ccmb-header-type"><label>Type</label></div>');
			this.write_to_buffer('</li>');
			items.each(function(item,count)
			{
				if(this.options.ccmb_search_text || !this.is_stale(item)) this.parse_item(item,count);
			}.bind(this));
			
			this.write_to_buffer('</ul>');
			if(this.options.ccmb_include_search && !this.options.ccmb_include_search_in_header) this.write_to_buffer(this.search_markup());
			this.write_to_buffer('</div>');
			
			return this.empty_buffer();
		},
		item_category: function(item)
		{	
			if(item['@contentId'] && item['@contentId'].toLowerCase().indexOf('blog') > -1) return "Blog Comment";
			if(item['@contentId']) return "Conversation";
			return "Message Board";
		},
		render: function(html,items)
		{
			if(this.options.ccmb_attach_point)
			{
				Event.onDOMReady(
					function()
					{
						$(this.options.attach_point).update(html);
						try{ var items = this.collect_items( this.load_data().ContentElement.Forum[0] ); }
						catch(e) { var items = []; }
						items.each(function(item,count)
						{
							this.add_item_to_tag_cloud(item);
						}.bind(this))
					}.bind(this));
					try{ $('ccmb-number-seen').update(this.number_seen+'');} catch(e){}
					this.apply_behaviors();
			}
			else
			{
				items.each(function(item,count)
				{
					this.add_item_to_tag_cloud(item);
				}.bind(this));
				try{ $('ccmb-number-seen').update(this.number_seen+'');} catch(e){}
				this.apply_behaviors();
			}
			this.store_in_buffer = true;
		},
		search_markup: function()
		{
			var class_name = this.options.ccmb_include_search_in_header ? 'ccmb_search_header' : 'ccmb_search_footer';
			var middle_p = this.options.ccmb_include_search_in_header ? '' : '</p><p>';
			
			return '<form action="" class="' + class_name + '" id="ccmb-search">\
						<p>\
							<input name="ccmb_search_text" type="text" class="ccmb-search-text" />&nbsp;&nbsp; \
							<input class="ccmb-search-submit" type="image" src="http://assets.espn.go.com/profile/ccmb/images/btn_search_comments.gif" value="Search Comments" />\
							' + middle_p + '\
							<input class="ccmb-search-option" checked="checked" type="radio" name="ccmb_search_type" value="keyword" /><label>Keyword</label>\
							<input class="ccmb-search-option" type="radio" name="ccmb_search_type" value="user" /><label>User</label>\
						</p>\
					</form><div style="clear:both;"></div>';
		},
		construct_options: function()
		{
			var options = {};
			var vars = {
				ccmb_include_tag_cloud: false,
				ccmb_show_number_seen: false,
				ccmb_search_text: null,
				ccmb_search_type: null,
				ccmb_include_search: true,
				ccmb_hours: 1,
				ccmb_cat: 'all',
				ccmb_attach_point: undefined,
				ccmb_include_title: true,
				ccmb_include_filter: true,
				ccmb_show: 20,
				ccmb_include_play_pause: true,
				ccmb_characters_allowed: 400,
				ccmb_characters_allowed_with_cloud: 300,
				ccmb_start_with_cloud_open: true,
				ccmb_include_search_in_header: false,
				ccmb_include_moderation: true,
				ccmb_link_to: 'search',
				ccmb_include_images: true,
				ccmb_freq: 5000
			};
			
			for(var i in vars)
			{
				options[i] = (window[i] === null || window[i] === undefined) ? vars[i] : window[i];	
			}
			
			return options;
		},
		collect_items: function( forum )
		{
			var items = [];
			forum.Folder.each( function( folder )
			{
				folder.Discussion.each( function( discussion )
				{
					items.push( discussion );
				});
			});
			
			return items;
		},
		populate_popular: function(obj)
		{
			try{ var items = this.collect_items( obj.ContentElement.Forum[0] ); }catch(e){ items = []; }
			items.each(function(item)
			{
				this.popular[item['@subject']] = 1;
			}.bind(this));
		},
		fetch_popular: function(type)
		{
			try{$(this.popular_id + '_' + type).remove();}catch(e){}
			
			var prospero_type = type == 'message_board' ? 'talkback' : 'discussions'
			var s_tag = document.createElement('script');
			var cat_list = (type == 'message_board') ? 'all' : (type == 'conversations') ? 'Conversations' : 'Blogs';
			s_tag.id = this.popular_id + '_' + type;
			s_tag.type = 'text/javascript';
			s_tag.src = this.popular_data_src + '&callback=ccmb_populate_popular_' + type + '&callbackparam=local&type=' + prospero_type + '&catList=' + cat_list;
			$$('head')[0].appendChild(s_tag);
		}
	};
	
	var ccmb = new CCMB;
	ccmb_populate_queue = ccmb.populate_queue.bind(ccmb);
	ccmb_populate_popular_message_board = ccmb.populate_popular.bind(ccmb);
	ccmb_populate_popular_conversations_conversations = ccmb.populate_popular.bind(ccmb);
	ccmb_populate_popular_blog_comments = ccmb.populate_popular.bind(ccmb);
}();
 