<%
 import java.net.URLEncoder;
 import java.util.ArrayList;
 import java.util.List;

 import javax.jcr.Node;
 import javax.jcr.Value;
 import javax.servlet.http.HttpServletRequest;

 import org.exoplatform.portal.application.PortalRequestContext;
 import org.exoplatform.portal.webui.portal.UIPortal;
 import org.exoplatform.portal.webui.util.Util;
 import org.exoplatform.services.wcm.search.ResultNode;
 import org.exoplatform.wcm.webui.paginator.UICustomizeablePaginator;
 import org.exoplatform.wcm.webui.search.UISearchForm;
 import org.exoplatform.wcm.webui.search.UISearchPageLayout;
 import org.exoplatform.services.wcm.search.SiteSearchService;
 import org.exoplatform.wcm.webui.reader.ContentReader;
 import org.exoplatform.services.cms.impl.Utils;

%>
<div id="$uicomponent.id" class="UIAdvanceSearchResultDefault">
 <%
  def showPaginator = false;
  def startItemIndex = 1;
  def pageMode = uicomponent.getPageMode();
  def currentPageData = uicomponent.getCurrentPageData();
  def currentPage = uicomponent.getCurrentPage();
  def itemsPerPage = uicomponent.getItemsPerPage();
  def totalItems = uicomponent.getTotalItem();
  def endItemIndex = (currentPage - 1) * itemsPerPage + currentPageData.size();
  def realCurrentPageData = uicomponent.getRealCurrentPageData();
  def keyword = uicomponent.getKeyword();
  if(keyword != null)
    keyword = ContentReader.getEscapeHtmlContent(keyword);
  def resultType = uicomponent.getResultType();
  def sortField = uicomponent.getSortField();
  def orderType = uicomponent.getOrderType();
  def rcontext = _ctx.getRequestContext() ;
  def jsManager = rcontext.getJavascriptManager();
  jsManager.require("SHARED/wcm-search", "search")
    .addScripts("search.SearchPortlet.init();")
    .addScripts("search.SearchPortlet.scrollToBottom('${uicomponent.id}');")
    .addScripts("search.SearchPortlet.changeColor('NewResultData');");

  // Get css used to describe arrow up or down for order criteria
  private String getSortTypeCss(String checkField) {
      if (checkField.equals(uicomponent.getSortField())) {
          if ("desc".equals(uicomponent.getOrderType())) {
              return "<i class=\"uiIconSortDown\"></i>";
          } else {
              return "<i class=\"uiIconSortUp\"></i>";
          }
      } else {
          return "";
      }
  }
  %>
  <!-- Header -->
  <div class="result clearfix">
      <%
      if (currentPageData != null && !currentPageData.isEmpty()) { 
        if (SiteSearchService.PAGE_MODE_PAGINATION.equals(pageMode) ) startItemIndex =  (currentPage - 1) * itemsPerPage + 1;
        showPaginator = (itemsPerPage==currentPageData.size() && SiteSearchService.PAGE_MODE_MORE.equals(pageMode)) ||
                                      (SiteSearchService.PAGE_MODE_PAGINATION.equals(pageMode));
   	 %>
   	   <%
   	   def strResult = "";
   	   if (totalItems == 1) {
   	     strResult = _ctx.appRes("UIDefaultSearchResult.label.oneResult");
   	     strResult = strResult.replace("{0}","<strong>" + keyword + "</strong>");
   	   } else {
   	     strResult = _ctx.appRes("UIDefaultSearchResult.label.results");
   	     strResult = strResult.replace("{0}",startItemIndex.toString());
   	     strResult = strResult.replace("{1}",endItemIndex.toString());
   	     strResult = strResult.replace("{2}","<strong>" + keyword + "</strong>");
   	   }
   	   %>
   		 <div class="pull-left resultHeader" id="resultHeader">
	       <p>$strResult</p>
	     </div>
	     <div class="pull-right resultSort" id="resultSort" style="display: block;">
	        <div class="btn-group uiDropdownWithIcon pull-right">
	           <a class="btn dropdown-toggle" data-toggle="dropdown">
	           <span id="sortField" sort="$sortField" order="$orderType"><%=uicomponent.getLabel("UIDefaultSearchResult.label." + sortField)%></span>
	           <span class="spiter"></span>
	           <i class="uiIconMiniArrowDown uiIconLightGray"></i>
	           </a>
	           <ul class="dropdown-menu" id="sortOptions">
	              <li><a sort="relevancy" href="#"><%=uicomponent.getLabel("UIDefaultSearchResult.label.relevancy")%><%=getSortTypeCss("relevancy");%></a></li>
	              <li><a sort="date" href="#"><%=uicomponent.getLabel("UIDefaultSearchResult.label.date")%><%=getSortTypeCss("date");%></a></li>
	              <li><a sort="title" href="#"><%=uicomponent.getLabel("UIDefaultSearchResult.label.title")%><%=getSortTypeCss("title");%></a></li>
	           </ul>
	        </div>
	        <span><%=uicomponent.getLabel("UIDefaultSearchResult.label.sortBy")%></span>
	     </div>
    
      <% } %>
     
  </div>
  <%
  if (realCurrentPageData.isEmpty()) {
    def msgNotMatch = _ctx.appRes("UIDefaultSearchResult.msg.search-not-match-type");
    msgNotMatch = msgNotMatch.replace("{0}", "<strong style=\"font-size: 15px; font-style: italic;\">" + keyword + "</strong>");
    msgNotMatch = msgNotMatch.replace("{1}", _ctx.appRes("UIDefaultSearchResult.label." + resultType).toLowerCase()); 
    %>
     <p>$msgNotMatch</p>
    <%
  } else {
    int dataIndex = 0;
    for (ResultNode resultNode : realCurrentPageData) {
     dataIndex++;
     Node viewNode = resultNode.getNode();
     def itemName = viewNode.getName();
     def itemTitle = uicomponent.getTitle(viewNode);
     if (itemTitle != null && itemTitle.trim().length() != 0) itemName = itemTitle;
     itemName = ContentReader.getXSSCompatibilityContent(itemName);
     def itemUrl = resultNode.getUserNavigationURI();
     List<String> listNavigationNodeUris = new ArrayList<String>();
     if (itemUrl == null || itemUrl.trim().length() == 0) {
       itemUrl = uicomponent.getURL(viewNode);
       listNavigationNodeUris = uicomponent.getURLs(viewNode);
       if (!listNavigationNodeUris.isEmpty()) {
         itemUrl = uicomponent.getPublishedNodeURI(listNavigationNodeUris.get(0));
       }
     }
     def itemExcerpt = resultNode.getExcerpt();
     PortalRequestContext portalRequestContext = Util.getPortalRequestContext();
     String requestURL = portalRequestContext.getRequest().getRequestURL().toString();
     Node realNode = org.exoplatform.wcm.webui.Utils.getRealNode(viewNode);
     String detail = uicomponent.getDetail(resultNode);

     %>
     <div class="resultBox clearfix">
       <a href="$itemUrl&urlSearch=$requestURL">
       <%if(resultType.equals("Document")){%>
         <a href="$itemUrl&urlSearch=$requestURL">
       <%}else{%>
       <a href="$itemUrl">
       <%}%>
         <span class="avatar pull-left ">
           <i class="<%=Utils.getNodeTypeIcon(realNode, "uiIcon64x64")%>"></i>
         </span>
       </a>
       <div class="content">
          <h6>
             <%if(resultType.equals("Document")){%>
               <a href="$itemUrl&urlSearch=$requestURL">$itemName</a>
             <%}else{%>
               <a href="$itemUrl">$itemName</a>
             <%}%>
          </h6>
          <p class="excerpt">$itemExcerpt</p>
          <div class="detail">$detail</div>
       </div>
     </div>
     <%
    }
  }%>

  <div class="ItemFunc">
   <% if (showPaginator) uicomponent.renderChild(UICustomizeablePaginator.class); %>
  </div>
</div>

