<%
  /**
   * Created by The eXo Platform SARL
   * Author : Nguyen Quang Trung
   *          trung.nguyen@exoplatform.com
   * October 20, 2009
   */
%>
<%
  import java.net.URLEncoder;
  import java.util.List;
  import java.util.ArrayList;
  import java.text.SimpleDateFormat;

  import org.exoplatform.ecm.webui.utils.Utils ;
  import org.exoplatform.web.application.Parameter ;
  import org.exoplatform.webui.core.UIRightClickPopupMenu ;
  import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea;
  import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer;
  import org.exoplatform.services.jcr.util.Text;
  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
  import org.exoplatform.services.cms.link.LinkManager;
  import org.exoplatform.ecm.jcr.model.Preference;
  import org.exoplatform.services.jcr.RepositoryService;
  import org.exoplatform.webui.core.UIPageIterator;
  import org.exoplatform.services.wcm.core.NodeLocation;

  def linkManager = WCMCoreUtils.getService(LinkManager.class);
  def uiWorkingArea = uicomponent.getAncestorOfType(UIWorkingArea.class);
  def uiExplorer = uicomponent.getAncestorOfType(UIJCRExplorer.class);
  def pref = uiExplorer.getPreference();
  def enableDragAndDrop = pref.isEnableDragAndDrop();
  String componentId = uicomponent.getId();
  String portalName = uicomponent.getPortalName();
  String restContextName = Utils.getRestContextName(portalName);
  def permlink;
  RepositoryService rService = uicomponent.getApplicationComponent(RepositoryService.class);
  String repository = rService.getCurrentRepository().getConfiguration().getName();
  def viewComponentId  = new Date().getTime();
  def rcontext = _ctx.getRequestContext() ;
  def action = "";  
  def size = uicomponent.getChildrenList().size();
  UIRightClickPopupMenu contextMenu = uicomponent.getContextMenu();
  def managersMultiItemContext =  uiWorkingArea.getMultiActionsExtensionList();
  def managersGroundContext = uiWorkingArea.getGroundActionsExtensionList();
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.UITimelineView','/ecmexplorer/javascript/');
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.DMSBrowser','/ecm-wcm-extension/javascript/');
  rcontext.getJavascriptManager().addJavascript("eXo.ecm.UITimelineView.initAllEvent('${componentId}-$viewComponentId', '$enableDragAndDrop');");
  rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.ECMUtils.initClipboard('clip_button','1','$size')");
  rcontext.getJavascriptManager().addOnLoadJavascript('eXo.ecm.ECMUtils.loadEffectedItemsInSideBar');

  uicomponent.checkTimelineUpdate();
  List<String> labels = new ArrayList<String>();
  labels.add(uicomponent.CATEGORY_TODAY);
  labels.add(uicomponent.CATEGORY_YESTERDAY);
  labels.add(uicomponent.CATEGORY_WEEK);
  labels.add(uicomponent.CATEGORY_MONTH);
  labels.add(uicomponent.CATEGORY_YEAR);
  
  List<UIPageIterator> pageInterators = new ArrayList<UIPageIterator>();
  pageInterators.add(uicomponent.getTodayPageIterator());
  pageInterators.add(uicomponent.getYesterdayPageIterator());
  pageInterators.add(uicomponent.getWeekPageIterator());
  pageInterators.add(uicomponent.getMonthPageIterator());
  pageInterators.add(uicomponent.getYearPageIterator());
  
  SimpleDateFormat formatDateTime = uicomponent.getSimpleDateFormat();
  UIPageIterator displayPaginator = null;
  
