<%
  /**
   * Created by The eXo Platform SARL
   * Author : Dang Van Minh
   *          minhdv@exoplatform.com
   * July 25, 2006
   * 8:16:23 AM
   */
%>
<%
  import java.util.ArrayList;
	import java.net.URLEncoder;
  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.utils.text.Text;
  import org.exoplatform.services.cms.link.LinkManager;
  import org.exoplatform.ecm.webui.component.explorer.DocumentProviderUtils;
  import org.exoplatform.ecm.jcr.model.Preference;
  import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer;
  
  import javax.jcr.Value;
  import javax.jcr.PathNotFoundException;
  
  def linkManager = uicomponent.getComponentInstanceOfType("org.exoplatform.services.cms.link.LinkManager");
  def uiWorkingArea = uicomponent.getAncestorOfType(UIWorkingArea.class);
  def uiExplorer = uicomponent.getAncestorOfType(UIJCRExplorer.class);
  def pref = uiExplorer.getPreference();
  def enableDragAndDrop = pref.isEnableDragAndDrop();
  def uiCustomActionComponent = uiWorkingArea.getCustomAction();
  def managersMultiItemContext =  uiWorkingArea.getMultiActionsExtensionList();
  def managersGroundContext = uiWorkingArea.getGroundActionsExtensionList();
  def action = "";
  def permLinkComponent = null;
  UIRightClickPopupMenu contextMenu = uicomponent.getContextMenu() ;
  String componentId = uicomponent.getId();
  java.text.DateFormat dateFormat = uicomponent.getSimpleDateFormat();
  def viewComponentId  = new Date().getTime();
  def rcontext = _ctx.getRequestContext() ;
  def size = uicomponent.getChildrenList().size();
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.ECMUtils', '/ecm-wcm-extension/javascript/');
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.UIListView','/ecmexplorer/javascript/');
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.DMSBrowser','/ecm-wcm-extension/javascript/');  
  rcontext.getJavascriptManager().addJavascript("eXo.ecm.UIListView.initAllEvent('${componentId}-$viewComponentId', '$enableDragAndDrop');");
  rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.UIListView.setHeight");
  rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.ECMUtils.initClipboard('clip_button','1','$size')");
	rcontext.getJavascriptManager().addOnLoadJavascript('eXo.ecm.UIListView.loadEffectedWidthColumn');
	
	//Config to display columns with format: ["${column};${width}"]
	//Default 
	String[] arrColumns = ["exo:owner;123px","exo:dateModified;123px","exo:dateCreated;121px"];
