/**
 * Comment -
 *
 * add, recommend or flag comments associated to specific pieces of content
 *
 */
billboard.comments = new (function($)
{
	// rest API urls
	var URL_RECOMMEND_COMMENT = "rest/v1/rating/comment/create";
	var URL_REPORT_COMMENT = "rest/v1/flag/comment";
	var URL_BB_PROFILE_COMMENT_EMAIL = "/user/email/profile-comment-email.json?";

	var SORT_RECENT = "MostRecentFirst";// "MostRecentlyCommented";
	var SORT_NORMAL ="LeastRecentFirst";// "LeastRecentlyCommented"  or chronological order;
	var SORT_REPLIES = "MostCommented";
	var SORT_RECOMMENDED = "HighestRated";
	var SORT_LAST_MODIFIED = "MostRecentlyCommented";

	var DEFAULT_PAGE_SIZE = 6;
	var DEFAULT_CONVERSATION_PAGE_SIZE = 20;

	var MAX_COMMENT_CHAR = 330;

	var me = this;
	me.contentId = '';
	me.commentId = '';
	me.sort = SORT_RECENT;
	me.posting = false;

	me.totalComments = 0;
	me.currentPage = 0;
	me.numPerPage = DEFAULT_PAGE_SIZE;
	me.conversationTitle = '';

	/**
	 * register listeners
	 */
	billboard.broadcaster.addListener( "pageLoaded", function() { me.onPageLoaded(); } );
	billboard.broadcaster.addListener( "userLoggedOut", function() { me.onLoggedOut(); } );

	/**
	 *
	 */
	me.init = function()
	{
		billboard.info("Comments.init()");
	};

	me.onLoggedOut = function()
	{
		// TODO: reset comments... i.e. remove recommend/flag buttons?
	};

	me.isDiscussions = function()
	{
		if ( $("#conversation-id").text().length > 0 || billboard.subsection != "conversations" ) { 
			return false;
		}
		else {
			return true;
		}
	};

	/**
	 * reset all values to the starting/default values
	 */
	me.reset = function()
	{
		me.contentId = $("#entity-id").text();
		me.commentId = $("#conversation-id").text();
		me.sort = (me.isDiscussions())?(SORT_LAST_MODIFIED):(SORT_RECENT);
		me.numPerPage = DEFAULT_PAGE_SIZE;
		me.totalComments = 0;
		me.currentPage = 0;
		me.posting = false;
	};

	me.clearForms = function()
	{
		$(".comment-add textarea").val("");
		$(".comment-add input").val("");
	//	$(".comment-add").hide();
		$(".comment-add #comment-subject, .comment-add #comment-body").removeClass("field-error");
		$("#comment-error").html("");
	}

	/**
	 *
	 */
	me.onPageLoaded = function()
	{
		billboard.log("Comments.onPageLoaded()");

		me.reset();

		me.getDiscussionCounts();

		if ( typeof(me.contentId)=="undefined" || me.contentId.length <= 0 ) {
			// if theres no entity to comment, theres no comments, so return
			return;
		}

		//billboard.log( "Comments.Content ID: "+me.contentId );
		
		me.activateUI();

		// load comments for this page type
		me.load();
           if(billboard.section=='forums' && billboard.subsection=='conversations'){
			
			document.title="Forums - "+$('#forum-topic-name').html()+" | Billboard.com";
			var categoryLink = (billboard.history.hash).substring(0,(billboard.history.hash).indexOf('&c'));
			var categoryLink=categoryLink.replace('%20',' ');			
			$('.conversation-link').attr('href',categoryLink);			
			$('.filter-nav.comment-filters').hide();
			
		}
	};

	/**
	 * add submit form handlers and filter button click handlers
	 */
	me.activateUI = function()
	{
		// activate add comment form
		$(".comment-add input:not(.comment-button)").focus( function(){$(this).addClass("active");} );
		$(".comment-add input:not(.comment-button)").blur( function(){$(this).removeClass("active");} );
		$(".comment-add textarea:not(.comment-button)").focus( function(){$(this).addClass("active");} );
		$(".comment-add textarea:not(.comment-button)").blur( function(){$(this).removeClass("active");} );
		$(".comment-add textarea:not(.comment-button)").keyup( function(){
			if($(this).attr("value").length>MAX_COMMENT_CHAR){
				$("#comment-error").html("Sorry. The message body cannot be any longer than "+ MAX_COMMENT_CHAR +" characters.");
				$(this).addClass("field-error");
				$(this).attr("value", $(this).attr("value").substr(0,MAX_COMMENT_CHAR));
			}
			else{
				$("#comment-error").html("");
				$(this).removeClass("field-error");
			}

		} );
		$(".comment-add form").submit( function() {
			// verify logged in
			var submitImpl = function() { 
				billboard.info(" Add Form Submit handler" );
				var body = $(".comment-add textarea").val();
				var subject = $(".comment-add #comment-subject").val();
				//strip out html
				body=body.replace(/<(.|\n)*?>/g,'');
				subject=subject.replace(/<(.|\n)*?>/g,'');
				me.add( me.contentId, subject, body );
			};
			billboard.user.requireLogin( submitImpl );
			return false;
		});

		// activate the add comment form 'cancel'
		$(".comment-add form :input[name=cancel]").click( function() {
			me.clearForms();
		});

		// conversation or comment list
		if ( !me.isDiscussions() ) { 
			billboard.log("-normal comment list");
			$("#conversations").hide();
			$(".comment-add .comment-subject").hide();
			//$(".comment-add").show();

			// attach click handlers to standard comment filters
			$(".filter-nav.comment-filters li a").click( function() {
				$(this).parents("ul:first").find("li").removeClass('active');
				$(this).parent().addClass('active');
			});

			$(".filter-nav.comment-filters .filter-recommended").click( function(){
				me.sort = SORT_RECOMMENDED;
				me.load();
			});

			$(".filter-nav.comment-filters .filter-date").click( function(){
				me.sort = SORT_RECENT;
				me.load();
			});

			// make date the active filter by default
			$(".filter-nav.comment-filters li").removeClass('active');
			$(".filter-nav.comment-filters .filter-date").addClass('active');

			// activate 'post comment' button
			$(".post-comment a" ).click(function(){
				$(".comment-add").show();
				$(".comment-add .comment-body").focus();
			});

			$(".start-new-convo a").removeClass("no-ajax");
			billboard.hijackLinks( ".start-new-convo" );
		}
		else { // discussion list
			billboard.log("-conversation list");

			// hide the comment button
			$(".post-comment a").hide();

			$("#comment-container .filter-nav").hide();
			$("#comment-container").hide();
			$(".comment-add .comment-subject").show();
			$(".start-new-convo").click( function() { 
				$("#comment-container").show();
				$(".comment-add").show();
			});

			// attach click handlers to the conversation sorting headers
			$(".most-recent a").click( function() {
				$(".showing div").removeClass("active");
				$(this).parents("div:first").addClass("active");
				me.sort = SORT_LAST_MODIFIED;
				me.load();
			});
			$(".most-replies a").click( function() {
				$(".showing div").removeClass("active");
				$(this).parents("div:first").addClass("active");
				me.sort = SORT_REPLIES;
				me.load();
			});	

			$(".start-new-convo").click( function() { 
				$("#comment-container").show();
				$(".comment-add").show();
				return false;
			});		

			if ( getQueryParams( billboard.currentUrl )["sf"] == 1 ) {
				$("#comment-container").show();
				$(".comment-add").show();
			}
		}
	};

	me.getDiscussionCounts = function()
	{
		/**
		 * artist pages, have a 'discussion' tab that needs a dynamic count of conversations
		 */
		billboard.log("Comments.getDiscussionCounts()");
		if ( billboard.section == "artists" || billboard.section == "forums") {

			billboard.social.getMessageBoardCount( me.contentId, function( response ) { 
				me.totalComments = response.numBoards;
				if(billboard.subsection == 'song' || billboard.subsection == 'album' || billboard.subsection == 'review')
					billboard.social.updateLoveBarCommentCount("#comment-share");
				$(".discussion-count").parent().html( "<span class='discussion-count'>(" + response.numBoards + ")</span> Discussion(s)" );
				if(response.numBoards==0 && billboard.section!='forums') $(".start-new-convo").addClass("empty-convo");
				else if($(".start-new-convo").hasClass("empty-convo")) $(".start-new-convo").removeClass("empty-convo");
			});

			/*
			billboard.social.getMessageBoards( me.contentId, {start:0,count:100}, function(response) { 
				billboard.info( "get discussion counts result" );
				billboard.info( response );

				me.totalComments = response.numBoards;

				//$(".discussion-count").parent().text( "(" + response.numBoards + ") Discussions" );
				//if ( response.numBoards > 0 ) { 
				//me.displayDiscussions( response.boards );
				//}
			});
			*/
			
			/*
			billboard.social.getMessageBoards( me.contentId, {start:0,count:1}, function(response) { 				
				var count = response.board_count?response.board_count:0;
				if ( count == 1 ) {
					$(".discussion-count").parent().text( "(1) Discussion" );
				}
				else { 
					$(".discussion-count").parent().text( "(" + count + ") Discussions" );
				}
			});
			*/
		}
	};

	me.load = function()
	{
		billboard.info( "Comments.load()" );
		// get counts first.. since this has to be two calls - (dont ask)
		billboard.social.getEntityInfo( me.contentId, function(data){
			// load comments
			me.numPerPage = DEFAULT_PAGE_SIZE;
			if ( me.isDiscussions() ) { 
				// artist discussion page, listing top level conversations
				me.numPerPage = DEFAULT_CONVERSATION_PAGE_SIZE;
				me.getFeaturedComment();
				me.getDiscussions( me.contentId, me.sort, (me.currentPage*me.numPerPage), me.numPerPage );
			}
			else if ( billboard.subsection == "conversations" ) {
				// specific conversation with a full pagable list of its comments
				// total is the 'number_comments' property on a board - we'll get it in the getDiscussion results
				me.getFeaturedComment();
				me.getDiscussion( $("#conversation-id").text(), (me.currentPage*me.numPerPage), me.numPerPage );
			}
			else { 
				// basic comment list, found on article pages, profile pages, song/album pages
				// total is the numComments on the entity
				me.totalComments = data.numComments;
				me.getComments( me.contentId, me.currentPage*me.numPerPage, me.numPerPage );
			}
		});
	};

	me.updatePagination = function()
	{
		billboard.info("Comments.updatePagination()");
		billboard.info( me.totalComments +">"+ me.numPerPage +" ? ") ;
		var li, ul, numPages = Math.ceil(me.totalComments/me.numPerPage);

		// hide by default
		$("#conversations .pagination, #conversations .paginationb, #comment-container .pagination, #comment-container .paginationb").hide();

		// if there are more comments than allowed perpage turn on the pagination UI
		if ( me.totalComments > me.numPerPage ) {

			ul = $("#comment-container .pagination ul");
			ula = $("#comment-container .paginationb ul");
			ulb = $("#conversations .pagination ul");
			ulc = $("#conversations .paginationb ul");
			if ( billboard.subsection == "conversations" && $("#conversation-id").text().length <= 0 ) {
				$("#comment-container .pagination, #comment-container .paginationb").hide();
			}
			ul.empty();
			ula.empty();
			ulb.empty();
			ulc.empty();

			$("#conversations .pagination, #conversations .paginationb, #comment-container .pagination, #comment-container .paginationb").show();

			// add the previous arrow if higher than page 1
			if ( me.currentPage > 0 ) {
				li = $("<li class='arrow-left'><a href='javascript:void(0);'>&lt;</a></li>");
				lia = $("<li class='arrow-left'><a href='javascript:void(0);'>&lt;</a></li>");
				lib = $("<li class='arrow-left'><a href='javascript:void(0);'>&lt;</a></li>");
				lic = $("<li class='arrow-left'><a href='javascript:void(0);'>&lt;</a></li>");
				ul.append( li );
				ul.find(".arrow-left a").click(function(){
					billboard.comments.page( me.currentPage-1 );
					return false;
				});
				ula.append( lia );
				ula.find(".arrow-left a").click(function(){
					billboard.comments.page( me.currentPage-1 );
					return false;
				});
				ulb.append( lib );
				ulb.find(".arrow-left a").click(function(){
					billboard.comments.page( me.currentPage-1 );
					return false;
				});
				ulc.append( lic );
				ulc.find(".arrow-left a").click(function(){
					billboard.comments.page( me.currentPage-1 );
					return false;
				});

			}
			
			// add all page numbers
			for ( var i=0;i<numPages;i++ ) {
				li = $("<li><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				lia = $("<li><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				lib = $("<li><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				lic = $("<li><a href='javascript:void(0);'>"+(i+1)+"</a></li>");
				li.find("a").click( function() { 
					billboard.comments.page( ($(this).text()-1) );
					return false;
				});
				lia.find("a").click( function() { 
					billboard.comments.page( ($(this).text()-1) );
					return false;
				});
				lib.find("a").click( function() { 
					billboard.comments.page( ($(this).text()-1) );
					return false;
				});
				lic.find("a").click( function() { 
					billboard.comments.page( ($(this).text()-1) );
					return false;
				});
				if ( i == me.currentPage ){
					li.addClass("on");
					lia.addClass("on");
					lib.addClass("on");
					lic.addClass("on");
				}
				ul.append( li  );
				ula.append( lia  );
				ulb.append( lib  );
				ulc.append( lic  );
			}
			
			// add the next arrow if less than total pages
			if ( me.currentPage < (numPages-1) ) {
				li = $("<li class='arrow-right'><a href='javascript:void(0);'>&gt;</a></li>");
				lia = $("<li class='arrow-right'><a href='javascript:void(0);'>&gt;</a></li>");
				lib = $("<li class='arrow-right'><a href='javascript:void(0);'>&gt;</a></li>");
				lic = $("<li class='arrow-right'><a href='javascript:void(0);'>&gt;</a></li>");
				ul.append( li );
				ul.find(".arrow-right a").click(function(){
					billboard.comments.page( me.currentPage+1 );
					return false;
				});
				ula.append( lia );
				ula.find(".arrow-right a").click(function(){
					billboard.comments.page( me.currentPage+1 );
					return false;
				});
				ulb.append( lib );
				ulb.find(".arrow-right a").click(function(){
					billboard.comments.page( me.currentPage+1 );
					return false;
				});
				ulc.append( lic );
				ulc.find(".arrow-right a").click(function(){
					billboard.comments.page( me.currentPage+1 );
					return false;
				});

			}		   
			if ( billboard.subsection == "conversations" && $("#conversation-id").text().length <= 0 ) {
				$("#comment-container .pagination, #comment-container .paginationb").hide();
			}
		}				
	};

	me.getComments = function( contentId, start, count ) 
	{
		//billboard.log( "Comment.get(" +contentId+", "+start+", "+count +")");

		var params = {sort_rating:"Recommended",rating:"Recommended",start:start,count:count,sort:me.sort};
		billboard.social.getComments( contentId, params, function( data ) {
			if ( data.error_code != 0 ) {
				// code of 19, means entity doesnt exist - which is ok, since it wont until the first comment is made
				if ( data.error_code != 19 ) {
					billboard.info("Error: "+data.error_str + data.error_detail);
				}
			}
			else if ( data.error_code == 0 ) {
				billboard.info("get comments result");
				billboard.info( data );
				//billboard.log( data.comments.length );
				// if successful, and there are some comments... populate the comment list
				if ( data.comments && data.comments.length > 0 ) {
					//billboard.log( "#comments retrieved for this page: " + data.comments.length );

					if ( me.isDiscussions() ) {
						me.displayDiscussions( data.comments )
					}
					else {
						me.displayComments( data.comments );
						if(billboard.section!= 'artists' || (billboard.section == 'artists' && (billboard.subsection=='song' || billboard.subsection=='album' || billboard.subsection=='review')))
							billboard.social.updateLoveBarCommentCount("#comment-share");
					}
					
				}
			}
		});
	};

	/**
	 *
	 */
	me.getDiscussions = function( contentId, sort, start, size )
	{
		billboard.log("Comments.getDiscussions()");

		billboard.social.getMessageBoards( contentId, {order:sort,start:start,count:size}, function(response) { 
			if ( response.numBoards > 0 ) { 
				if ( response.boards ) me.displayDiscussions( response.boards );
			}
		});

		/*
		billboard.social.getMessageBoards( contentId, {start:start,count:size}, function(response) { 
			me.totalComments = response.board_count;
			if ( response.board_count > 0 ) { 
				me.displayDiscussions( response.boards );
			}
		});

		billboard.social.search( "groupuid:mb_group_"+me.contentId, "board", me.sort, 0, 100, function(response) {
			billboard.log( response );
			var boards = [];
			for ( var i=0;i<response.results.length;i++ ) {
				boards.push( response.results[i].board );
            }
			billboard.log( boards );
			//me.displayDiscussions( boards );
		});
		*/
	};

	me.getFeaturedComment = function()
	{
		var category = me.contentId.split("-")[1];
		billboard.social.browseEntity( {category:category,order:"MostRecentlyCommented",offset:0,max_return:1}, function(response){		
			if ( response.entities && response.entities.length > 0 ) { 
				billboard.social.getComments( response.entities[0].uid, { order:"MostRecentFirst", offset:0, max_return:1 }, function( res2 ) {
					if ( res2.comments ) { 
						me.displayFeaturedComment( response.entities[0].uid, res2.comments[0] );
					}
				});
			}
		});
	};

	/**
	 *
	 */
	me.getDiscussion = function( boardId, start, count ) 
	{
		//billboard.log("Comments.getDiscussion("+boardId+","+start+","+count+")");
		if(billboard.section=='forums' && billboard.subsection=='conversations')
			me.sort=SORT_NORMAL;
		
		billboard.social.getMessageBoard( boardId, {sort_rating:"Recommended",start:start,count:count,order:me.sort}, function(result) {
			billboard.info("get message board results");
			billboard.info( result );
			
			me.totalComments = result.numComments;
			if(billboard.section=='forums' && billboard.subsection=='conversations')
				$(".post-comment h4").text( me.totalComments + " Posts" );
			else
				$(".post-comment h4").text( me.totalComments + " Comments" );
			if ( result.starter ) me.displayStarterComment ( result.starter );			
			me.displayComments( result.comments );
		});

		/*  /search method with message boards NOTE: /search uses lucene and as such is victim to 
		 *                                           indexing, results are updated infrequently, and
		 *                                           certainly no where near real-time
		var options = {user:billboard.user.username,rating:"Recommended",start:0,count:20};
		billboard.social.getMessageBoard( boardId, options, function(result) {
			billboard.log( "Comments.getDiscussion() result" );
			billboard.log( result );

			// total is the 'number_comments' property on a board
			me.totalComments = result.number_comments;

			if ( result ) { 
				// update the feature area
				//$(".comment-feature h1").text( result.number_comments +" Replies" );
				//$(".comment-feature h2").html( result.title );
				var user = (result.user)?(result.user):("unknown user");
				$(".comment-feature .author a").html( user );
				$(".comment-feature .author a").attr("href", "/user/"+user );
				var body = (result.description)?result.description:("");
				if ( body.length > 331 ) body = body.substr( 0, 331 ) + "...";
				$(".comment-feature .conversation-content a").html( body );				
				$(".comment-feature-content").css("visibility","visible");
				
				var params = {sort_rating:"Recommended",rating:"Recommended&rating=Default",start:start,count:count,sort:me.sort};
				billboard.social.getBoardComments( result.id, params, function( data ) {
					me.displayComments( data.comments );
				});
			}
		});
		*/
	};

	me.displayFeaturedComment = function( discussion, comment ) 
	{
		billboard.log("Comment.displayFeaturedComment()");
		//billboard.log( discussion );
		//billboard.log( comment );
		if ( comment ) { 
			var user = (comment.user)?(comment.user.external_id):'unknown';
			var body = (comment.body)?(decodeURI(comment.body)):("");
			if ( body.length > MAX_COMMENT_CHAR ) body = body.substr( 0, MAX_COMMENT_CHAR ) + "...";
			link = updateQueryParams( billboard.history.hash,{cid:discussion});

			// set the featured comment in the top convo area
			$(".comment-feature .author a").html( user );
			$(".comment-feature .author a").attr("href", "/user/"+user );
			$(".comment-feature .conversation-content a").html( body );

			$(".comment-feature .conversation-content a").attr( "href", link );
			$(".comment-feature-content").css("visibility","visible");
			billboard.hijackLinks( $(".comment-feature") );
		}
	};

	me.displayDiscussions = function( convos )
	{
		billboard.log("Comments.displayDiscussions()");
		//var convos = group.boards;
		//billboard.log( convos );

		// add a row for each convo
		var item;
		var curDate = new Date();
		var date,dateStr,lastDate;
		var board,user,subject,body,link;
		var replyCount=0;

		me.updatePagination();

		// clear out any existing conversation entries prior to adding the new list
		$("#conversation-table .conversation-row:not(#conversation-row-template)").remove();
		for ( var i=0;i<convos.length;i++ ) {
			board = convos[i];
			// set local cars from the conversation data
			user = (board.user)?(board.user):'unknown user';
			subject = (board.title)?(decodeURI(board.title)):'unknown title';
			// IE wont support &apos, so replace it out w/ the numeric encoding
			subject = subject.replace("&apos;", "&#39;");
			subject = subject.replace("'", "&#39;");
			body = (board.description)?(decodeURI(board.description)):("unknown body");
			lastDate = (board.created)?(board.created):(board.modified);
			replyCount = convos[i].numReplies;

			// format the date, and the links to the message
			lastDate -= 1000*60*60;
			dateStr = formatDate( lastDate, true, "HH:MM:SS" );
			if(billboard.section=='forums' && billboard.subsection=='conversations')
			    link = updateQueryParams( billboard.history.hash,{cid:board.id,tname:subject});
			else
				link = updateQueryParams( billboard.history.hash,{cid:board.id});
				

			// create the dom element, and updates the bits
			item = $("#conversation-row-template").clone();
			item.removeAttr("id");
			item.find(".subject").html( subject );
			item.find(".subject").attr("href", link );
			item.find(".subject").click(function(){ me.conversationTitle = subject; });
			item.find(".author").text( user );
			item.find(".author").attr("href", "/user/" + user );
			item.find(".replies").text( replyCount );
			item.find(".replies").attr("href", link );
			item.find(".last-post").text(dateStr);
			item.find(".last-post").attr("href", link );
			if ( (i&1)==1 ) item.addClass("altColor");

			$("#conversation-table").append( item.show() );
		}
		billboard.hijackLinks( "#conversation-table" );
		if ( convos.length>0 ) { 
			$("#conversations").show();
		}
		else {
			$("#conversations").hide();
		}
	};

	me.getCommentNode = function( comment ) 
	{
		if ( comment.flag_count>= 5 ) {
			return;
		}
		var recommended,dateStr, username,url,item, count, user_status

		recommended=false;
		// get formatted date
		dateStr = formatDate( comment.created, true );
    user_status = comment.user.status;
    
		if ( typeof(comment.user) == "object" ) { 
			username = (comment.user.user_name) ? comment.user.user_name : comment.user.external_id;
			url = comment.user.profile_photo_url;
		}
		else {
			username = comment.user;
		}
		
		url = (url)?(url):("/images/defaults/user-94.gif");
		item = $("#comment-item-template").clone().removeAttr("id");
		item.find(".comment-id").text(comment.id);
		item.find(".column-1 img").attr("src", url );
		item.find(".column-1 a").attr("href", "/user/"+ username );
		item.find(".column-1 .username").html( username );
		item.find(".column-2 .comment-date").text( dateStr );
		var body = comment.body.replace("&apos", "&#39;");
		body = body.replace("'", "&#39;");
		if(body.length > MAX_COMMENT_CHAR) body = body.substring(0,MAX_COMMENT_CHAR) + "...";
		item.find(".column-2 p").html( body );
		
		// get the 'Recommended' rating and update the buttons,text
		try { 
			for ( var j=0;j<comment.ratings.length;j++ ) {
				if ( comment.ratings[j].category == "Recommended" ) {
					count = comment.ratings[j].count;
				}
				if ( comment.ratings[j].user_rating > 0 ) {
					recommended = true;
				}				
			}
		} catch(ex) {
			//billboard.error("Comments - Ratings undefined");
		}
		
		// if this user has recommended, hide the button, otherwise attach its click handler
		if ( count > 0 ) {
			item.find(".column-2 div span").html( "Recommended by "+count+" music fans" );
		}
		if ( recommended ) {
			item.find(".recommend").removeClass("recommend").addClass("recommended");
			item.find(".flag-item").hide();
		}
		
		if (user_status=="Deleted" || user_status=="Suspended") {
		   item.find(".column-2 .recommend").hide();
		} 
		
		item.find(".recommend a").click( function() {
			var $this = $(this);
			billboard.user.requireLogin( function() { 
				billboard.comments.recommend( $this.parents(".comment-item").find(".comment-id").text() );
			});
		});

		if ( billboard.user.username == username ) {
			item.find(".recommend").hide();
		}
		
		/**
		 * activate recommend and flag buttons for all comments
		 */
		// TODO, should check if current user has flagged this item, to hide the button
		item.find(".flag-item a").click( function() {
			var $this = $(this);
			billboard.user.requireLogin( function() { 
				billboard.comments.flag( $this.parents(".comment-item") );
			});
		});
		
		// add to container and make visible
		billboard.hijackLinks( item );
		return item.show();
	}
	
	me.displayStarterComment = function( comment ) 
	{
		billboard.log("Comments.displayStarterComment()");
		$(".comment-item.starter").remove();

		var node = me.getCommentNode( comment );
		node.css( { "border-bottom":"1px solid #ccc", "margin-bottom":"10px"} );
		node.addClass("starter");
		$(".post-comment").parent().prepend( node );
	};

	/**
	 *
	 */
	me.displayComments = function( comments )
	{
		billboard.log("Comments.displayComments()");
		//billboard.log( comments );		
		if ( typeof(comments)=="undefined" ) { return; }

		// clear existing comments
		$("#comment-item-container").empty();

		if ( me.totalComments > 0 && billboard.section != 'forums' ) {
			//$(".post-comment h4").text( comments.length + " Comments");
			$("#comment-container .filter-nav").show();
		}

		me.updatePagination();

		// add new ones
		var item, url;
		var count=0,recommended,node;

		for  ( var i=0;i<comments.length;i++ ) {
			node = me.getCommentNode( comments[i] );
			/*
			if ( comments[i].flag_count>= 5 ) {
				continue;
			}
			recommended=false;
			// get formatted date
			dateStr = formatDate( comments[i].created, true );
			
			var username;
			if ( typeof(comments[i].user) == "object" ) { 
				username = (comments[i].user.user_name) ? comments[i].user.user_name : comments[i].user.external_id;
				url = comments[i].user.profile_photo_url;
			}
			else {
				username = comments[i].user;
			}

			url = (url)?(url):("/images/defaults/user-94.gif");
			item = $("#comment-item-template").clone().removeAttr("id");
			item.find(".comment-id").text(comments[i].id);
			item.find(".column-1 img").attr("src", url );
			item.find(".column-1 a").attr("href", "/user/"+ username );
			item.find(".column-1 .username").html( username );
			item.find(".column-2 .comment-date").text( dateStr );
			item.find(".column-2 p").html( comments[i].body );
			
			// get the 'Recommended' rating and update the buttons,text
			try { 
				for ( var j=0;j<comments[i].ratings.length;j++ ) {
					if ( comments[i].ratings[j].category == "Recommended" ) {
						count = comments[i].ratings[j].count;
					}
					if ( comments[i].ratings[j].user_rating > 0 ) {
						recommended = true;
					}				
				}
			} catch(ex) {
				billboard.error("Comments - Ratings undefined");
			}
			
			// if this user has recommended, hide the button, otherwise attach its click handler
			if ( count > 0 ) {
				item.find(".column-2 div span").html( "Recommended by "+count+" music fans" );
			}
			if ( recommended ) {
				item.find(".recommend").removeClass("recommend").addClass("recommended");
				item.find(".flag-item").hide();
			}
			
			item.find(".recommend a").click( function() {
				var $this = $(this);
				billboard.user.requireLogin( function() { 
					billboard.comments.recommend( $this.parents(".comment-item").find(".comment-id").text() );
				});
			});
			
			
			 //activate recommend and flag buttons for all comments
			 
			// TODO, should check if current user has flagged this item, to hide the button
			item.find(".flag-item a").click( function() {
				var $this = $(this);
				billboard.user.requireLogin( function() { 
					billboard.comments.flag( $this.parents(".comment-item") );
				});
			});
			*/
			
			if ( i&1 ) { node.addClass("altColor"); }
			
			// add to container and make visible
			$("#comment-item-container").append( node );
			billboard.hijackLinks( node );
		}
	};
	
	/**
	 * go to the page index of comments indicated by 'which'
	 */
	me.page = function( which ) 
	{
		//billboard.log("Comments.page("+which+")");
		me.currentPage = parseInt( which );
		me.load();
		var jump = ($("#conversations").length>0) ? $("#conversations").offset().top : $("#comment-container .comment-filters").offset().top;
		$('html,body').animate( {scrollTop: jump }, 1000 );
		return false;
	};
	
	/**
	 *
	 */
	me.recommend = function( id )
	{
		// get the recommedn url, then sent along the request
		//billboard.log("Comments.recommend("+id+")");
		
		var props = billboard.properties;
		var url = URL_RECOMMEND_COMMENT;
		url = props.proxyPrefix + props.cfConsumerUrl + url + "?" + props.cfQuery + "&rating=Recommended&value=1&comment="+id;
		
		// pull down the json data 
		$.getJSON( url, function(data,status) { 
			if ( data.error_code == 0 ) {
				me.load();				
			}
			else {
				billboard.error( data.error_str );
			}
		});
	};
	
	me.flag = function( comment )
	{
		//billboard.log("Comments.flag("+comment+")");
		var id = comment.find(".comment-id").text();
		
		//billboard.log(" id: "+id );
		var props = billboard.properties;
		var url = URL_REPORT_COMMENT;
		url = props.proxyPrefix + props.cfConsumerUrl + url + "?" + props.cfQuery + "&comment="+id;
		
		// pull down the json data 
		
		$.getJSON( url, function(data,status) { 
			if ( data.error_code == 0 ) {
				comment.find(".flag-item").hide();
			}
		});		
	};
	
	me.add = function( contentId, subject, body )
	{
		//billboard.log( "Comment.add(" +contentId+","+subject+", "+body +")");
		if ( me.isDiscussions() ) {
			me.addDiscussion( contentId, subject, body );
		}
		else {
			me.addComment( contentId, body );
		}
	}
	
	/**
	 * addDiscussion
	 * discussions are modeled as MessageBoards in CF...
	 * creating a message board is two steps, first create a group
	 * then add a message board to it
	 */
	me.addDiscussion = function( contentId, subject, body )
	{
		//billboard.log("Comment.addDiscussion("+contentId+")");
		var realSubject = subject;	
		// only post content when populated
		if (!isNaN(subject) && billboard.subsection == "conversations" ) {
			$("#comment-error").html("Please enter a subject.");
			$(".comment-add #comment-subject").addClass("field-error");
			return;
		}
		
		if ( subject.length > 35 ) {
			$("#comment-error").html("Sorry. The subject cannot be any longer than 35 characters");
			$("#comment-subject").addClass("field-error");
			return;
		}
		
		if ( body.length<=0 || body == null || body =='' || !isNaN(body) ) {
			$("#comment-error").html("Please enter a message body.");
			$("#comment-body").addClass("field-error");
			return;
		}			
		
		if ( body.length > MAX_COMMENT_CHAR ) {
			$("#comment-error").html("Sorry. The message body cannot be any longer than "+ MAX_COMMENT_CHAR +" characters.");
			$("#comment-body").addClass("field-error");
			return;
		}
		
		subject = escape(subject);
		body = escape(body);

		billboard.social.createMessageBoard( contentId, billboard.user.username, subject, body , function(response) { 
			billboard.log( "Comment add discussion result " );
			//billboard.logObject( response );
			/* this is now down when the message board is created....
			// if successful, add a new comment to the newly created message board
			var id;
			if ( response.error_code == 0 ) {
				id = response.board.id;
				me.addComment( me.contentId, body, id );
			}
			*/
			me.getDiscussionCounts();
			me.clearForms();
			me.load();	
			if(billboard.section !='forums') //no facebook publish for forums
			 billboard.facebook.publish("conversation",realSubject);
		});
		
		
		/* NESTED COMMENT IMPLEMENTATION
		billboard.social.addComment( contentId, subject, body, null, function(response) { 
			billboard.log( "comment add discussion result " );
			// add some rating here to get the count of dicussions....
			//billboard.social.rate( contentId, "comment", "Default",  );
			me.clearForms();
			me.load();
		});
		*/
									 
		/* MessageBoard IMPLEMENTATION :-(
		billboard.social.createMessageBoard( contentId, subject, body , function(response) { 
			billboard.log( "Comment add discussion result " );
			billboard.logObject( response );
			// if successful, add a new comment to the newly created message board
			var id;
			if ( response.error_code == 0 ) {
				id = response.board.id;
				me.addComment( me.contentId, body, id );
			}
			$(".comment-add").hide();
			me.load();		
		});
		*/
	};
	
	me.addComment = function( contentId, body, parent )
	{
		billboard.log( "Comment.addComment("+contentId+", "+body +")");
		if ( !me.posting ) { 
			
			if ( body.length<=0 || body == null || body =='' || !isNaN(body)  ) {
				$("#comment-error").html("Please enter a message body.");
				$("#comment-body").addClass("field-error");
				return;
			}			
			
			if ( body.length > MAX_COMMENT_CHAR ) {
				$("#comment-error").html("Sorry. The message body cannot be any longer than "+ MAX_COMMENT_CHAR +" characters.");
				$("#comment-body").addClass("field-error");
				return;
			}
			
			var realComment = body;
			body = escape(body);
			var subject = escape(subject);
			parent = parent?parent:$("#conversation-id").text();
			
			me.posting = true;

			billboard.social.addComment( contentId, subject, body, parent, function(response) {

				//
				me.clearForms();

				// load the comments back

				me.load();
				
				// if this is profile page, shoot an email out
				if ( billboard.section == "profile" ) {
					var url = URL_BB_PROFILE_COMMENT_EMAIL;
					var username = billboard.publicUser;
					var comment = body;
					url = url + "username="+username+"&comment="+comment;
					$.getJSON( url, function( data ) { 
						billboard.log( "email result" );
						//billboard.log( data );
					});
				}
				/* if this is NEST COMMENT implementation, lets add a rating to try to track reply counts
				else if ( typeof parent != "undefined" ) {
					// this is a comment on a artist converstatio...so add a rating to track
					// replies....
					billboard.social.rate( parent, "comment", "Default", 1, function(response) {
						billboard.log( response );
					});
				}
				*/
				if(billboard.section !='forums') //no facebook publish for forums
				 billboard.facebook.publish("comment",realComment,me.conversationTitle);
				googleA.trackSocialEvent("Commented");

				// Now pop-up the Facebook
			/*	if (FB.Connect.get_loggedInUser() != null) {
					FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(permissions){
						
						if(permissions == 1) {
							
							//var result = FB.Connect.showFeedDialog(103509064440, null, null, body, null, FB.RequireConnect.require, function(){}, "Add custom message here", "");
							FB.Connect.streamPublish("commented on Billboard.com",{"name":"Comment:","href":location.href,"description":realComment},[{"text":"Visit the new Billboard.com","href":"http://www.billboard.com"}],null,null,function(){},true);
						}						
						
					});
						
				}			*/		
				me.posting = false;
				
			});
		}
		return false;
	};
	
})(jQuery);


