/**
 * @author gsandrigo
 * v2.05
 */

var mcs = new DynamicStatsServices();
var postReply = true;
var postedPopUpMessage = "<span style=\"font-family:verdana;font-size:10px;color:#000;\">Your comment has been received.<br>It will be posted shortly.</span>";
var xpos = 0;
var ypos = 0;
var TimeoutID;

var lastsubject = "";
var lastcomment = "";
var lastcommentreplyid;

var openReplies = -1;

var fromId = document.cookie;
var spamJson = new BreakJSON();

function ShowLinkbackBox(){
	var linkbackBox = document.getElementById("linkback_box");

	if(linkbackBox.style.display == "none"){
		linkbackBox.style.display = "block";
	}
	else{
		linkbackBox.style.display = "none";
	}
}

function getDynamicStats(contentId) {
	BrowserDetect.init();
	mcs.postGetDynamicStats(contentId, postDynamicStatsCallback);
}

function postDynamicStatsCallback(XmlDoc, isOk){
	
	if(!isOk) {
      //error display default
	  documentWriter("comment_bot", renderDefultComments());
	  return;
   }
   
   document.getElementById("comment_bot").innerHTML = "";

   var error = "parsing JSON.";
   try {
   		if (BrowserDetect.browser == "Firefox")
   			XmlDoc.normalize();
   		var messageNode = XmlDoc.getElementsByTagName("Message");

		var jsonDoc;
        jsonDoc = messageNode[0].firstChild.nodeValue;

		var objResp = eval('(' + jsonDoc + ')');

		error = "processing renderPosted";
		if (undefined != objResp.DynamicStats.Stats){
        	documentWriter("posted_box", renderPosted(objResp.DynamicStats.Stats));
		}

        error = "processing renderViews";
		if (undefined != objResp.DynamicStats.Stats){
        	documentWriter("stats_views", renderViews(objResp.DynamicStats.Stats));
        }

        error = "processing renderCommentCount";
		if (undefined != objResp.DynamicStats.Stats){
			var commentsDiv = 'stats_comments_uml';
			if(isUGC == false && whichReferrer != 'google') {
				commentsDiv = 'stats_comments';
			}
        	documentWriter(commentsDiv, renderCommentCount(objResp.DynamicStats.Stats));
        }
        
        error = "processing renderLowerCommentCount";
			if (undefined != objResp.DynamicStats.Stats){
			documentWriter("comments_count", renderLowerCommentCount(objResp.DynamicStats.Stats));
        }

		error = "processing renderComments";
        //documentWriter("comments_box", renderComments(objResp.DynamicStats.CommentsDetail.Comment));
		if (undefined != objResp.DynamicStats.CommentsDetail){
		    
			currentComments = objResp.DynamicStats.CommentsDetail.Comment;
			renderComments(currentComments);
        }
		else{
			documentWriter("comment_bot", renderDefultComments());
		}
		var showComments = getCookie('showcommentsalltime');
	    if(showComments == 1){
 	        document.getElementById("chk_comments").checked = true;
	        toggleBox('disable_comment_box',0);
		    toggleBox('comment_bot',1);
		}
		var feaThumbsCookie = getCookie('showfeathumbs');
		if(feaThumbsCookie == 1){
			toggleBox('featured_hide',0);
			toggleBox('featured_bot',0);
			toggleBox('featured_show',1);
		}
		var recThumbsCookie = getCookie('showrecthumbs');
		if(recThumbsCookie == 1){
			toggleBox('recommended_hide',0);
			toggleBox('recommended_bot',0);
			toggleBox('recommended_show',1);
		}

        error = "processing linkbacks";
		if (undefined != objResp.DynamicStats.Linkbacks){
			renderLinkbacks(objResp.DynamicStats.Linkbacks.Linkback);
		}
		else{
			renderDefaultLinkbacks();
		}	
	}


   catch(e){
        //alert("error " + error + " - " + e);
   }
   return;
}

