#*
 * commentsinline.vm Shows document comments and gives the user an oppertunity to add a comment.
 * To include this template in a document you may specify:
 *
 * $replyTo (Integer) - If set then the comment form will appear ready to make a reply to the comment with the id number given.
 *                      If not set and request parameter 'replyto' is set then $replyTo is set to parameter 'replyto', if
 *                      no replyto request parameter and $replyTo isn't set, and $fillInFields is true and 
 *                      'XWiki.XWikiComments_replyto' is set then $replyTo is set to that.
 *
 * $hideCaptcha (boolean) - If true then the captcha is hidden and then shown by javascript when the user focuses on the comment
 *                          textarea. If not set and $captchaAnswerWrong is true or 'X-Requested-With' equals 'XMLHttpRequest' then 
 *                          it is set true.
 *
 * $captchaAnswerWrong (boolean) - If true then a message is displayed next to the captcha window telling the user that the captcha 
 *                                 answer is incorrect. If not set then this template will check for a request parameter by the same
 *                                 name and sets this true if that equals 1.
 *
 * $fillInFields (boolean) - If true then author, and comment fields are filled in from request parameters of the same names 
 *                           as the fields, also if $replyTo is set the form appears under the comment corrisponding to the $replyTo
 *                           number. If not set and $captchaAnswerWrong is true then this is set to true.
 *
 * $offerGuestsCaptcha (boolean) - If true then users who are not logged in are offered a captcha image to solve, if undefined then
 *                                 $xwiki.getSpacePreference('guest_comment_requires_captcha') NOTE: this template doesn't have the power
 *                                 to require the captcha (that is the commentAdd action) only offer it.
 *
 *###
##
## These are used when this page is accessed directly but are useless when the page is pulled in with ajax using 
## bin/view/Space/Page?xpage=xpart&vm=commentsinline.vm
$xwiki.jsfx.use('uicomponents/viewers/comments.js', {'forceSkinAction': true, 'language': ${xcontext.language}})
$xwiki.ssfx.use('uicomponents/viewers/comments.css', true)
##
##---------------------------------------------------------------------
## Set some 'global' variables
##---------------------------------------------------------------------
##
#set($xCommentClass = 'XWiki.XWikiComments')
##
#if(!$replyTo)
  #set($replyTo = $escapetool.xml($!request.get('replyto')))
#end
##
#set($requestedByAjax = ($request.getHeader('X-Requested-With') == 'XMLHttpRequest'))
##
#if("$!captchaAnswerWrong" == '')
  #set($captchaAnswerWrong = ($request.get('captchaAnswerWrong') == '1'))
#end
##
#if("$!hideCaptcha" == '')
  #set($hideCaptcha = ($captchaAnswerWrong != true && $requestedByAjax))
#end
##
#if("$!fillInFields" == '')
  #set($fillInFields = ($captchaAnswerWrong == true))
#end
##
## If $fillInFields, then set variables for each field.
#if($fillInFields)
  #set($author = $!escapetool.xml($request.get("${xCommentClass}_author")))
  #set($comment = $!escapetool.xml($request.get("${xCommentClass}_comment")))
  #if("$!replyTo" == '')
    #set($replyTo = $escapetool.xml($!request.get("${xCommentClass}_replyto")))
  #end
#end
##
#if("$!author" == '')
  #set($author = $services.localization.render('core.viewers.comments.add.guestName.default'))
#end
##
#set($xredirect = $!escapetool.xml($request.get("xredirect")))
#if("$!xredirect" == '')
  #set($xredirect = "$doc.getURL('view')?$request.getQueryString()")
#end
##
#if("$!offerGuestsCaptcha" == '')
  #set($offerGuestsCaptcha = $xwiki.getSpacePreferenceAsInt('guest_comment_requires_captcha', 0) == 1)