%>
<div id="$componentId">
<div id="${componentId}-$viewComponentId" class="UIListView" style="">
  <div class="UIListGrid UITimelineView">
    <div style="padding:4px 3px 0px 3px;">
      <div class="TitleTable ClearFix">
        <div style="width: 40px;" class="LeftColumn Split">
          <span></span>
        </div>
        <div style="width: 26px;" class="LeftColumn Split">
          <% if (uicomponent.getTimeLineSortByFavourite().equals(Preference.BLUE_DOWN_ARROW)) { %>
            <div  class="StarLight"
                  style="margin-top: 5px;"
                  onclick="<%=uicomponent.event("SortTimelineDESC", Utils.formatNodeName("favourite"))%>"
                  title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineFavouriteDESC")%>">
              <span></span>
            </div>
          <% } else {%>
          <div  class="StarLight"
                style="margin-top: 5px;"
                onclick="<%=uicomponent.event("SortTimelineASC", Utils.formatNodeName("favourite"))%>"
                title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineFavouriteASC")%>">
            <span></span>
          </div>
          <% } %>
        </div>
        <div style="border: medium none; width: 130px; padding: 0px 3px;" class="RightColumn">
          <% if (uicomponent.getTimeLineSortByDate().equals(Preference.BLUE_UP_ARROW)) {%>
              <div onclick="<%=uicomponent.event("SortTimelineASC", Utils.formatNodeName("dateTime"))%>"
                   title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineDateTimeASC")%>">
                <div class="BlueUpArrow16x16Icon"> <%=_ctx.appRes("UIDocumentInfo.header.dateTime")%></div>
            
              </div>
          <% } else if (uicomponent.getTimeLineSortByDate().equals(Preference.BLUE_DOWN_ARROW)) { %>
              <div onclick="<%=uicomponent.event("SortTimelineDESC", Utils.formatNodeName("dateTime"))%>"
                   title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineDateTimeDESC")%>">
                <div class="BlueDownArrow16x16Icon"><%=_ctx.appRes("UIDocumentInfo.header.dateTime")%></div>
              
              </div>
          <% } else { %>
              <div onclick="<%=uicomponent.event("SortTimelineASC", Utils.formatNodeName("dateTime"))%>"
                   title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineDateTimeASC")%>">
                <%=_ctx.appRes("UIDocumentInfo.header.dateTime")%>
              </div>
          <% } %>
        </div>
        <div class="ResizeColumn Split" style="margin-left: 163px;" >
          <% if (uicomponent.getTimeLineSortByName().equals(Preference.BLUE_UP_ARROW)) {%>
              <div style="padding: 6px 5px 0px;" onclick="<%=uicomponent.event("SortTimelineASC", Utils.formatNodeName("name"))%>"
                   title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineNameASC")%>">
                <div class="BlueUpArrow16x16Icon" style="margin: 0px;"><%=_ctx.appRes("UIDocumentInfo.header.title")%></div>
                
              </div>
          <% } else if (uicomponent.getTimeLineSortByName().equals(Preference.BLUE_DOWN_ARROW)) { %>
              <div style="padding: 6px 5px 0px;" onclick="<%=uicomponent.event("SortTimelineDESC", Utils.formatNodeName("name"))%>"
                   title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineNameDESC")%>">
                <div class="BlueDownArrow16x16Icon" style="margin: 0px;"><%=_ctx.appRes("UIDocumentInfo.header.title")%></div>
                
              </div>
          <% } else { %>
              <div onclick="<%=uicomponent.event("SortTimelineASC", Utils.formatNodeName("name"))%>"
                     title="<%=_ctx.appRes("UIDocumentInfo.tooltip.timelineNameASC")%>">
                  <%=_ctx.appRes("UIDocumentInfo.header.title")%>
              </div>
          <% } %>
        </div>
        
      </div>
      
      <div style="position: relative; top: 0px; left: 0px; width: 0px; height: 0px">
        <div class="Mask" style="position: absolute; top: 0px; left: 0px; width: 0px; height: 0px"></div>
        
        <div class="JCRMoveAction" 
             style="display: none;" 
             request="<%=uiWorkingArea.getJCRMoveAction().event(UIWorkingArea.MOVE_NODE)%>" 
             symlink="<%=uiWorkingArea.getCreateLinkAction().event(UIWorkingArea.CREATE_LINK)%>">
        </div>
        <div class="ItemContextMenu" style="position: absolute; top: 0px; left: 0px; display: none;">
          <div class="UIRightClickPopupMenu" style="display: block;">
            <div class="UIRightPopupMenuContainer" onmousedown="event.cancelBubble = true;">                  
            <%
              for(itemContext in managersMultiItemContext) {
                action = itemContext.getUIExtensionName();
            %>
                <a class="MenuItem" style="display: block;" onclick=eXo.ecm.UITimelineView.postGroupAction("<%=itemContext.event(action)%>")>   
                  <div class="ItemIcon ${action}16x16Icon"><%=_ctx.appRes("ECMContextMenu.event." + action)%></div>
                </a>
            <%}%>            
           </div> 
         </div> 
       </div>
       <div class="GroundContextMenu" style="position: absolute;top: 0px; left: 0px; display: none;">
          <div class="UIRightClickPopupMenu" style="display: block;">
            <div class="UIRightPopupMenuContainer" onmousedown="event.cancelBubble = true;">          
              <%
                for(itemGroundContext in managersGroundContext) {
                action = itemGroundContext.getUIExtensionName();
              %>
                <a class="MenuItem" href="<%=itemGroundContext.event(action)%>" style="display: block;">  
                  <div class="ItemIcon ${action}16x16Icon"><%=_ctx.appRes("ECMContextMenu.event." + action)%></div>
                </a>
              <%}%>     
             </div> 
           </div>
         </div>
       </div>
       
      <%
        int k = 0; 
        for(int i = 0; i < 5; i++) {
            String label = labels.get(i);
            UIPageIterator pageInterator = pageInterators.get(i);
            if (pageInterator.getAvailablePage() > 1) {
              displayPaginator = pageInterator;
            }
            List<Node> nodeList = NodeLocation.getNodeListByLocationList(pageInterator.getCurrentPageData());
            if (nodeList.size() == 0) continue;
      %>    
      <div class="TextTitleDay">
        <% if (uicomponent.getDisplayCategory().equals(uicomponent.CATEGORY_ALL)) { 
             if (uicomponent.getIsExpanded().get(label) == uicomponent.YES) {
        %>
        <a class="ExpandCategory" href="<%=uicomponent.event("ExpandTimelineCatergory", label);%>" title="<%=_ctx.appRes("UIDocumentInfo.label.tooltip.expand")%>"><%=_ctx.appRes(label)%> >></a>
        <%
             } else {
        %>
        <%=_ctx.appRes(label)%>
        <%   
             }
        %>
        <% } else { %>
        <a class="CollapseCategory" href="<%=uicomponent.event("CollapseTimelineCatergory", label);%>" title="<%=_ctx.appRes("UIDocumentInfo.label.tooltip.collapse")%>"><%=_ctx.appRes(label)%> <<</a>
        <% } %>
      </div>  
      <div class="BorderRow">
          <%
            for (node in nodeList) {
            def data = node;
            k++;
            def rightClickMenu = "" ;
            def isPreferenceNode = uicomponent.isPreferenceNode(data);
            def preferenceWS = data.getSession().getWorkspace().getName();
            String nodePath = data.getPath();
            String path = node.getPath() + "&workspaceName=" + preferenceWS ;
            String name = nodePath.substring(nodePath.lastIndexOf("/") + 1, nodePath.length());   
            String title = uiWorkingArea.getTitle(data);            
            String subName;
            String hiddenStyle = (node.isNodeType("exo:hiddenable"))?"color: #A0A0A0;":"";
            String actionLink = uicomponent.event("ChangeNode",Utils.formatNodeName(data.path), new Parameter("workspaceName", preferenceWS));
            permLinkComponent =  uiWorkingArea.getPermlink(data);
            String strActs = "<div class=\"RightClickCustomItem\" style=\"display: none;\">" ;
            if (permLinkComponent != null) {
              permlink = permLinkComponent.getUIExtensionName();
              strActs +=  "<a class='MenuItem' style='display: block;' href=\"" + permLinkComponent.getPermlink(data) + "\" target='_new' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\">" ;
              strActs +=  " <div class='ItemIcon ${permlink}16x16Icon'>" ;
              strActs +=    _ctx.appRes("ECMContextMenu.event." + permlink);
              strActs +=  " </div>";
              strActs +=  "</a>";
            }
            //Begin WebDav Action
            if (!data.isNodeType(Utils.EXO_RESTORELOCATION) && !Utils.isTrashHomeNode(data)) {
              if ((!linkManager.isLink(data) || linkManager.isTargetReachable(data)) && data.getPrimaryNodeType().getName().equals("nt:file")) {
                String mimeType="";
                try {
                  mimeType=data.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                } catch (Exception e) {                     
                }
                // This escape "'" for js
                String webDavPath = nodePath.contains("%27") ? nodePath.replaceAll("%27","%2527") : nodePath;
                String link ="javascript:eXo.ecm.ECMUtils.generateWebDAVLink('','"+ portalName +"','"+ restContextName +"','"+repository+"','"+ preferenceWS+ "','" + webDavPath +"','"+mimeType+"')";
                strActs +=    "<a class=\"MenuItem\" style='display: block;' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\" href=\"" + link + "\" >" ;          
                strActs +=    "  <div class=\"ItemIcon WebDAV16x16Icon\">" + _ctx.appRes("UITreeExplorer.label.webDavView") + "</div>" ;
                strActs +=    "</a>" ;            
              } else {
                //data = Utils.getNodeSymLink(data);
                def dataTarget = data;
                if(uicomponent.isSymLink(data)) dataTarget = Utils.getNodeSymLink(data);
                if (dataTarget != null) {
                  String link = "/" + restContextName + "/private/jcr/" + repository+ "/" + preferenceWS + Utils.formatNodeName(dataTarget.getPath()); 
                  strActs +=    "<a class=\"MenuItem\" style='display: block; {behavior: url(#default#AnchorClick);}' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\" href=\"" +link + "\" target='_new' folder=\"" + link +"\">" ;          
                  strActs +=    "  <div class=\"ItemIcon WebDAV16x16Icon\">" + _ctx.appRes("UITreeExplorer.label.webDavView") + "</div>" ;
                  strActs +=    "</a>" ;
                }
              }
            }
            //End WebDav Action
            List customActs = uicomponent.getCustomActions(data);  
            Parameter[] params ;
            if (customActs.size() > 0) {            
              for (act in customActs) {
                String actName = act.getProperty("exo:name").getValue().getString() ;
                params = [new Parameter("workspaceName", preferenceWS), new Parameter("actionName",Utils.formatNodeName(act.getName()))] ;
                strActs += "<a class=\"MenuItem\" style='display: block;' onclick=\"return eXo.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\" href=\"" + uiCustomActionComponent.event("Custom",Utils.formatNodeName(nodePath),params) + "\">" ;
                strActs += "  <div class=\"ItemIcon " + Utils.getNodeTypeIcon(act, "16x16Icon") + "\">$actName</div>" ;
                strActs += "</a>" ;
              }            
            }
            
            if (!data.isNodeType(Utils.EXO_RESTORELOCATION) && !Utils.isTrashHomeNode(data)) {
              String clipboardLink = "/" + restContextName + "/private/jcr/" + repository + "/" + preferenceWS + data.getPath();
              strActs +=  "<a class='MenuItem' style='display: block;' id='clip_button1$k' path='$clipboardLink' onclick=\"eXo.ecm.ECMUtils.pushToClipboard(event,'$clipboardLink');\">" ;
              strActs +=  " <div class='ItemIcon GetURL16x16Icon'>" ;
              strActs +=    _ctx.appRes("ECMContextMenu.event.GetURL");
              strActs +=  " </div>" ;
              strActs +=  "</a>";
            }
            strActs += "</div>";
            
            String isFavourite = "false";
            String isInTrash = "false";
            String isMediaType = "false";
            String isTrashHome = "false";
            Boolean isLocked = false;
            String lockedLabel = "";
            if (data.isLocked()) {
              isLocked = true;
              lockedLabel  = "("+_ctx.appRes("UIDocumentWorkspace.tooltip.LockedBy")+" "+data.getLock().getLockOwner()+")";
            }
            if (uicomponent.isFavouriter(data)) isFavourite = "true";
            if (data.isNodeType("exo:restoreLocation")) isInTrash = "true";
            if (uicomponent.isMediaType(data)) isMediaType = "true";
            if (Utils.isTrashHomeNode(data)) isTrashHome = "true"
            if (!uicomponent.isSystemWorkspace()) rightClickMenu = contextMenu.getJSOnclickShowPopup(preferenceWS + ":" + Utils.formatNodeName(nodePath), uiWorkingArea.getActionsExtensionList(data)) ;
            
            %>
            <div <%=rightClickMenu%> class="RowView Normal ClearFix" trashHome="$isTrashHome" locked="$isLocked" mediaType="$isMediaType" removeFavourite="$isFavourite" inTrash="$isInTrash" workspacename="$preferenceWS" objectId="<%=URLEncoder.encode(Utils.formatNodeName(nodePath), "utf-8")%>" ondblclick="$actionLink">
              $strActs
              <div style="width: 31px;" class="LeftColumn">
                <span></span>
              </div>                
              <div style="width: 26px; padding-top: 5px;" class="LeftColumn">
                <% if (uicomponent.isFavouriteNode(node.getSession().getUserID(), node)) { %>
                  <div class="StarLight" onclick="<%=uicomponent.event("StarClick",node.getSession().getWorkspace().getName() + ":" +  Utils.formatNodeName(node.getPath()))%>"
                       title="<%=_ctx.appRes("UIDocumentInfo.tooltip.RemoveFromFavourite")%>"/>
                    <span></span>
                  </div>
                <% } else { %>
                  <div class="StarOff" onclick="<%=uicomponent.event("StarClick",node.getSession().getWorkspace().getName() + ":" +  Utils.formatNodeName(node.getPath()))%>"
                       title="<%=_ctx.appRes("UIDocumentInfo.tooltip.AddToFavourite")%>"/>
                    <span></span>
                  </div>
                <% }%>
              </div>
              <div class="LeftColumn default16x16Icon ItemIcon <%=Utils.getNodeTypeIcon(node, "16x16Icon")%>" style="margin-left:10px; width: 26px; padding-top: 5px;">
                <%if(Utils.isSymLink(node)) {%>
                  <div class="LinkSmall"></div>
                <%}%>
                <%if(isLocked) {%>
                <div class="IconLocked"></div>
                <%}%>
                <span></span>
              </div>
              <div style="border: medium none; width: 120px" class="RightColumn">
                <%=formatDateTime.format(node.getProperty(Utils.EXO_MODIFIED_DATE).getValue().getDate().getTime())%>
              </div>
              <div class="ResizeColumn" style="width:495px; *width: 425px;">
                <div class="PositionIconDocument">
                  <div class="NodeLabel">
                    <div style="cursor: pointer; -moz-outline: none; -moz-user-select: none;$hiddenStyle;" title="<%=title%> $lockedLabel"><%=title%></div>
                  </div>                
                </div>
              </div>
              
            </div>
          <% } %>
          <% if (!uicomponent.getDisplayCategory().equals(uicomponent.CATEGORY_ALL)) { %>
            <div id="FillOutElement"></div>
          <% } %>   
      </div>
      <% } %>
    </div>
  </div>
  <%
    if (displayPaginator != null) {
      int availablePage = displayPaginator.getAvailablePage();
      if (availablePage > 1) { 
  %>
        <div class="PageAvailable" pageAvailable='$availablePage'>
          <%_ctx.renderUIComponent(displayPaginator)%>
        </div>
  <%  }
    } 
  %>
</div>
</div>