function renderDefultComments(){
	var html = "";
	html += "No Comments.";
	return html;
}

function renderViews(stats){
	var html = "";
	html += placeCommasInNumber(stats.Views);
	return html;
}

function renderCommentCount(stats){
	var html = "";
	html += stats.Comments;
	return html;
}


function renderLowerCommentCount(stats){
	if(parseInt(stats.Comments) == 0)
	   return "0 Comments";
	   
	if(parseInt(stats.Comments) < 11)
	   return "1 - " + parseInt(stats.Comments) + " of " + parseInt(stats.Comments) + " Comments";
	else
	   return "1 - 10 of " + parseInt(stats.Comments) + " Comments";
}

function renderPosted(stats){
	var html = "";
	html += stats.Posted;
	return html;
}

function renderDefaultLinkbacks(){
	document.getElementById("linkback_box_nocontent").style.display = "block";
}

function renderLinkbacks(linkbacks){
	var linkbackBox = document.getElementById("linkback_box_content");
	linkbackBox.style.display = "block";

	var linkbackContent = document.getElementById("linkback_box_content_div");
	linkbackContent.innerHTML = "";

	var linkbackArr = new Array();

	if(typeof(linkbacks.length) == "undefined")
		linkbackArr[0] = linkbacks;
	else
		linkbackArr = linkbacks;

	if (linkbackArr.length > 0){
		for(i = 0; i < linkbackArr.length; i++){
			var text = linkbackArr[i].ReferrerURL;
			if(text.length > 55)
				text = text.substring(0, 55) + "...";

			linkbackContent.innerHTML += "<div><span class='linkback_views'>" + linkbackArr[i].Views + "</span> views via <a href=\"" + linkbackArr[i].ReferrerURL + "\">" + text + "</a></div>";
		}
	}
}

function renderComments(comments){
	var isChild = false;
	var isReply = false;
	var parent_node;
	var pendingChildren = new Array();

	if (comments.length > 0){
		//var bottom_border = document.getElementById("comments_divider_bottom");
		//bottom_border.style.visibility = "visible";
		var element = document.getElementById("comment_bot");
		for(i = 0; i < comments.length; i++){
			isChild = (comments[i].ContentCommentID == comments[i].ParentContentCommentID) ? false : true;
			node = document.createElement("div");
			if(isChild){
				node.innerHTML = buildReplyComment(comments[i].ContentCommentID, comments[i].DateCreated, comments[i].ByNickName, comments[i].ByAvatarURL, comments[i].Title, comments[i].DiscussionText);
				parent_node = document.getElementById("comment" + comments[i].ParentContentCommentID);
				if(parent_node != null){
					document.getElementById("container" + comments[i].ParentContentCommentID).appendChild(node);
	               			//parentContainer = document.getElementById("container" + comments[i].ParentContentCommentID);
	               			//parentContainer.insertBefore(node, parentContainer.firstChild);
	               }
	            else{
					if(typeof(pendingChildren[comments[i].ParentContentCommentID]) == 'undefined')
	                  pendingChildren[comments[i].ParentContentCommentID] = new Array();

	               pendingChildren[comments[i].ParentContentCommentID].push(node);
	            }
	         }
	         else{
	            node.innerHTML = buildComment(comments[i].ContentCommentID, comments[i].DateCreated, comments[i].ByNickName, comments[i].ByAvatarURL, comments[i].Title, comments[i].DiscussionText);
	            if(isReply)
	               element.insertBefore(node, element.firstChild);
	            else
	               element.appendChild(node);
			}
		}

		var morecomments = document.createElement("div");
		morecomments.setAttribute("class", "module_comment_ctrl");
		morecomments.setAttribute("className", "module_comment_ctrl");
		morecomments.innerHTML = "<a href=\"http://my.break.com/Content/Comment/ContentComment.aspx?ContentID=" + sGlobalContentID + "\">View All</a>";
		element.appendChild(morecomments);
		
		for(var key in pendingChildren){
	         try{
	            if(document.getElementById("container"+key) != null){
	               for(i=0; i<pendingChildren[key].length; i++)
	                  document.getElementById("container"+key).appendChild(pendingChildren[key][i]);
	            }
	         }
	         catch(e){
	            //discard it, we can't do anything with it anyways
	            continue;
	         }
	    }
	}
	else if(comments.ContentCommentID){
		//var bottom_border = document.getElementById("comments_divider_bottom");
		//bottom_border.style.visibility = "visible";
		var element = document.getElementById("comment_bot");
		node = document.createElement("div");
		node.innerHTML = buildComment(comments.ContentCommentID, comments.DateCreated, comments.ByNickName, comments.ByAvatarURL, comments.Title, comments.DiscussionText);
		element.appendChild(node);
	}
}