#end
##
##---------------------------------------------------------------------
## Macros
##---------------------------------------------------------------------
##
## If we are viewing this page through the commentAdd or save actions then we should redirect to view
## This doesn't apply if it is being viewed through javascript.
#macro(redirectIfActionNotView)
  #if(!$requestedByAjax && $xcontext.getAction() != 'view' && $xcontext.getAction() != 'get')
    #if(!$captchaAnswerWrong)
      $response.sendRedirect("$doc.getURL('view')?viewer=comments");
    #else
      #foreach($name in $request.getParameterNames())
        #set($queryString = "$!queryString&$name=$escapetool.url($request.get($name))")
      #end
      $response.sendRedirect($doc.getURL('view', "captchaAnswerWrong=1&$queryString"));
    #end
    $response.setContentLength(0)
    #stop
  #end
#end
##
##
##
#macro(addCommentToThreads $comment $commentThreads $rootKey)
  #set($thread = $commentThreads.get("$!{comment.replyto}"))
  #if("$!{thread}" == '')
    #set($thread = $commentThreads.get($rootKey))
  #end
  #set($discard = $thread.add($comment.number))
  #set($thread = '')
#end
##
##
##
#macro(displayThread $key $commentThreads, $commentDoc)
  ## If request parameter replyto is specified then we show the form under that comment.
  #if($replyTo == "$key")
    #displayCommentForm()
    #set($replied = true)
  #end
  ##
  #set($thread = $commentThreads.get("$!key"))
  #if($thread.size() > 0)
    <ul class="commentreplies">
    #foreach($commentID in $thread)
      <li class="reply">
      #displayComment($doc.getObject($xCommentClass, $commentID))
      <div class="commentthread">
        #displayThread($commentID, $commentThreads)
      </div>
      </li>
    #end
    </ul>
  #end
#end
##
##
##
#macro(displayComment $comment, $commentDoc)
  ## if the current comment is an annotation (i.e. has selection) set a flag to display selection, and add a few classes
  #set($commentSelection = $comment.getProperty('selection').value)
  #set($isAnnotation = false)
  #if ("$!commentSelection" != "")
    #set($isAnnotation = true)
  #end
  <div id="xwikicomment_${comment.number}" class="xwikicomment  #if($comment.getProperty('author').value == $doc.creator) commentByCreator#end#if($isAnnotation) annotation#end">
    <div class="commentavatar">#if("$!comment.replyto" == '')#mediumUserAvatar($comment.author)#{else}#smallUserAvatar($comment.author)#end</div>
    <div class="commentheader">
      <div>
      <span class="commentauthor">$!xwiki.getUserName($doc.display('author', 'view', $comment))</span>##
      #set($date = $comment.getProperty('date').value)
## Don't indent, otherwise the comma will be misplaced
#if($date), <span class="commentdate">$!xwiki.formatDate($date)</span>#end
      </div>
      <div class="btn-group commenttools">
      #if($xwiki.hasAccessLevel('comment'))
        <a class="commentreply btn btn-default btn-xs" rel="nofollow" href="$xredirect.replaceAll('&?replyto=\d++', '')&amp;replyto=${comment.number}#xwikicomment_${comment.number}" title="$services.localization.render('core.viewers.comments.reply')"#if("$!replyTo" == "${comment.number}") style="display: none;"#end>#glyphicon('comment')</a></span>
        #if($comment.author == $xcontext.user && $hasEdit)
          <a class="edit btn btn-default btn-xs" rel="nofollow" href="$doc.getURL('view', "viewer=comments&amp;number=${comment.number}&amp;xredirect=$xredirect")" title="$services.localization.render('core.viewers.comments.edit')">#glyphicon('pencil')</a>
        #end
      #end
      <a class="permalink btn btn-default btn-xs" rel="nofollow" href="$doc.getURL('view', 'viewer=comments')#xwikicomment_${comment.number}" title="$services.localization.render('core.viewers.comments.permalink')">#glyphicon('link')</a>
      #if ($hasAdmin || (!$isGuest && $hasEdit && $comment.author == $xcontext.user))
        <a class="delete btn btn-default btn-xs " rel="nofollow" href="$doc.getURL('objectremove', "form_token=$!{services.csrf.getToken()}&amp;classname=${xCommentClass}&amp;classid=${comment.number}&amp;xredirect=$xredirect")" title="$services.localization.render('core.viewers.comments.delete')">#glyphicon('remove')</a>
      #end
      </div>## btn-group
    </div>## commentheader
    #if ($isAnnotation)
      <a href="#ID$comment.number"><blockquote class="annotatedText">$!escapetool.xml($commentSelection)</blockquote></a>
    #end
    <div class="commentcontent#if($isAnnotation) annotationText#end">$commentDoc.getRenderedContentRestricted($comment.getProperty('comment').getValue(), $doc.getSyntax().toIdString())</div>
  </div>## xwikicomment
