<%
  import org.apache.commons.lang.StringUtils;
  import org.exoplatform.portal.application.PortalRequestContext;
  import org.exoplatform.portal.webui.util.Util;
  import org.exoplatform.resolver.ResourceResolver;
  import org.exoplatform.services.cms.taxonomy.TaxonomyService;
  import org.exoplatform.services.jcr.RepositoryService;
  import org.exoplatform.services.jcr.core.ManageableRepository;
  import org.exoplatform.services.wcm.core.WebSchemaConfigService;
  import org.exoplatform.wcm.connector.collaboration.RESTImagesRendererService;
  import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler;
  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
  import org.exoplatform.web.application.ApplicationMessage;
  import org.exoplatform.webui.application.WebuiRequestContext;
  import org.exoplatform.webui.application.portlet.PortletRequestContext;
  import org.exoplatform.webui.config.annotation.ComponentConfig;
  import org.exoplatform.webui.config.annotation.ComponentConfigs;
  import org.exoplatform.webui.config.annotation.EventConfig;
  import org.exoplatform.webui.core.UIPageIterator;
  import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
  import org.exoplatform.webui.event.Event;
  import org.exoplatform.webui.event.EventListener;
  import org.exoplatform.webui.form.UIForm;

  import org.exoplatform.services.organization.OrganizationService;
  import org.exoplatform.services.organization.UserHandler;
  import org.exoplatform.services.wcm.core.NodeLocation;
  import org.exoplatform.services.cms.comments.CommentsService;
  import org.exoplatform.social.core.manager.IdentityManager;
  import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider;
  import org.exoplatform.services.organization.Query
  
  import javax.jcr.Node;
  import javax.jcr.NodeIterator;
  import javax.jcr.Session;
  import javax.jcr.PathNotFoundException;
  import javax.portlet.PortletPreferences;
  import javax.portlet.PortletRequest;
  
  import org.exoplatform.services.cms.i18n.MultiLanguageService;
  
  import java.util.ArrayList;
  import java.util.Locale;
  import java.text.SimpleDateFormat;

  import org.exoplatform.services.wcm.core.WCMConfigurationService;
  import org.exoplatform.services.cms.relations.RelationsService;
  
  import java.io.UnsupportedEncodingException;
  import java.net.URLDecoder;
  import java.util.List;
  import org.exoplatform.services.jcr.ext.common.SessionProvider;
  import org.exoplatform.services.security.ConversationState;
  import org.exoplatform.services.cms.folksonomy.NewFolksonomyService;
  import org.exoplatform.services.wcm.core.NodeLocation;
  import org.exoplatform.services.wcm.skin.XSkinService;
  import org.exoplatform.services.wcm.javascript.XJavascriptService;
  import java.text.DateFormat;
  import java.text.ParseException;
  import java.util.Date;
  import java.text.*;
  import java.text.SimpleDateFormat;

  public String getImageCover(Node currentNode) {
  
    String path ="/marketplace-extension-webapp/skin/css/images/addons-icon.jpg";
    Node mediaNode = currentNode.getNode("medias/images");
    NodeIterator iterator = mediaNode.getNodes();
    
    if (iterator.getSize() > 0) {
     Node firstNode= iterator.nextNode();
     path = "/rest/jcr/repository/collaboration" + firstNode.getPath();
    }
  
    return path;
     
  }
  
  public List getImages(Node currentNode) {
  
    List<String> images = new ArrayList<String>();
    Node mediaNode = currentNode.getNode("medias/images");   
    NodeIterator nodeIterator = mediaNode.getNodes();
    while (nodeIterator.hasNext()) {
      Node img = nodeIterator.nextNode();
      images.add(img.getPath());
    }
    return images;
  }

  public String getAddonAvatarUrl(Node currentNode) {
  
    //use default avatar
    String avatarImageUrl="/marketplace-extension-webapp/skin/css/images/defaultAvatar_121.jpg";
    String preFix = "/rest/jcr/repository/collaboration";
    if(!currentNode.hasNode("medias/avatar")) return avatarImageUrl;
    Node mediaNode = currentNode.getNode("medias/avatar");   
    NodeIterator nodeIterator = mediaNode.getNodes();
    while (nodeIterator.hasNext()) {
      Node img = nodeIterator.nextNode();
      avatarImageUrl = preFix + img.getPath();
    }
     return avatarImageUrl;
  }
  
  
  public String generateLink(Node node) throws Exception {
  
    String categoryPath = null;
    PortalRequestContext portalRequestContext = Util.getPortalRequestContext();
    PortletRequestContext portletRequestContext = (PortletRequestContext) WebuiRequestContext.getCurrentInstance();
    PortletRequest portletRequest = portletRequestContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();
    String preferenceRepository = "repository";
    String preferenceTreeName = "website";
    String preferenceTargetPage = "resource-viewer";
    String workspace = "collaboration";
    String repository = "repository";
    String pageNodeSelected = Util.getUIPortal().getSelectedNode().getUri();
    try {
      categoryPath = URLDecoder.decode(StringUtils.substringAfter(portalRequestContext.getNodePath(),pageNodeSelected +"/"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
    
    }
  
    String gpath = Util.getPortalRequestContext().getRequestParameter("path");
    if (gpath!=null) {
      categoryPath = gpath.substring(gpath.indexOf(preferenceTreeName)+preferenceTreeName.length()+1);
    }
    RepositoryService repositoryService = uicomponent.getApplicationComponent(RepositoryService.class);
    ManageableRepository manageableRepository = repositoryService.getRepository(repository);
    TaxonomyService taxonomyService = uicomponent.getApplicationComponent(TaxonomyService.class);
    Node treeNode = null;
    treeNode = taxonomyService.getTaxonomyTree(preferenceRepository,preferenceTreeName);
    Node categoryNode = null;
  
    if (preferenceTreeName.equals(categoryPath) || "".equals(categoryPath)) {
      categoryNode = treeNode;
    } else {
      if (!categoryPath.startsWith("Content-types")) {
      
        String[] arr_temp = categoryPath.split("/");
        categoryPath = arr_temp[arr_temp.length -1] ;
      } 
      
      categoryNode = treeNode.getNode(categoryPath);
    }
  
    if (!categoryNode.isNodeType("exo:taxonomy")) {
    
      if (categoryPath!=null && categoryPath.lastIndexOf("/")>-1) {
        categoryPath = categoryPath.substring(0, categoryPath.lastIndexOf("/"));
        categoryNode = treeNode.getNode(categoryPath);
      } else {
        categoryPath = "";
        categoryNode = treeNode;
      }
    }
    String nodeName = null;
    if(node.getName().equals("jcr:frozenNode")) {
    
      String uuid = node.getProperty("jcr:frozenUuid").getString();
      Session session = WCMCoreUtils.getUserSessionProvider().getSessionProvider().getSession(workspace,manageableRepository);
      Node realNode = session.getNodeByUUID(uuid);
      
      if(realNode != null){
        nodeName = realNode.getName();
      }
    } else {    
      nodeName = node.getName();
    }
    
    Node newNode = null;
  
    try {
      newNode= categoryNode.getNode(nodeName);
    } catch(PathNotFoundException e1) {
      try {
        if (categoryPath != null && categoryPath.lastIndexOf("/")>-1) {
        categoryPath = categoryPath.substring(0, categoryPath.lastIndexOf("/"));
        categoryNode = treeNode.getNode(categoryPath);
        } else {
        categoryPath = "";
        categoryNode = treeNode;
        }
        newNode = categoryNode.getNode(nodeName);
      } catch(PathNotFoundException e2) {
        try {
        if (categoryPath != null && categoryPath.lastIndexOf("/")>-1) {
        categoryPath = categoryPath.substring(0, categoryPath.lastIndexOf("/"));
        categoryNode = treeNode.getNode(categoryPath);
        } else {
        categoryPath = "";
        categoryNode = treeNode;
        }
        newNode = categoryNode.getNode(nodeName);
        } catch(PathNotFoundException e3) {
        try {
          if (categoryPath != null && categoryPath.lastIndexOf("/")>-1) {
          categoryPath = categoryPath.substring(0, categoryPath.lastIndexOf("/"));
          categoryNode = treeNode.getNode(categoryPath);
          } else {
          categoryPath = "";
          categoryNode = treeNode;
          }
          newNode = categoryNode.getNode(nodeName);
        } catch(PathNotFoundException e4) { }
        }
      }
    }
    String path = newNode.getPath();
    String link = null;
    String itemPath = path.substring(path.lastIndexOf(preferenceTreeName));
    String backToCategory = "";
    if (categoryPath.equals("")) {
      backToCategory = pageNodeSelected;
    } else {
      backToCategory = itemPath.substring(0,
      itemPath.indexOf(newNode.getName()) - 1);
    }
    String portalURI = portalRequestContext.getPortalURI();
    link = portalURI + preferenceTargetPage + "?path=/" + itemPath;
    return link;
  }
  
  public String getTitle(Node node) throws Exception {
    return node.hasProperty("exo:title") ?
      node.getProperty("exo:title").getValue().getString() : node.getName();
  }
  
  public List<Node> getRelatedContents(Node node) throws Exception {
  
    SessionProvider sessionProvider = null;
    if (sessionProvider == null && ConversationState.getCurrent() != null)
    sessionProvider = (SessionProvider) ConversationState.getCurrent().getAttribute(SessionProvider.SESSION_PROVIDER);
    
    try {
      RelationsService relationService = uicomponent.getApplicationComponent(RelationsService.class);
      List<Node> relationNodes = relationService.getRelations(node ,  sessionProvider);
      return relationNodes;
    } catch (Exception e) {
      e.printStackTrace();
      return new ArrayList<Node>();
    } finally {
    //sessionProvider.close();
    }
  }

  public String encode(String input) {
    int startPre =input.indexOf("<pre");
    if (startPre > 0) {
      String checkClass = input.substring(startPre);
      if(checkClass.contains("class=\"prettyprint\"") || checkClass.contains("class='prettyprint'")) {
        int endPreOpen =input.indexOf(">", startPre);
        if(endPreOpen > 0) {
          String text = input.substring(endPreOpen + 1);
          String replaceText = text.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
          return input.replace(text, replaceText) + "</pre>";
        }
      } else {
        return input + "</pre>";
      }
    }
    return input;
  }
  
  def currentNode = uicomponent.getOriginalNode() ;
  def currentNodeId = currentNode.getUUID();
  def title = getTitle(currentNode);
  def addonAvatarUrl = getAddonAvatarUrl(currentNode);
  def realNode = org.exoplatform.ecm.webui.utils.Utils.getNodeSymLink(currentNode);
  def rels = getRelatedContents(realNode);
  PortalRequestContext requestContext = Util.getPortalRequestContext();
  String linkBack = requestContext.getPortalURI() + "resource-center";
  
  public boolean getPortletPreference(String name) {
    String value =
    _ctx.getRequestContext().getRequest().getPreferences().getValue(name,null);
    
    if(value != null) return Boolean.parseBoolean(value);
    return false;
  
  }
  
  String uriLink = requestContext.getRequestParameter("path");
  
  String basePath = "";
  String link = "";
  try {
    basePath = generateLink(currentNode);
    if (basePath != null && !basePath.equals("")) {
      if (basePath.indexOf("/website/") > 0) {
        uriLink = basePath.substring(basePath.indexOf("path=/website/") +
        14, basePath.length());
        basePath = basePath.substring(0, basePath.indexOf("path=/website/") + 14);
      }
    }
    if (uriLink != null && !uriLink.equals("")) {
      String[] arrLink = uriLink.split("/");
      String path = basePath;
      if(arrLink.length > 0) {
        for (int i=0; i < arrLink.length; i++) {
          if (i > 0)  path += "/";
          path += arrLink[i];
          if (i < (arrLink.length -1)) path = path.replaceAll("resource-viewer", "resource-center");
          else path = "#";
          if (i < (arrLink.length -1)) {
            link += "<a href='" + path + "'>" + arrLink[i].replaceAll("-"," ") + "</a>";
            link += " / ";
          } else  link += "<a href='" + path + "'>" + getTitle(currentNode) + "</a>";
        }
      }
    }
  } catch(Exception e) {
  
  }

  /* get the full name by userName */
  String fullName(def userName) {
    def userHandler = uicomponent.getApplicationComponent(OrganizationService.class).userHandler
    def user = userHandler.findUserByName(userName)
    def name = user.fullName
    return name?name:userName
  }

  /* get the username from email */
  String getUsernameByEmail(def email) {
    try{
      def userHandler = uicomponent.getApplicationComponent(OrganizationService.class).userHandler
      Query queryEmail = new Query()
      queryEmail.setEmail(email)
      def userList = userHandler.findUsersByQuery(queryEmail).load(0, 1)
      if (userList != null && userList.length > 0) {
        def user = userList[0]
        return user.getUserName()
      }else{
        return null;
      }
    }catch (Exception e){
        return null;s
    }
  }

  /* get the url of the avatar */
  String getAvatarUrl(def username) {
    String avatar = "/marketplace-extension-webapp/skin/css/images/UserAvtDefault.png";
    try {
      def identityManager = uicomponent.getApplicationComponent(IdentityManager.class)
      def userIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, username)
      def userProfile = userIdentity.getProfile()

      if(null != userProfile.getAvatarUrl() && userProfile.getAvatarUrl().length() >0){
        avatar = userProfile.getAvatarUrl();
      }
    } catch (Exception e) {
      //print e.message
    }
    return avatar
  }

  private String partDateToString(Date date, String format){
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    String s = formatter.format(date);
    return s;
  }

  def post = uicomponent.originalNode;

  def uuid = post.getUUID()

  def viewer = _ctx.getRequestContext().getRemoteUser();

  //list aAthors Emails
  def authorEmail = post.getProperty("exo:email").getString().split(",");
  

  def description = currentNode.getProperty("exo:description").getString();
  def version;
  if ( currentNode.hasProperty("exo:version")) version= currentNode.getProperty("exo:version").getString();

  def summary;
  if ( currentNode.hasProperty("exo:summary")) summary= currentNode.getProperty("exo:summary").getString();
  

  def author;
  if ( currentNode.hasProperty("exo:author"))  author = currentNode.getProperty("exo:author").getString();

  def license;
  if ( currentNode.hasProperty("exo:license"))  license = currentNode.getProperty("exo:license").getString();

  def compatibility;
  if ( currentNode.hasProperty("exo:compatibility")) compatibility = currentNode.getProperty("exo:compatibility").getString();

  def sourceUrl;
  if ( currentNode.hasProperty("exo:sourceUrl")) sourceUrl = currentNode.getProperty("exo:sourceUrl").getString();

  def documentUrl;
  if ( currentNode.hasProperty("exo:documentUrl"))  documentUrl = currentNode.getProperty("exo:documentUrl").getString();

  def downloadUrl = currentNode.getProperty("exo:downloadUrl").getString();

  def codeUrl;
  if ( currentNode.hasProperty("exo:codeUrl"))  codeUrl = currentNode.getProperty("exo:codeUrl").getString();

  def demoUrl;
  if ( currentNode.hasProperty("exo:demoUrl"))  demoUrl = currentNode.getProperty("exo:demoUrl").getString();

  def installCommand;
  if ( currentNode.hasProperty("exo:installCommand"))  installCommand = currentNode.getProperty("exo:installCommand").getString();

  def lastUpdate = partDateToString(currentNode.getProperty("exo:dateModified").getDate().getTime(),"dd MMM, yyyy");
  
  List<String> gal_images = getImages(currentNode);

/* render the comment form */
void commentForm(Node post) {

  try {
    uuid = post.getUUID()
    def viewer = _ctx.getRequestContext().getRemoteUser()
    def fme = fullName(viewer)
    def avt = getAvatarUrl(viewer)
    %>

    <script type="text/javascript">
        //<![CDATA[

        var jq = jQuery.noConflict();

        jq(function() {
          jq("#btn-$uuid").click(function(event) {
            event.preventDefault();

            var aform = jq("#commentform-$uuid");
            var comment = CKEDITOR.instances['comment-$uuid'].getData();
            if(comment.trim() == "") return;
            var path = aform.find( 'input[name="jcrPath"]' ).val();
            jq.ajax({
              type: "POST",
              url: "/rest/contents/comment/add",
              data: { comment: comment, jcrPath:path},
              success: function() {
              //jq('#respond-$uuid').html("<div id='message'></div>");
              jq('#message-$uuid').html('<div class="alert alert-success"><p>Your comment has been posted.</p></div>').fadeIn(3000).fadeOut(3000);
              CKEDITOR.instances["comment-$uuid"].setData("");
              fillComment_$uuid();
            }
            }); // end ajax
            return false;
          }); // end click on button

        }); // end jq
        //]]>
    </script>



      <div style="display: block;" class="commentList inputContainer inputContainerShow">
          <div class="commentItem commentFormBox" id="respond-$uuid">
              <div class="commmentLeft">
                  <a commentor="$fme" class="avatarMedium" data-placement="bottom" rel="tooltip" href="/portal/intranet/profile/$viewer" data-original-title="$fme">
                    <img src="$avt" alt="$fme">
                  </a>
              </div><!--end commentLeft-->
              <div class="commentRight">
                  <div class="commentInputBox ">
                      <form class="form-inline" id="commentform-$uuid" name="commentform-$uuid">

                        <div class="input-area">
                          <input name="jcrPath" type="hidden" value="/repository/collaboration${post.path}"/>
                          <textarea  name="comment" id="comment-$uuid" placeholder="Your Comment Here…" style=" resize: none; max-height: 50px; height: 50px;" tabindex="0"/>
                          </textarea>
            
                        </div>

                        <div class="comment-submit">
                          <input type="submit" data-original-title="Comment" id="btn-$uuid" data-placement="bottom" rel="tooltip" class="btn btn-primary" value="Post Comment">
                        </div>
            
                      </form>
                  </div>
              </div><!--end commentRight-->
          </div> <!--end commentFormBox-->
      </div><!--end commentlist-->

    <%
  } catch (Exception e) {
    //print e
  }
} // end comment form


%>




<script type="text/javascript" src="/eXoResources/javascript/jquery-1.7.1.js"></script>
<link href="/marketplace-extension-webapp/skin/css/jquery.fancybox-1.3.4.css" rel="stylesheet">
<script src="/marketplace-extension-webapp/javascript/exo/add-on/jquery.fancybox-1.3.4.pack.js">
</script>
<script src="/commons-extension/ckeditor/ckeditor.js"></script>
<link href="/marketplace-extension-webapp/skin/css/add-ons.css" rel="stylesheet">
<!--Stylesheep for image slider-->
<link href="/marketplace-extension-webapp/skin/css/CircularContentCarouselStyle.css" rel="stylesheet">

<!--JS for image slider-->
<script type="text/javascript" 
  src="/marketplace-extension-webapp/javascript/exo/add-on/CircularContentCarousel/jquery.easing.1.3.js"></script>

<!-- the jScrollPane script for image slider-->
<script type="text/javascript" 
  src="/marketplace-extension-webapp/javascript/exo/add-on/CircularContentCarousel/jquery.contentcarousel.js"></script>

<!--JS Description Read more-->
<script type="text/javascript" 
  src="/marketplace-extension-webapp/javascript/exo/add-on/readmore.js"></script>

<script type="text/javascript">
  function getREST(url){         
    return jQuery.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      async: false
    });
  }

  function fillVote_$uuid(){
    var url = "/rest/contents/vote/getVote?jcrPath=/repository/collaboration${post.path}";
    jQuery.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: function( data ) {
        rate = jQuery(data).find("rate").text();
        totalVote = jQuery(data).find("total").text();
        voteData = "Avg. Rating: <span>" + rate + "</span> &nbsp" +
                   "Votes: <span>" + totalVote + "</span>";
        jQuery("#voteDetail-$uuid").show();
        //do not render vodeData (for new UI)
        //jQuery("#voteSummary-$uuid").html(voteData);

        //render voteStars
        rateInt = parseInt(rate + "");
        rateFloat = parseFloat(rate);
        offset = rateFloat - rateInt;
        totalVoteStar = rateInt;
        if(offset >= 0.5){
          totalVoteStar = totalVoteStar + 1;
        }

        voteStarData="";
        voteStartIndex=0;
        votePermission=false;
        if("$viewer" != "null") votePermission=true;
        for(i=1; i<=totalVoteStar; i++){
          voteStartIndex +=1;
          if(votePermission){
            voteStarData += "<i class='voted' onclick='postVote_$uuid("+ voteStartIndex + ")' data-original-title='Click here to vote' data-toggle='tooltip' rel='tooltip'></i>";
          }else{
            voteStarData += "<i class='voted'></i>";
          }
        }
        for(i=1; i<= (5-totalVoteStar) ; i++){
          voteStartIndex +=1;
          if(votePermission){
            voteStarData += "<i class='unvoted' onclick='postVote_$uuid("+ voteStartIndex + ")' data-original-title='Click here to vote' data-toggle='tooltip' rel='tooltip'></i>";
          }else{
            voteStarData += "<i class='unvoted'></i>";
          }
        }
        jQuery("#voteStarList-$uuid").html(voteStarData);
      }
     });
  }

  function postVote_$uuid(voteValue){
    var url = "/rest/private/contents/vote/postVote?jcrPath=/repository/collaboration${post.path}&vote=" + voteValue + "&lang=en";
    jQuery.ajax({
      type: "GET",
      url: url,
      success: function( data ) {
        fillVote_$uuid();
        if(voteValue ==1){
          jQuery('#VoteMessage-$uuid').html('<div class="alert alert-success voteMessageAlert"><p class="voteMessageAlertContent">Your Vote (' + voteValue + ' star) has been posted.</p></div>').fadeIn(2000).fadeOut(2000);
        }else{
          jQuery('#VoteMessage-$uuid').html('<div class="alert alert-success voteMessageAlert"><p class="voteMessageAlertContent">Your Vote (' + voteValue + ' stars) has been posted.</p></div>').fadeIn(2000).fadeOut(2000);
        }
        cleanAddonCacheById_$uuid();
      }
     });
  }
  
  function cleanAddonCacheById_$uuid(){
    var url = "/rest/private/addonservice/cleanAddonCacheById?addonNodeId=$currentNodeId";
    jQuery.ajax({
      type: "GET",
      url: url,
      success: function( data ) {
        //do nothing
      }
     });
  }


  function showUpdateCommentForm_$uuid(commentId){

    jQuery("#updateComment_$uuid" + "_" + commentId).show();

    // Replace the <textarea id="..."> with a CKEditor
    CKEDITOR.replace( 'txtUpdateComment_$uuid' + '_'  + commentId,
    {
      removePlugins: 'elementspath',
      toolbar :
      [
        { name: 'tools', items : [ 'Maximize' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
        { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-',
  '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-' ] },
        { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
        
      ],

      height: 80
    });

    CKEDITOR.instances['txtUpdateComment_$uuid' + '_'  + commentId].setData(jQuery("#commentDetail_$uuid" + "_"  + commentId).html());

    //jQuery("#txtUpdateComment_$uuid" + "_"  + commentId).val(jQuery("#commentDetail_$uuid" + "_"  + commentId).html());
    jQuery("#commentDetail_$uuid" + "_" + commentId).hide();
  }

  function hideUpdateCommentForm_$uuid(commentId){
    //revert textbox change
    CKEDITOR.instances['txtUpdateComment_$uuid' + '_'  + commentId].setData(jQuery("#commentDetail_$uuid" + "_"  + commentId).html());
    jQuery("#updateComment_$uuid" + "_"  + commentId).hide();
    jQuery("#commentDetail_$uuid" + "_"  + commentId).show();
  }

  function deleteComment_$uuid(commentId){
    deleteConfirm =  'Are you sure you want to delete this comment?'; 
    if(!confirm(deleteConfirm)) return;
    var url = "/rest/private/addonservice/delete-comment?jcrPath=/repository/collaboration${post.path}&commentId=" + commentId ;
    jQuery.ajax({
      type: "GET",
      url: url,
      success: function( data ) {
        fillComment_$uuid();
        jQuery('#message-$uuid').html('<div class="alert alert-success"><p>The comment has been removed.</p></div>').fadeIn(1500).fadeOut(1500);
        
      }
     });

     return false;
  }

  function updateComment_$uuid(commentId){
    var newComment = CKEDITOR.instances['txtUpdateComment_$uuid' + '_'  + commentId].getData();
    if(newComment.trim()=="") return;
    
    var url = "/rest/private/addonservice/edit-comment";
    var jcrPath="/repository/collaboration${post.path}";
    jQuery.ajax({
      type: "POST",
      url: url,
      data: { jcrPath:jcrPath, commentId:commentId, newComment:newComment },
      success: function( data ) {
        fillComment_$uuid();
        jQuery('#message-$uuid').html('<div class="alert alert-success"><p>The comment has been updated.</p></div>').fadeIn(1500).fadeOut(1500);
        
      }
     });

     return false;
  }

  function fillComment_$uuid(){
    var url = "/rest/addonservice/all-comment?jcrPath=/repository/collaboration${post.path}";
    jQuery.getJSON( url, function( data ) {
      jQuery("#comment-title-$uuid").html(data.length + "&nbsp Comment(s)");
      HTMLdata =  "";

      for(i = (data.length-1); i>=0; i--){ 

        commentId = data[i].id; 
        canDelete = data[i].canDelete; 
        commentorFullname = data[i].commentorFullname; 
        commentorUsername = data[i].commentorUsername; 
        commentorAvataUrl = data[i].commentorAvataUrl; 
        commentDetail = data[i].commentDetail; 
        createDate = data[i].createDate;      
        HTMLdata += "<div class='commentContainer commentItem clearfix' id='comment-" + commentId + "'>" +
                    "<div class='avatarBox pull-left'>" +
                      "<a commentor='"+ commentorFullname + "' class='avatarMedium' data-placement='bottom' rel='tooltip' href='/portal/intranet/profile/" + commentorUsername + "' data-original-title='" + commentorFullname + "'>" +
                        "<img alt='" + commentorFullname + "' src='" + commentorAvataUrl + "'>" +
                      "</a>" +
                    "</div>" +
                    "<div class='commentBox uiBox'>" +
                      "<span class='arrowLeft'></span>" +
                      "<div class='commentInfo'>" +
                        "<strong><a href='/portal/intranet/profile/" + commentorUsername +"'>" + commentorFullname + "</a></strong> " +
                        "<div class='pull-right'>" +
                             createDate ;
                         
                        if(canDelete){
              HTMLdata += " <a data-original-title='Edit this comment' class='actionIcon' href='javascript:void(0);' rel='tooltip' data-placement='bottom' title='' onclick='showUpdateCommentForm_$uuid(" + commentId +")'>" +
                          "<i class='uiIconEdit uiIconLightGray'></i>" +
                          "</a>" +
          
                          "<a data-original-title='Remove this comment' class='actionIcon' href='javascript:void(0);' rel='tooltip' data-placement='bottom' title='' onclick='javascript:deleteComment_$uuid(" + commentId + ");return false;'>" +
                            "<i class='uiIconTrash uiIconLightGray'></i>" +
                          "</a>";
                         }
              
              HTMLdata +="</div>" +
                      "</div>" +
                      "<div class='commentContent' id='commentDetail_$uuid" + "_" + commentId + "'>" +
                            commentDetail +
                      "</div>" +

                      "<!--BEGIN update form--> " + 
                      "<div style='display:none' class='commentItem commentFormBox' id='updateComment_$uuid" + "_" + commentId +"'>" +           
                        "<div class='commentRight'> " + 
                          "<div class='commentInputBox '> " + 
                            "<form class='form-inline'> " + 

                              "<div class='input-area'> " + 
                      
                                  "<textarea id= 'txtUpdateComment_$uuid" + "_" + commentId + "' type='text' tabindex='0' style=' resize: none; max-height: 50px; height: 50px;' placeholder='Your Comment Here…' value='" + commentDetail + "' data-default-value='" + commentDetail + "'></textarea>" + 
                      
                              "</div> " + 

                              "<div class='comment-submit'> " + 
                                "<input type='button' value='Update' class='btn btn-primary' rel='tooltip' data-placement='bottom' data-original-title='Update Comment'onclick='javascript:updateComment_$uuid(" + commentId + ")'> &nbsp" + 
                                "<input type='button' value='Cancel' class='btn' rel='tooltip' data-placement='bottom' data-original-title='Cancel' onclick='javascrip:hideUpdateCommentForm_$uuid(" + commentId +")'> " + 
                        
                              "</div> " + 
                    
                            "</form> " + 
                          "</div> " + 
                        "</div><!--end commentRight--> " + 
                      "</div><!--commentFormBox-->" +
                    "<!--End update form--> " + 

              
                    "</div>" +
                "</div>";

      }

      jQuery("#listComment-$uuid").html(HTMLdata);
    });
    
  }


    jQuery(document).ready(function(){
      fillComment_$uuid();
      fillVote_$uuid();

      if("$viewer" != "null"){
        // Replace the <textarea id="comment-$uuid"> with a CKEditor
        CKEDITOR.replace( 'comment-$uuid',
        {
          removePlugins: 'elementspath',
          toolbar :
          [
            { name: 'tools', items : [ 'Maximize' ] },
            { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
            { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-',
      '-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-' ] },
            { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
            
          ],

          height: 80
        });  
      }

      <%if(installCommand!=null && installCommand!=("")){%>
        jQuery("#installCommand_$uuid").click(function() {jQuery(this).select(); } );
      <%}%>
    });


  jQuery(document).ready(function(){


    // init image slider
    jQuery('#ca-container-$uuid').contentcarousel({
        // speed for the sliding animation
        //sliderSpeed   : 500,
        // easing for the sliding animation
        //sliderEasing  : 'easeOutExpo',
        // speed for the item animation (open / close)
        //itemSpeed   : 500,
        // easing for the item animation (open / close)
        //itemEasing    : 'easeOutExpo',
        // number of items to scroll at a time
        //scroll      : 1,
          minItemToShowNav:2
      });

    //init image slider popup
    jQuery(".screenShotPopup").fancybox({

        openEffect  : 'elastic', // 'elastic', 'fade' or 'none'
        openSpeed   : 250,
        openEasing  : 'swing',
        openOpacity : true,
        openMethod  : 'zoomIn',

        // Closing fancyBox
        closeEffect  : 'elastic', // 'elastic', 'fade' or 'none'
        closeSpeed   : 250,
        closeEasing  : 'swing',
        closeOpacity : true,
        closeMethod  : 'zoomOut',

        // Changing next gallery item
        nextEffect : 'fade', // 'elastic', 'fade' or 'none'
        nextSpeed  : 250,
        nextEasing : 'swing',
        nextMethod : 'changeIn',

        // Changing previous gallery item
        prevEffect : 'fade', // 'elastic', 'fade' or 'none'
        prevSpeed  : 250,
        prevEasing : 'swing',
        prevMethod : 'changeOut',
    });

    //process readmore for description
    jQuery('#description_$uuid').readmore({
      speed: 75,
      lessLink: '<a href="#">Read less</a>'
    });
    

  });
</script>



<!--Addon navigation-->
<div class="addonToolbar clearfix">
  <ul class="breadcrumb pull-left">  
    <li class="">
      <a href="/portal/intranet/add-ons">All Add-ons</a>
      <span class="uiIconMiniArrowRight">&nbsp;</span>
    </li>
    <li class="active">$title</li>
  </ul>
  <div class="pull-right">
    <button class="btn" type="button" onclick="location.href='/portal/intranet/create-addon'">Add New Add-on</button>
    <button class="btn" type="button" onclick="window.open('https://codenvy.com/f?id=7nop24paia4u2okn', '_blank')">Code New Add-ons</button>
  </div>
</div>
<!--END Addon navigation-->
<div class="addonMainContent">
  <div class="clearfix">
     <div class="img pull-left"><a href="#" title=""><img class='addonAvatar' src="$addonAvatarUrl" alt="" /></a></div>
  <%if(installCommand!=null && installCommand!=("")){%>
      <div class="install pull-right">
        <div>Install via eXo add-on Manager:</div>
        <div class="installInputArea">
          <div class="specialTxt">&#36;</div>
          <input data-original-title='$installCommand' data-placement='bottom' rel='tooltip' type="text" id="installCommand_$uuid" readonly='readonly' value="$installCommand"/>
        </div>
      </div>
    <%}%>
      
    <div class="info">
    <div class="detail">
      <h2>$title</h2>
      
      <!-- Begin vote-->
      <div class="clearfix">
        <div class="pull-left uiVote clearfix" id="voteDetail-$uuid" style="display:none">
          <!--
          <div class="voteRatingInfo" id= "voteSummary-$uuid">
            Avg. Rating: <span>0.0</span>
            Votes: <span>0</span>
          </div>
          -->
          <div class="avgRatingImages clearfix" id="voteStarList-$uuid">

                <i class="unvoted"></i>
      
                <i class="unvoted"></i>
      
                <i class="unvoted"></i>
      
              <i class="unvoted"></i>
      
              <i class="unvoted"></i>
          </div>
        </div>
        <div id='VoteMessage-$uuid' style="display:none" class="voteMessageParent"></div>
      </div>
      <!-- End vote--> 

      <div class="dateTime">Updated $lastUpdate</div>
      <div class="btnList">
        <a target="_blank" href="$downloadUrl" class="btn"><%=_ctx.appRes("UIPortlet.Download")%></a>
        <%if(null!=codeUrl && codeUrl!=("")){%>
        <a target="_blank" href="$codeUrl" class="btn">Code</a>
        <%}%>
        <%if(null!=demoUrl && demoUrl!=("")){%>
        <a target="_blank" href="$demoUrl" class="btn btn-primary"><i class="uiIconVideo"></i>&nbsp;&nbsp;Run</a>
        <%}%>
      </div>
    </div>
    </div>
    
  </div>


  <%if(gal_images.size()>0){%>
  <div class="listImg">  

    <div id="ca-container-$uuid" class="ca-container">
    <div class="ca-wrapper">
      <%
      for (int i=0;i<gal_images.size();i++) {
        gal_img = (String) gal_images.get(i);
      %>
        <div class="ca-item ca-item-$i">
          <div class="ca-item-main">
            <a class="screenShotPopup" data-fancybox-group="gallery"  href="/rest/jcr/repository/collaboration<%=gal_img%>">
              <img style="max-height:292px" alt="addon image" src="/rest/jcr/repository/collaboration<%=gal_img%>">
            </a>
          </div>
          
        </div>
      <%} //end for%>
    </div>
  </div>

  </div>
  <%} //end check list image%>


  <div class="addonContent">
    <p>
      <div class="description" id="description_$uuid">
        <%=description%>
      </div>
      
    </p>
  </div>
</div>

<div class="addonMoreInfo">
  <div class="title20">More Information</div>
  <div class="row-fluid">
    <div class="span2">
      <h6>Updated</h6>
      <span>$lastUpdate</span>
    </div>
    <div class="span3">
      <h6><%if(authorEmail.length>1){%>Authors<%}else{%>Author<%}%></h6>
      <ul class="authorList">
        <%for (String emailItem : authorEmail) {
            def authorUserName = getUsernameByEmail(emailItem.trim());
            if(authorUserName!=null && !authorUserName.equals("")){
              //if author is existed in Platform
              def authorFullname = fullName(authorUserName);
              def authorAvatar = getAvatarUrl (authorUserName);
        %>
              <li><a rel="tooltip" data-placement="bottom" commentor="$authorFullname" title="$authorFullname" href="/portal/intranet/profile/$authorUserName" class="avatarXSmall"><img alt="$authorFullname" src="$authorAvatar"></a></li>
        <%    
            } //end of if
            else{ //if author is not existed in Platform
        %>
              <li><a rel="tooltip" data-placement="bottom" commentor="$emailItem" title="$emailItem" href="mailto:$emailItem" class="avatarXSmall"><img alt="$emailItem" src="/marketplace-extension-webapp/skin/css/images/UserAvtDefault.png"></a></li>
        <%
            } //end else
          } //end of for 
        %>

      </ul>
    </div>
    <%if((sourceUrl!=null && !sourceUrl.equals("")) || (documentUrl!=null && !documentUrl.equals(""))){%>
      <div class="span3">
        <h6>Add-on resources</h6>
        <%if(sourceUrl!=null && !sourceUrl.equals("")){%>
          <div><a target="_blank" href="$sourceUrl">Source</a></div>
        <%}%>
        <%if(documentUrl!=null && !documentUrl.equals("")){%>
          <div><a target="_blank" href="$documentUrl">Documentation</a></div>
        <%}%>
      </div>
    <%}%>
    <%if(license!=null && !license.equals("")){%>
      <div class="span2">
        <h6>License</h6>
        <span>$license</span>
      </div>
    <%}%>
    <%if(compatibility!=null && !compatibility.equals("")){%>
      <div class="span2">
        <h6>Compatibility</h6>
        <span>$compatibility</span>
      </div>
    <%}%>
  </div>
</div>



 <!--Addon comment-->
<div class="UIPluginTemplateOneScr">
    <h5 class='title' id='comment-title-$uuid'>Comment(s)</h5>
    <div class='commentList'>
      <div id='message-$uuid' style="display:none"></div>
      <div>
        <div id="listComment-$uuid" class="listComment"></div>
      </div>
    </div>
    <% commentForm(post) %>
</div>
<!--END Addon comment-->