function documentWriter(divId, html){
	var div = document.getElementById(divId);
	if (div)
	{
		div.innerHTML = html;
	}
}

function buildComment(commentId, date, by, avatar, title, text){
   var html = "";
   title = unescape(title);
   text = unescape(text);

	html += "<div class=\"comment_entry\" id=\"comment" + commentId + "\">";
	html += "<div class=\"comment_avatar\"><a href=\"http://break.com/" +by+ "\"><img src=\"" + avatar + "\" border=\"0\" width=\"50\" height=\"50\" class=\"comment_avatar\" onerror=\"onMissingAvatar(this)\" /></a></div>";
	html += "<div class=\"comment_nonavatar\">";
	html += "<div class=\"comment_entry_top\">";
	html += "<div class=\"comment_entry_date\">";
	html +=  GetSpamLink(commentId)  + date;
	if(canPost){
		html += " <a id=\"reply" +commentId+ "\" href=\"javascript:toggleBox('newPopup_post_reply" +commentId+ "', 1);javascript:toggleBox('post_box', 0); closeOpenReplies(" + commentId + ");\">REPLY</a>";
	}
	html += "</div>";
	//html += "<a href=\"http://break.com/" +by+ "\"><img src=\"" + avatar + "\" border=\"0\" width=\"18\" height=\"17\" onerror=\"onMissingAvatar(this)\" /></a>&nbsp;";
	html += "<a href=\"http://break.com/" +by+ "\" class=\"comment_entry_link\">" + by +"</a> says:";
	html += "</div>";
	html += "<div class=\"comment_entry_bot\">";
	html += "<div class=\"comment_quote_lft\">";
	html += "<img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif\" border=\"0\" />";
	html += "</div>";
	html += "<div class=\"comment_quote\">" + text + "</div>";
	html += "<div class=\"comment_quote_rgt\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif\" border=\"0\" /></div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "<!-- COMMENT REPLY start -->";
	html += "<div id=\"newPopup_post_reply" + commentId + "\" class=\"post_box\">";
	html += "<div class=\"post_box_wrap\">";
	html += "<a href=\"javascript:toggleBox('newPopup_post_reply" + commentId + "',0);\" class=\"comment_entry_link_sml\">Close</a><br /><br />";
	html += "<input type=\"button\" value=\"Post\" onclick=\"javascript:submitReplyComment(" + commentId + ");\" /><br />";
	html += "</div>";
	html += "<textarea class=\"post_text\" id=\"post_text" + commentId + "\"></textarea><div id=\"commentReplyBodyError"+ commentId + "\"></div>";
	html += "</div>";
	html += "<!-- COMMENT REPLY end -->";
	html += "<div id=\"container" + commentId + "\" style=\"padding-top:0;margin-top:0;\">";
   
   return html;
}