#end
##
##
##
#macro(displayCommentForm)
  #if($xwiki.hasAccessLevel('comment'))
    <form action="$doc.getURL('commentadd', "xpage=view&amp;viewer=comments#commentform")" method="post" id="AddComment">
      <fieldset id="commentform">
        <legend class="sr-only">$services.localization.render('core.viewers.comments.add.title')</legend>
        <div class="commentavatar">#mediumUserAvatar($xcontext.user)</div>
        #if($xcontext.user != 'XWiki.XWikiGuest')
          <label>$xwiki.getUserName($xcontext.user) $services.localization.render('core.viewers.comments.add.says')</label>
          <input type="hidden" name="${xCommentClass}_author" value="$xcontext.user"/>
        #else
          <label for="${xCommentClass}_author"><input type="text" id="${xCommentClass}_author" name="${xCommentClass}_author" value="$author" maxlength="255" /> says:</label>
          <strong><a href='$xwiki.getURL('XWiki.XWikiLogin', 'login', "xredirect=$escapetool.url($xwiki.relativeRequestURL)")'>$services.localization.render('login')</a></strong>
        #end
        ## CSRF prevention
        <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
        <input type="hidden" name="${xCommentClass}_date" value=""/>
        <input type="hidden" name="${xCommentClass}_replyto" value="$!replyTo"/>
        <div class="commentcontainer">
           <label for="${xCommentClass}_comment">$services.localization.render('core.viewers.comments.add.comment.label')</label>
           <textarea id='${xCommentClass}_comment' rows='5' cols="80" name='${xCommentClass}_comment'>$!comment</textarea>
        </div>
        #if($xcontext.user == 'XWiki.XWikiGuest' && $offerGuestsCaptcha)
          #displayCaptcha()
        #end
        <div>
          <input type="submit" value="$services.localization.render('core.viewers.comments.add.submit')" class="btn btn-primary"/>
          <a class="cancel btn btn-default" href="$doc.getURL()">$services.localization.render('core.viewers.comments.add.cancel')</a>
        </div>
      </fieldset>
    </form>
  #end
#end
##
##
##
#macro(displayCaptcha)
  <div id='commentCaptcha'>
  ## We only want to hide the captcha if we're sure the user has javascript, if this is an ajax call then it's a safe bet.
  #if($hideCaptcha)
    <script type='text/javascript'>
    $('commentCaptcha').style.display = "none";
    var handler = function() {
      var captchaDiv = $('commentCaptcha');
      var image = new Element('img', {'src' : '$doc.getURL("imagecaptcha")?nounce=$datetool.getSystemTime()', 'alt' : '$escapetool.javascript($services.localization.render("core.captcha.image.alternateText"))'});
      captchaDiv.insertBefore(image, captchaDiv.firstChild);
      Event.observe(image, 'load', function() {
        Effect.SlideDown('commentCaptcha', { duration: 0.7 });
      });
      Event.stopObserving($('${xCommentClass}_comment'), 'focus', handler);
    }.bind(this);
    Event.observe($('${xCommentClass}_comment'), 'focus', handler);
    </script>
  #else
    <img src='$doc.getURL("imagecaptcha")?nounce=$datetool.getSystemTime()' alt='$services.localization.render("core.captcha.image.alternateText")' />
  #end
  <input type='hidden' name='captcha_type' value='image'/>
  <br/>
  <label for='captcha_answer'>$services.localization.render('core.captcha.image.instruction')</label>
  <br/>
  <input id='captcha_answer' name='captcha_answer' type='text'>
  #if($captchaAnswerWrong)
    <span style="color:#C00; font-weight:bold; margin:0 0 0 5px;">$services.localization.render('core.captcha.captchaAnswerIsWrong')</span>
  #end
  <div class="wikimodel-emptyline"></div>
  </div>
