﻿// JScript File


function displayRow(obj){
	var row = document.getElementById(obj);
	if (row.style.display == '') row.style.display = 'none';
	else row.style.display = '';
}
function changeText(fieldObj, newLinkText) {
	if (newLinkText == fieldObj.innerHTML) {
		fieldObj.innerHTML = oldLinkText;
	} else {
		oldLinkText = fieldObj.innerHTML;
		fieldObj.innerHTML = newLinkText;
	}
}



function CommentsPager (varName, contentId, commentsArray, userIsAnonymous, UserIsAdmin, pageIndex, pageSize, pageGroupSize, displayReplies, gotoComment, gotoReply)
{ 
  this.VarName = varName;
  this.ContentId = contentId;
  this.PageIndex = 1;
  this.PageGroupStart = -1;
  this.PageSize = 10;
  this.PageGroupSize = 10;
  this.TotalPages = 0;
  this.TotalRecords = 0;
  this.DisplayReplies = 5;
  this.OrderBy = "PostDate";
  this.UserIsAnonymous = true;
  this.UserIsAdmin = false;

  this.Init = function(commentsArray, userIsAnonymous, UserIsAdmin, pageIndex, pageSize, pageGroupSize, displayReplies, gotoComment, gotoReply)
  {
	 if (pageIndex != null) this.PageIndex = pageIndex;
	 if (pageSize != null) this.PageSize = pageSize;
	 if (pageGroupSize != null) this.PageGroupSize = pageGroupSize;
	 if (displayReplies != null) this.DisplayReplies = displayReplies;
	 if (userIsAnonymous != null) this.UserIsAnonymous = userIsAnonymous;
	 if (UserIsAdmin != null) this.UserIsAdmin = UserIsAdmin;
	 
	 if (commentsArray && commentsArray.length >= 1) {	 
  	 
		var PagerOrderTopContainer = document.getElementById("PagerOrderTopContainer");
		if (PagerOrderTopContainer) PagerOrderTopContainer.style.display = ""; 
		var PagerOrderBottomContainer = document.getElementById("PagerOrderBottomContainer");
		if (PagerOrderBottomContainer) PagerOrderBottomContainer.style.display = ""; 
		
		//var PagerNumCommentsContainer = document.getElementById("PagerNumCommentsContainer");
		//PagerNumCommentsContainer.innerHTML = commentsArray[0].TotalDisplayComments ? ( commentsArray[0].TotalDisplayComments + " Coment&aacute;rio" + ( 1*commentsArray[0].TotalDisplayComments != 1 ? "s" : "" ) ) : "Comentários";
		this.PagerTitleTopContainer = document.getElementById("PagerTitleTopContainer");
		this.PagerTitleBottomContainer = document.getElementById("PagerTitleBottomContainer");
		
  		var aux = null;
  		var PagerLinksTopContainer = document.getElementById("PagerLinksTopContainer");
  		var PagerLinksBottomContainer = document.getElementById("PagerLinksBottomContainer");
  		
  		this.GroupPreviousContainers = new Array();
  		this.PagePreviousContainers = new Array();
  		aux = GetDescendant(PagerLinksTopContainer, "previousPageGroup", "span")
  		if (aux) this.GroupPreviousContainers.push(aux);
  		aux = GetDescendant(PagerLinksTopContainer, "previousPage", "span")
  		if (aux) this.PagePreviousContainers.push(aux);
  		aux = GetDescendant(PagerLinksBottomContainer, "previousPageGroup", "span")
  		if (aux) this.GroupPreviousContainers.push(aux);
  		aux = GetDescendant(PagerLinksBottomContainer, "previousPage", "span")
  		if (aux) this.PagePreviousContainers.push(aux);
  	 
  		this.GroupNextContainers = new Array();
  		this.PageNextContainers = new Array();
  		aux = GetDescendant(PagerLinksTopContainer, "nextPageGroup", "span")
  		if (aux) this.GroupNextContainers.push(aux);
  		aux = GetDescendant(PagerLinksTopContainer, "nextPage", "span")
  		if (aux) this.PageNextContainers.push(aux);
  		aux = GetDescendant(PagerLinksBottomContainer, "nextPageGroup", "span")
  		if (aux) this.GroupNextContainers.push(aux);
  		aux = GetDescendant(PagerLinksBottomContainer, "nextPage", "span")
  		if (aux) this.PageNextContainers.push(aux);
  	 
  		this.PageNumbersContainers = new Array();
  		aux = GetDescendant(PagerLinksTopContainer, "pages", "span")
  		if (aux) this.PageNumbersContainers.push(aux);
  		aux = GetDescendant(PagerLinksBottomContainer, "pages", "span")
  		if (aux) this.PageNumbersContainers.push(aux);
  		
  		this.CommentForm = document.getElementById("CommentForm");
		this.txtPostID = GetDescendantById(this.CommentForm, "txtPostID", "input");
		this.txtDisplayName = GetDescendantById(this.CommentForm, "txtDisplayName", "input");
		this.txtUserEmail = GetDescendantById(this.CommentForm, "txtUserEmail", "input");
		this.txtCommentText = GetDescendantById(this.CommentForm, "txtCommentText", "input");
		this.chkGetFeedback = GetDescendantById(this.CommentForm, "chkGetFeedback", "input");
		this.chkPostAsAnonymous = GetDescendantById(this.CommentForm, "chkPostAsAnonymous", "input");
		this.publishComment = GetDescendantById(this.CommentForm, "publishComment", "input"); 

  		var CommentFormEditor = document.getElementById("CommentFormEditor");
  		if (CommentFormEditor) {
  		  var CommentFormEditorTxtPostID = GetDescendant(CommentFormEditor, "txtPostID", "input");
  		  if (CommentFormEditorTxtPostID) CommentFormEditorTxtPostID.value = commentsArray[0].PostID;
		}
  		this.CommentsListContainer = document.getElementById("CommentsListContainer");
  		
  		this.CommentsOrderByPostDate = document.getElementById("CommentsOrderByPostDate"); 
  		this.CommentsOrderByNumReplies = document.getElementById("CommentsOrderByNumReplies");
  	 
  		this.SetPage(commentsArray, true);
  		
  		var objGoto = null;
  		
  		var jumptoComments = GetQueryStringValue("jump");
  		
  		if (jumptoComments)
  		{
  		  JumpTo('CommentFormEditor');
  		}
  		else{
  		
  		  if ( gotoReply>0 ) objGoto = document.getElementById("PostReply" + gotoReply);
  		  else if ( gotoComment>0 ) objGoto = document.getElementById("PostComment" + gotoComment);
  		  if (objGoto) 
  			 if (IsWebkitPreviousVersions()) scrollY (objGoto, true);
  			 else objGoto.scrollIntoView(true);
    		  
  		  if (IsIE()) {
  			 var brLogin = document.getElementById("clearBRLogin");
  			 if (brLogin) brLogin.style.display = "none";
  		  } 
  		} 
  		
	 }
  }

  this.SetOrderBy = function(orderBy)
  {
	 if (orderBy != this.OrderBy) {
	   this.OrderBy = orderBy;
	   this.CommentsOrderByPostDate.className = ( orderBy == "PostDate" ? "on" : "off" ); 
  		this.CommentsOrderByNumReplies.className = ( orderBy == "PostDate" ? "off" : "on" ); 
		this.GotoPage(this.PageIndex);
	 }
  }

  this.GotoPreviousPageGroup = function()
  {
	 this.GotoPage(this.PageGroupStart - this.PageGroupSize);
  }
  this.GotoNextPageGroup = function()
  {
	 this.GotoPage(this.PageGroupStart + this.PageGroupSize);
  }
  this.GotoPreviousPage = function()
  {
	 this.GotoPage(this.PageIndex - 1);
  }
  this.GotoNextPage = function()
  {
	 this.GotoPage(this.PageIndex + 1);
  }

  this.GotoPage = function (page)
  {
    var url = "/common/services/CommentsGetPage.aspx?pagesize=" + this.PageSize + 
		        "&sort_by=" + this.OrderBy + "&page=" + page + "&content_id=" + this.ContentId;
    var func = this.VarName + ".SetPagePrep";
    AssyncContentFunc(url, func);
  }
  

  this.ClaimInappropriate = function(obj, CommentID)
  {
	 obj.parentNode.style.visibility = "hidden";
    var url = "/Common/Services/CommentReportAsImproper.aspx?post_id=" + CommentID;
    var func = this.VarName + ".ClaimInappropriateResponse";
    AssyncContentFunc(url, func);

  }
  
  this.ClaimInappropriateResponse = function(responseText)
  {
	 if (1*responseText > 0) alert("Comentário denunciado");
	 else alert("Ocorreu um erro. Tente mais tarde");
  }
  
  this.SetPagePrep = function(commentsArrayStr)
  {
	  var objGoto = document.getElementById("AreaComentarios");
	
	  if (objGoto == "") {
		var x = 0;
		var divs = document.getElementsByTagName("div");
		for (var k=0; k<divs.length; k++) {
		  var id = GetElementAttribute(divs[k], "id").toString();
		  if ( id.indexOf("AreaComentarios")>=0 ){
			 objGoto = divs[k];
			 break;
		  }
		}   
	  }
	  if (objGoto) 
		 if (IsWebkit()) scrollY (objGoto, true);
		 else objGoto.scrollIntoView(true);
  		  
	  this.SetPage (eval(commentsArrayStr));
  }

  this.SetPage = function(commentsArray, is_init)
  {
	 this.TotalPages = commentsArray[0].TotalPages;
	 this.TotalRecords = commentsArray[0].TotalComments;
	 var pagePreviousIndex = this.PageIndex;
	 this.PageIndex = commentsArray[0].PageIndex;
	 var wrapper = document.getElementById("ListCommentsWrapper");
	 
	 if ( this.TotalRecords == 0 ) {
		if (wrapper) wrapper.style.display = "none";
	 }
	 else {
	 
	   var k, j;
	   if (  this.PageGroupStart < this.PageIndex || this.PageGroupStart + this.PageGroupSize > this.PageIndex ){
        this.PageGroupStart = this.PageGroupSize * Math.floor( (this.PageIndex-1) / this.PageGroupSize ) + 1;
        for (k=0; k<this.GroupPreviousContainers.length; k++)
		    this.GroupPreviousContainers[k].style.display = (this.PageGroupStart == 1 ? "none" : ""); 
	     for (k=0; k<this.GroupNextContainers.length; k++){
		    this.GroupNextContainers[k].style.display = (this.PageGroupStart + this.PageGroupSize > this.TotalPages ? "none" : ""); 
		  }
		  var topaux = ( this.TotalPages > this.PageGroupStart + this.PageGroupSize - 1 ? this.PageGroupStart + this.PageGroupSize : this.TotalPages + 1 ); 
	     for (k=0; k<this.PageNumbersContainers.length; k++){
		    this.PageNumbersContainers[k].innerHTML = ""; 
		    for (j=this.PageGroupStart; j<topaux; j++) {
			   this.PageNumbersContainers[k].innerHTML += "<a href=\"javascript:commentsPager.GotoPage(" + j + ")\">" + j + "</a>";
			   if (j<topaux-1) this.PageNumbersContainers[k].innerHTML += "|";
		    }
		  }
	   }
	   if ( (this.PageIndex == 1 && pagePreviousIndex != 1) || (this.PageIndex != 1 && pagePreviousIndex == 1) )
        for (k=0; k<this.PagePreviousContainers.length; k++)
		    this.PagePreviousContainers[k].style.display = (this.PageIndex == 1 ? "none" : ""); 
	   if ( is_init || (this.PageIndex == this.TotalPages && pagePreviousIndex != this.TotalPages) || (this.PageIndex != this.TotalPages && pagePreviousIndex == this.TotalPages) )
        for (k=0; k<this.GroupNextContainers.length; k++)
		    this.PageNextContainers[k].style.display = (this.PageIndex == this.TotalPages ? "none" : ""); 

	   var pgTitle = "P&aacute;gina " + this.PageIndex + "/" + this.TotalPages;
	   this.PagerTitleTopContainer.innerHTML = pgTitle
	   this.PagerTitleBottomContainer.innerHTML = pgTitle;
  	 
	   this.CommentsListContainer.innerHTML = "";
	   for (k=0; k<commentsArray[0].ListComments.length; k++)
		  this.CommentsListContainer.innerHTML += this.CommentHTML(commentsArray[0].ListComments[k]);
	  }
	  
  }



  this.CommentHTML = function(comment)
  {
    var html = "<div id=\"PostComment" + comment.CommentID + "\" class=\"CommentItem_Parent\">" +
    	  this.CommentCommonHTML(comment, true) +
    	  this.ReplyFormHTML(comment.CommentID) +
		"</div>";   
    var k, moreReplies = false;
    for (k=0; k<comment.ListReplies.length; k++){
		if ( k == this.DisplayReplies ){
		  moreReplies = true;
		  html += "<div id=\"moreChilds" + comment.CommentID + "\" style=\"display:none\">";
		}
		html += this.ReplyHTML (comment.ListReplies[k], comment.CommentID);
    }
	 if (moreReplies) html += "</div><div class=\"SeeReplies\">" +
		"<a href=\"javascript:displayRow('moreChilds" + comment.CommentID + "')\" " +
		    "onclick=\"changeText(this,'Ver menos respostas &raquo;')\">" +
				"Ver mais respostas &raquo;" +
	   "</a></div>";
    return html;
  }

  this.ReplyHTML = function(reply, commentID)
  {
		return "<div id=\"PostReply" + reply.CommentID + "\" class=\"CommentItem_Child\">" +
    	  this.CommentCommonHTML(reply, false, commentID) +
		"</div>";    
  }

  this.CommentCommonHTML = function(comment, showReplyForm, commentID)
  {
	 //var mailStr = GetLocationValue() + "?content_id=" + this.ContentId + 
	 //       "&postref_id=" + (commentID ? commentID + "&postreply_id=" : "") + comment.CommentID;
	        
	 var mailStr = "&postref_id=" + (commentID ? commentID + "&postreply_id=" : "") + comment.CommentID;
	 var linkStr = escape(ReplaceQueryStringValue("postref_id", (commentID ? commentID + "&postreply_id=" : "") + comment.CommentID));
	 var registeredTitle = "Utilizador " + ( comment.UserIsAnonymous ? "Não " : "" ) + "Registado";
	 return "" +
    	"<div class=\"LeftWrap\">" +
    	  "<table cellpadding='0' cellspacing='0'>" +
    	  "<tr title='" + registeredTitle + "'>" +
    		 "<td valign='top'>" +
    			"<img class='type_comment' src='/common/images/icons/comment_" + ( comment.UserIsAnonymous ? "un" : "" ) + "registered.gif' width='15' height='14' alt='" + registeredTitle + "'/>" +
    		 "</td>" +
    		 "<td valign='top'>" +
    			"<h1>" + ( comment.PostAsAnonymous ? "Anónimo" : comment.DisplayName) + "</h1>" +
    			"<h2>" + comment.CommentDate + "</h2>" +
    			( comment.PostAsAnonymous || comment.UserLocation == "" ? "" : "<h3>" + comment.UserLocation + "</h3>" ) +
    		 "</td>" +
    		"</tr>" +
    		"</table>" +
    	"</div>" +
      "<div class=\"RightWrap\">" +
        ( showReplyForm ? "<ul class=\"round\">" +
            "<li><a href=\"javascript:displayRow('ReplyForm" + comment.CommentID + "')\"><b></b><span>Responder</span><b></b></a></li>" +
        "</ul>" : "" ) +
        "<div class=\"ShareItBar\"><span>Partilhar: </span>" +
			 "<a href=\"javascript:SendNews(null, null, '" + mailStr + "')\">Email</a> | " +
			 "<a href=\"http://www.facebook.com/sharer.php?u=" + linkStr + "\" title=\"Partilhar comentário no Facebook\" target=\"_blank\">Facebook</a> | " +
			 "<a href=\"http://twitter.com/home?status=" + linkStr + "\" title=\"Partilhar comentário no Twitter\" target=\"_blank\">Twitter</a></div>" +
        "<div class=\"CommentDelation\">" +
			 ( this.UserIsAdmin ?
				"<a href=\"" + comment.DeleteLink + "\">apagar coment&aacute;rio &raquo;</a>" :
				"<a href=\"javascript:Empty()\" onclick=\"commentsPager.ClaimInappropriate(this, " + comment.CommentID + ")\">denunciar este coment&aacute;rio &raquo;</a>" 
			 ) +
		  "</div>" +
      "</div>" +
 	  "<p class=\"justify\">" + comment.CommentBody + "</p>";    
  }
  
  
  this.ReplyFormHTML = function(CommentID)
  {
	 return "<center>" +
    	"<center class=\"BoxReply\" style=\"display:none;\" name=\"ReplyCommentForm\" id=\"ReplyForm" + CommentID + "\">" +
		  "<div class=\"CommentReplyBoxHeader\">" +
			 "<h1>Responder</h1>" +
			 "<a href=\"javascript:displayRow('ReplyForm" + CommentID + "');\">Cancelar Resposta</a>" +
        "</div><br clear='all' class='breakall'/>" +
		  "<div class=\"CommentBox\">" +
          "<input name=\"txtPostID\" type=\"hidden\" value=\"" + CommentID + "\" />" +
          ( this.UserIsAnonymous ?
				"<input name=\"txtDisplayName\" type=\"text\" class=\"name\" value=\"Nome\" onkeypress=\"commentsPager.CheckLen(this, 100, 'Nome')\" onmousedown=\"commentsPager.CheckLen(this, 100, 'Nome')\" />" +
				"<input name=\"txtUserEmail\" type=\"text\" class=\"email\" value=\"E-mail\" onkeypress=\"commentsPager.CheckLen(this, 100, 'E-mail')\" onmousedown=\"commentsPager.CheckLen(this, 100, 'E-mail')\" />" 
				: "" ) +
          "<textarea name=\"taCommentText\" rows=\"4\" class=\"comment\" onkeypress=\"commentsPager.CheckLen(this, 750, 'Comentário', 'txtNumChars')\" onmousedown=\"commentsPager.CheckLen(this, 750, 'Comentário', 'txtNumChars')\" onblur=\"commentsPager.ResetTextBox(this, 'Comentário', 750, 'txtNumChars')\">Comentário</textarea>" +
          "<h1>Caracteres dispon&iacute;veis: <b name=\"txtNumChars\">750</b></h1>" +
          "<div class=\"checkOptions\">" +
				"<input name=\"chkPostAsAnonymous\" type=\"checkbox\" /> Aparecer como Anónimo" +
		    "</div>" +
          "<div class=\"SubmitBut\">" +
              "<ul class=\"round\">" +
                  "<li><a href=\"javascript:Empty()\" onclick=\"commentsPager.PublishComment(this)\">" +
						 "<b></b><span>enviar &raquo;</span><b></b>" +
					  "</a></li>" +
              "</ul>" +
          "</div>" +
          "<div><p>" +
			   "Nota: Os comentários deste site são publicados sem edição prévia e são da exclusiva responsabilidade dos seus autores. " +
            "Consulte a <a href=\"/info/termosdeuso.aspx\">Conduta do Utilizador</a>, " +
            "prevista nos <a href=\"/info/termosdeuso.aspx\">Termos de Uso e Política de Privacidade</a>. " +
            "O JN reserva-se ao direito de apagar os comentários que não cumpram estas regras.  " +
            "<b>Receber alerta de resposta</b> - será enviado um alerta para o seu e-mail sempre que houver uma resposta ao seu comentário. " +
            "<b>Aparecer como anónimo</b> - os dados (nome e-mail) são ocultados. Os comentários podem demorar alguns segundos para ficarem disponíveis no site." +
          "</p></div>" +
				( this.UserIsAnonymous ?
				"<div class=\"loginBox\">" +
					 "<h2>Se tem conta,</h2>" +
					 "<h3 class=\"lnkRegister\"><a href=\"/MeuJN\">Fa&ccedil;a Login</a></h3>" +
				"</div>" +
				"<div class=\"registerBox\">" +
        			"<h2>Se n&atilde;o tem conta,</h2>" +
					"<h3 class=\"lnkRegister\"><a href=\"/MeuJN/Registo.aspx\">Registe-se aqui</a></h3>" +
				"</div>" : "" ) +
          "<br clear='all' class='breakall'/>" +
        "</div>" +
      "</center>" +
    "</center><br clear='all' /><br clear='all' />";
  }  
  
  
  
  
  
  
  this.CheckLen = function(obj, maxlen, defaultValue, counterName)
  {
	 if (defaultValue && obj.value == defaultValue) obj.value = "";
	 else {
		var len = obj.value.length;
		if (maxlen-len<0) obj.value = obj.value.substr (0, maxlen);
		this.CheckCounterLen (obj, maxlen, counterName);
	 }
  }


  
  this.ResetTextBox = function(obj, defaultValue, maxlen, counterName)
  {
	 if (obj.value == "") 
	 {
		this.CheckCounterLen (obj, maxlen, counterName);
		obj.value = defaultValue;
	 }
  }
  
  this.CheckCounterLen = function(obj, maxlen, counterName)
  {
		if (counterName) {
		  var parent = GetAncestor(obj, "ReplyCommentForm");
		  if (parent){
			 var counterObj = GetDescendant(parent, counterName, "b");
			 if (counterObj) counterObj.innerHTML = maxlen - obj.value.length;
		  }
		}	
  }
  

    
  this.PublishComment = function (obj)
  {
	 var parent = GetAncestor(obj, "ReplyCommentForm");
 	 if (parent){
	
	 	var txtPostID = GetDescendant(parent, "txtPostID", "input");
	 	var txtDisplayNameComment = GetDescendant(parent, "txtDisplayName", "input");
		var displayName = ( !txtDisplayNameComment || txtDisplayNameComment.value == "Nome" ? "" : txtDisplayNameComment.value ); 
		if (this.UserIsAnonymous && displayName == "") {
		  alert("O nome é obrigatório");
		  return;
		}
		var txtUserEmailComment = GetDescendant(parent, "txtUserEmail", "input");
		var userEmail = ( !txtUserEmailComment || txtUserEmailComment.value == "E-mail" ? "" : txtUserEmailComment.value ); 
		if (this.UserIsAnonymous && userEmail == "") {
		  alert("O E-mail é obrigatório");
		  return;
		}
		if (userEmail != "" && userEmail.indexOf("@")<0) {
		  alert("O E-mail tem que ser válido");
		  return;
		}
		var txtCommentTextComment = GetDescendant(parent, "taCommentText", "textarea");
		var comment = txtCommentTextComment.value == "Comentário" ? "" : txtCommentTextComment.value; 
		if (comment == "") {
		  alert("O texto do comentário é obrigatório");
		  return;
		}
		
		var chkGetFeedbackComment = GetDescendant(parent, "chkGetFeedback", "input");
		var chkPostAsAnonymousComment = GetDescendant(parent, "chkPostAsAnonymous", "input");
				
  		this.txtPostID.value = txtPostID.value;
  		this.txtDisplayName.value = displayName;
		this.txtUserEmail.value = userEmail;
		this.txtCommentText.value = comment.replace("<", "&lt;");
		this.chkGetFeedback.checked = chkGetFeedbackComment ? chkGetFeedbackComment.checked : false;
		this.chkPostAsAnonymous.checked = chkPostAsAnonymousComment.checked;
		this.publishComment.click(); 

	 }
  }
   


  this.Init(commentsArray, userIsAnonymous, UserIsAdmin, pageIndex, pageSize, pageGroupSize, displayReplies, gotoComment, gotoReply);
  return this;

}