function buildReplyComment(commentId, date, by, avatar, title, text){
   
   var html = "";

   title = unescape(title);
   text = unescape(text);

	html += "<div class=\"comment_entry_sml\" id=\"comment" +commentId+ "\">";
	html += "<div class=\"comment_avatar\"><a href=\"#\"><img src=\"" + avatar + "\" border=\"0\" width=\"50\" height=\"50\" class=\"comment_avatar\" onerror=\"onMissingAvatar(this)\" /></a></div>";
	html += "<div class=\"comment_nonavatar2\">";
	html += "<div class=\"comment_entry_top_sml\">";
	html += "<div class=\"comment_entry_date\"> " + GetSpamLink(commentId)  + date + " </div>";
	html += "<a href=\"http://break.com/" +by+ "\" class=\"comment_entry_link\">" + by +"</a> says:";
	html += "</div>";
	html += "<div class=\"comment_entry_bot_sml\">";
	html += "<div class=\"comment_quote_lft\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif\" border=\"0\" /></div>";
	html += "<div class=\"comment_quote_sml\">";
	html += text;
	html += "</div>";
	html += "<div class=\"comment_quote_rgt\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif\" border=\"0\" /></div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";  
   return html;
}

function GetSpamLink(commentId){
	var link = "";

	  if(canPost != ""){
      	   	link = "[ " + "<a href='javascript:SentSpam(" + commentId + ");'>spam</a>" + " ] ";
      	  }

	return link;
}

function SentSpam(commentId){
	var fromId = getEncodedMemberID();

	 spamJson.sendBegin("http://websvc.break.com/cms/Handlers/Spam/SpamHandler.ashx?invoke=reportcomment&memberId=" +fromId+ "&commentId=" + commentId, "updateCommentSpam");

}

function updateCommentSpam(jsonData){
	alert("Thank you for Marking as Spam.");
}



function closeOpenReplies(commentId)
{
    if(openReplies > -1 && openReplies != commentId)
    {
        toggleBox("newPopup_post_reply" + openReplies, 0);
    }
    openReplies = commentId;
}

function onMissingAvatar(img){
   img.src = "http://media1.break.com/static/live/v1/img/site/avatar_mini.gif";
}

function IsMeaningless(str){
	var tempStr = str.split(" ");
	for (i = 0; i < tempStr.length; i++)
	{
		if(tempStr[i] != "")
		{
			return false;
		}
	}
	return true;
}

function submitReplyComment(commentReplyId){
	var subject = "";
	var comment = "";
	var isInError = false;
	var fromId = getEncodedMemberID();

	comment = document.getElementById("post_text" + commentReplyId).value;

	if(comment == ""  || IsMeaningless(comment)) {
	   displayMessage("commentReplyBodyError" + commentReplyId, "You must specify a comment.");
	   isInError = true;
	}

	if(isInError)
	   return;

	hideReplyMessage(commentReplyId);
	toggleBox("newPopup_post_reply" + commentReplyId, 0);
	//hideReplyBox();
	mcs.postContentComment(siteId, fromId, sGlobalContentID, commentReplyId, subject, comment, postContentCommentCallback);
	lastcomment = comment;
    lastcommentreplyid = commentReplyId;
    lastsubject = subject;
}

function submitComment(){
	
	var subject = "";
	var comment = "";
	var isInError = false;
	var fromId = getEncodedMemberID();

	comment = document.getElementById("taReplyComments").value;
	if(comment == "" || IsMeaningless(comment)) {
	   displayMessage("commentBodyReplyError", "You must specify a comment.");
	   isInError = true;
	}

	if (fromId == null)
		isInError = true;
	
	if(isInError)
	   return;

	hideMessage();
	toggleBox('post_box', 0);
	mcs.postContentComment(siteId, fromId, sGlobalContentID, 0, subject, comment, postContentCommentCallback);
	lastcomment = comment;
    lastcommentreplyid = 0;
    lastsubject = subject;
}