#end
##
##
##
#macro(displayEditCommentForm $comment)
  #if (${comment.author} == ${xcontext.user})
  <form action="$doc.getURL('save')" method="post" class="edit-xcomment reply">
    <div id="xwikicomment_${comment.number}" class="xwikicomment#if($comment.getProperty('author').value == $doc.creator) commentByCreator#end">
    <div class="commentavatar">#if("$!comment.replyto" == '')#mediumUserAvatar($comment.author)#{else}#smallUserAvatar($comment.author)#end</div>
    <div class="commentheader">
      <div>
      <span class="commentauthor">$!xwiki.getUserName($doc.display('author', 'view', $comment))</span>##
## Don't indent, otherwise the comma will be misplaced
#set($date = $comment.getProperty('date').value)##
#if($date), <span class="commentdate">$!xwiki.formatDate($date)</span>#end
      </div>
    </div>## commentheader
    <div class="commentcontent">$doc.display('comment', 'edit', $comment)</div>
    <div class="hidden">
      ## CSRF prevention
      <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
      <input type="hidden" name="comment" value="$services.localization.render('core.viewers.comments.edit.versionComment', [${comment.number}])"/>
      <input type="hidden" name="minorEdit" value="true"/>
      <input type="hidden" name="xredirect" value="$xredirect">
    </div>
    <div>
      <input type="submit" name="action_save" class="button" value="$services.localization.render('core.viewers.comments.edit.save')"/>
      <a class="cancel secondary button" href="$doc.getURL('view', 'viewer=comments')">$services.localization.render('core.viewers.comments.edit.cancel')</a>
    </div>

    </div>## xwikicomment
  </form>
  #else
    $response.setStatus(403) ## forbidden
    #error($services.localization.render('core.viewers.comments.edit.notAllowed'))
  #end
#end
##
##---------------------------------------------------------------------
## Code
##---------------------------------------------------------------------
##
#redirectIfActionNotView()
#set($commentNumber = "$!{request.number}")
#if($commentNumber != '')
  #set($commentNumber = $mathtool.toInteger($commentNumber))
  #set($comment = $doc.getObject($xCommentClass, $commentNumber))
  #if("$!{comment}" != '')
    #if ("$!{request.xpage}" == '')
    <div id="commentscontent" class="xwikiintracontent">
    <div id="_comments">
    #end
    #displayEditCommentForm($comment)
    #if ("$!{request.xpage}" == '')
    </div>
    </div>
    #end
  #else
    $response.setStatus(404) ## Comment not found
    #error($services.localization.render('core.viewers.comments.edit.notFound'))
  #end
#else
#if($xwiki.getSpacePreferenceAsInt('commentsorder', 1) == 1)
  #set($comments = $doc.getComments())
#else
  #set($comments = $doc.getComments(false))
#end
##
##
<div id="commentscontent" class="xwikiintracontent">
  <div id="_comments">
#if($comments.size() > 0)
  #set($rootKey = "-1")
  #set($commentThreads = {})
  #set($discard = $commentThreads.put($rootKey, []))
  #foreach($comment in $comments)
    #set($discard = $commentThreads.put("${comment.number}", []))
  #end
  #foreach($comment in $comments)
    #addCommentToThreads($comment, $commentThreads, $rootKey)
  #end
  ##
  ## Comments will be rendered in the context of this document.
  #set($commentDoc = $doc)
  ##
  #displayThread($rootKey, $commentThreads, $commentDoc)
#else
  <p class="noitems">$services.localization.render('core.viewers.comments.noComments')</p>
#end

##
##
#if(!$replied)
  #displayCommentForm()
#end
  </div> ## comments
</div> ## commentscontent
#end ## comment == ''