%>
<div id="$componentId">
	<div id="${componentId}-$viewComponentId" class="UIListView">	
		<div class="UIListGrid">
				<div class="TitleTable">
			    <%
			      String selectedSortType = uicomponent.getTypeSort();
			      String sortOrder = uicomponent.getSortOrder();
			      String typeActionLink = "";
			      if (sortOrder.equals("BlueDownArrow")) {
			        typeActionLink = "Descending;";
		        } else {
		          typeActionLink = "Ascending;";
		        }
			    %>
			    
				    <div class="ColumnIcon" style="width: 20px;" onclick="<%= uicomponent.event("Sort", typeActionLink + "Type")%>" style="cursor:pointer;" >
			        <%
			          if (selectedSortType.equals("Type")) {
			        %>
				        <div class="SortButton ${sortOrder}16x16Icon" style="width: auto; padding-right: 20px; cursor:pointer;">
				          <span></span>
				        </div>
				      <%}%>
				    </div>
				    <div class="LineLeft"><span></span></div>
				    <div class="ColumnName" style="width: 150px;" onclick="<%=uicomponent.event("Sort", typeActionLink + "Alphabetic")%>">
			        <%
			          if (selectedSortType.equals("Alphabetic")) {
			        %>
				        <div class="SortButton ${sortOrder}16x16Icon" style="width: auto; padding-left: 20px;">
				        	<%=_ctx.appRes("ListView.view.label.name")%>
				        </div>
				      <%} else { %>
				        <%=_ctx.appRes("ListView.view.label.name")%>
				      <%} %>
				    </div>
					<!--
					<div class="LineLeft" onmousedown="eXo.ecm.UIListView.resizeColumn(this, event);"><span></span></div>
				    <div class="ColumnAuditing" style="border: none; width: 105px;" onclick="<%=uicomponent.event("Sort", typeActionLink + "Auditing")%>">
			        <%
			          if (selectedSortType.equals("Auditing")) {
			        %>
				        <div class="SortButton ${sortOrder}16x16Icon" style="width: auto; padding-left: 20px;">
				        	<%=_ctx.appRes("ListView.view.label.auditing")%>
				        </div>
				      <%} else { %>
				        <%=_ctx.appRes("ListView.view.label.auditing")%>
				      <%} %>
				    </div>
					-->
					<div class="LineLeft" onmousedown="eXo.ecm.UIListView.resizeColumn(this, event);"><span></span></div>
				    <div class="ColumnVersion" style="width: 105px;" onclick="<%=uicomponent.event("Sort", typeActionLink + "Versionable")%>">
			        <%
			          if (selectedSortType.equals("Versionable")) {
			        %>
				        <div class="SortButton ${sortOrder}16x16Icon" style="width: auto; padding-left: 20px;">
				        	<%=_ctx.appRes("ListView.view.label.versionable")%>
				        </div>
				      <%} else { %>
				        <%=_ctx.appRes("ListView.view.label.versionable")%>
				      <%} %>
				    </div>
			    <%
			      for(String sortType : arrColumns) {
							def arrColumn = sortType.split(";");
			    %>
						<div class="LineLeft" onmousedown="eXo.ecm.UIListView.resizeColumn(this, event);"><span></span></div>
              <div class="Column<%=uicomponent.getPropertyNameWithoutNamespace(arrColumn[0])%>" style="width: ${arrColumn[1]}" onclick="<%= uicomponent.event("Sort", typeActionLink + arrColumn[0])%>">
			       <%  
			       if (arrColumn[0].equals(selectedSortType)) {
             %>
				        <div class="SortButton ${sortOrder}16x16Icon" style="width: auto; padding-left: 20px;">
				        	<%=_ctx.appRes("ListView.view.label." + arrColumn[0].replace(":","_"))%>
				        </div>
			       <%} else { %>
			         <%=_ctx.appRes("ListView.view.label." + arrColumn[0].replace(":","_"))%>
			       <%} %>
				    </div>
			    <%
		  	    }
			    %>
						<div class="LineLeft" onmousedown="eXo.ecm.UIListView.resizeColumn(this, event);"><span></span></div>
		      </a>
			    <div style="clear: left"><span></span></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, 'MultiSelection')%>" 
								 symlink="<%=uiWorkingArea.getCreateLinkAction().event(UIWorkingArea.CREATE_LINK, 'MultiSelection')%>">
						</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;" style="border: 2px solid #b7b7b7">									
											<%
												for(itemContext in managersMultiItemContext) {
													action = itemContext.getUIExtensionName();
											%>
													<a class="MenuItem" style="display: block;" onclick=eXo.ecm.UIListView.postGroupAction("<%=itemContext.event(action, 'MultiSelection')%>")> 	
													<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;" style="border: 2px solid #b7b7b7">					
										<%
													for(itemGroundContext in managersGroundContext) {
													action = itemGroundContext.getUIExtensionName();
										%>
									<a class="MenuItem" href="<%=itemGroundContext.event(action)%>" style="display: block;"> 	
											<div class="MenuIcon ${action}16x16Icon">
												<%=_ctx.appRes("ECMContextMenu.event." + action)%>
											</div>
									 	</a>
									<%}%>			
									 </div>	
								 </div>
						</div>
					</div>
				</div>
      <%
      	String serverUrl = uicomponent.getWebDAVServerPrefix();
      	String portalName = uicomponent.getPortalName() ;
      	String repository = uicomponent.getRepository();
      	String restContextName = Utils.getRestContextName(portalName);
      	def permlink;
        int i = 0;
        for (data in uicomponent.getChildrenList()) {
    		  try {
						data.getSession().getItem(data.getPath());
					} catch(PathNotFoundException pne) {
						continue;
					}
    		  i++;
          def isPreferenceNode = uicomponent.isPreferenceNode(data) ;
          def preferenceWS = data.getSession().getWorkspace().getName() ;
          String nodePath = data.getPath() ;
          String name = nodePath.substring(nodePath.lastIndexOf("/") + 1, nodePath.length()) ;   
          String title = uiWorkingArea.getTitle(data);
          String subName ;
          String actionLink = uicomponent.event("ChangeNode",Utils.formatNodeName(data.path), new Parameter("workspaceName", preferenceWS)) ;
          //Begin permlink
          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.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\">" ;
            strActs +=  " <div class='MenuURLIcon ${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('"+serverUrl+"','"+ portalName +"','"+ restContextName +"','"+repository+"','"+ preferenceWS+ "','" + webDavPath +"','"+mimeType+"')";
	    		  	strActs +=		"<a class=\"MenuItem\" onclick=\"return eXo.webui.UIRightClickPopupMenu.prepareObjectId(event, 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 = serverUrl + "/" + portalName + "/" + restContextName + "/jcr/" + repository+ "/" + preferenceWS + Utils.formatNodeName(dataTarget.getPath()); 
  	    		  	strActs +=		"<a class=\"MenuItem\" onclick=\"return eXo.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\" style=\"{behavior: url(#default#AnchorClick);}\" 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\" 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 = serverUrl + "/" + portalName + "/rest-ecmdemo/private/jcr/" + repository + "/" + preferenceWS + data.getPath();
		        strActs +=	"<a class='MenuItem' style='display: block;' id='clip_button1$i' path='$clipboardLink' onclick=\"eXo.ecm.ECMUtils.pushToClipboard(event,'$clipboardLink');\">" ;
		  			strActs +=  "	<div class='MenuURLIcon GetURL16x16Icon'>" ;
		  			strActs +=	  _ctx.appRes("ECMContextMenu.event.GetURL");
		  			strActs +=  "	</div>" ;
		  	 		strActs +=  "</a>";
	        }
	        strActs += "</div>";
	        def rightClickMenu = "" ;
          Boolean isLocked = false;
          String lockedLabel = "";
          String isFavourite = "false";
          String isInTrash = "false";
          String isMediaType = "false";
          String isTrashHome = "false";
          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" trashHome="$isTrashHome" locked="$isLocked" mediaType="$isMediaType" removeFavourite="$isFavourite" inTrash="$isInTrash" workspacename="$preferenceWS" objectId="<%=URLEncoder.encode(Utils.formatNodeName(nodePath), "utf-8")%>" ondblclick="$actionLink">
			      $strActs
		        <div class="ColumnIcon" style="padding: 2px 0px; 	border-right: none; width: 30px;">
						  <div title="$title" class="Icon16x16 default16x16Icon <%=Utils.getNodeTypeIcon(data, "16x16Icon")%>">
                <%if(isLocked) {%>
                  <div class="IconLocked"></div>
                <%}%>
						    <%if(uicomponent.isSymLink(data)) {%>
						      <div class="LinkSmall"></div>
						    <%}%>
						  </div>
		        </div>
		        <div class="ColumnName" style="width: 150px;">
							<div class="NodeLabel">
								<div style="cursor: pointer; -moz-outline: none; -moz-user-select: none;" title="<%=Text.unescapeIllegalJcrChars(title)%> $lockedLabel"><%=Text.unescapeIllegalJcrChars(title)%></div>
		 					</div>
		        </div>
		        <!--
						<div class="ColumnAuditing" style="border: none; width: 108px;">
		           <%= Utils.isAuditable(data)%>
		           <% if (Utils.isAuditable(data)&& uicomponent.hasAuditHistory(data)) 
		                println "("+ uicomponent.getNumAuditHistory(data)+")";
		              else
		                println ""; 
		            %>
		        </div>
						-->
		        <div class="ColumnVersion" style="width: 108px;">
			         	<%=Utils.isVersionable(data)%>
			          <%
			            if(Utils.isVersionable(data) && !uicomponent.getVersionName(data).equals("jcr:rootVersion")) {
			              println "(" + uicomponent.getVersionName(data) + ")" ;
			            }
			          %>
		        </div>
						<%
							for(column in arrColumns) {
								def arrColumn = column.split(";");
								def arrColumnValue = uicomponent.getPropertyValue(data, arrColumn[0]);
								if ("exo:owner".equals(arrColumn[0]) && "__system".equals(arrColumnValue) ) arrColumnValue = ""; 
						%>
			        <div class="Column<%=uicomponent.getPropertyNameWithoutNamespace(arrColumn[0])%>" style="width: ${arrColumn[1]}">
				        <%=arrColumnValue%>
			        </div>
		        <%}%>
		        
		        <div style="clear: both"><span></span></div>
			    </div>
	      <%}%>
	      
	      </div>
	 <% 
	 //re-initialize action
	 	uiWorkingArea.initialize();
	  int availablePage = uicomponent.getContentPageIterator().getAvailablePage();
	  if (availablePage > 1) { 
	%>	
			<div class="PageAvailable" pageAvailable='$availablePage'>
				<%_ctx.renderUIComponent(uicomponent.getContentPageIterator())%>
			</div>
	<% } %>
		</div>

</div>	