function insertComment(commentReplyId, subject, comment, avatar, nickName){
	if(nickName == "")
		nickName = "You";
	var htmlNode;
	if (avatar == "")
		avatar = "http://media1.break.com/dnet/media/AVATARS/NeutralAvatar.jpg";


	var date = new Date();
	var dateString = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
	var hs = date.getHours()
	var meridian = hs < 12 ? "AM" : "PM";
	if (hs > 12) {hs = hs-12;}

	dateString += " " + hs + ":" + date.getMinutes() + ":" + date.getSeconds() + " " + meridian;

	if(commentReplyId == 0){
		var tempstate = canPost;
		canPost = false;
		htmlNode = buildComment(0, dateString, nickName, avatar, subject, comment);
		canPost = tempstate;
		var commentBox = document.getElementById("comment_bot").innerHTML;
		commentBox = htmlNode + commentBox;
		document.getElementById("comment_bot").innerHTML = commentBox;
	}
	else{
		htmlNode = buildReplyComment(1, dateString, nickName, avatar, subject, comment);
		var containerNode = document.getElementById("container" + commentReplyId);
		var containerHTML = htmlNode + containerNode.innerHTML ;
		containerNode.innerHTML = containerHTML;
	}
	var bottom_border = document.getElementById("comments_divider_bottom");
	bottom_border.style.visibility = "visible";
}


function closeAllotherBoxes(){
	try{
		hideBox('popup_box_share',0);
	}
	catch(e){
		//alert("popup_box_share" + e);
	}
	try{
		hideBox('popup_box_embed',0);
	}
	catch(e){
		//alert("popup_box_embed" + e);
	}
	try{
		hideBox('popup_box_add',0);
	}
	catch(e){
		//alert("popup_box_add" + e);
	}
}

function displayMessage(divId, messageText){
   document.getElementById(divId).innerHTML = messageText;
   document.getElementById(divId).style.display="block";
}

function hideMessage() {
   document.getElementById("commentBodyReplyError").style.display="none";
   //document.getElementById("subjectReplyError").style.display="none";
}

function hideReplyMessage(commentId) {
   document.getElementById("commentReplyBodyError" + commentId).style.display="none";
   //document.getElementById("commentReplySubjectError" + commentId).style.display="none";
}

function postContentCommentCallback (xmlDoc, isOk) {
   if(!isOk) {
      //displayMessage("genericError", "Error saving comment.");
      return;
   }

   try {
      var responseNode = xmlDoc.documentElement;

      if(responseNode.getAttribute("Code")<0) {
		 if(responseNode.getAttribute("Code") < -2){
			displayMessage("genericError", responseNode.getAttribute("Message"));
			}
      }
	  else {
	  //document.getElementById("iReplySubject").value = "";
      document.getElementById("taReplyComments").value = "";

	  var avatar;
	  var nickName;
      var node = xmlDoc.documentElement;

	  for (i = 0; i < node.childNodes.length; i++)
	  {
	 		if (node.childNodes[i].nodeName == "avatarURL")
			{
				avatar = node.childNodes[i].firstChild.nodeValue;
			}
			else if (node.childNodes[i].nodeName == "memberNickname")
			{
				nickName = node.childNodes[i].firstChild.nodeValue;
			}
	  }
	  clearDefaultComment();
	  insertComment(lastcommentreplyid, lastsubject, lastcomment, avatar, nickName);
  	  }
      return;
   }
   catch(e) {
		document.getElementById("taReplyComments").value = "";
   }
}

function getEncodedMemberID(){
          var memberIdCookie = getCookie("MemberID");
          if(memberIdCookie != null)
            return memberIdCookie;
          else
            return null;
}

function placeCommasInNumber(number)
{
	number = '' + number;
	if (number.length > 3) {
	var mod = number.length % 3;
	var output = (mod > 0 ? (number.substring(0,mod)) : '');
	for (i=0 ; i < Math.floor(number.length / 3); i++) {
	if ((mod == 0) && (i == 0))
	output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
	else
	output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
	}
	return (output);
	}
	else return number;
}

function isThisFirstComment(div){
	if(div.text() == "No Comments."){
		return true;
	}
	else{
		return false;
	}
}
function clearDefaultComment(){
	var div = jQuery("#comment_bot");
	if(isThisFirstComment(div)){
		div.empty();
	}
}


