<%
  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.ecm.webui.component.explorer.DocumentProviderUtils;
  import org.exoplatform.ecm.jcr.model.Preference;
  import org.exoplatform.ecm.webui.component.explorer.UIJCRExplorer;
  import org.exoplatform.services.cms.link.LinkManager;
  import org.exoplatform.services.jcr.RepositoryService;
  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
     
  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();
  
  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();
  String portalName = uicomponent.getPortalName();
  String restContextName = Utils.getRestContextName(portalName);
  RepositoryService rService = uicomponent.getApplicationComponent(RepositoryService.class);
  String repository = rService.getCurrentRepository().getConfiguration().getName();
  def size = uicomponent.getChildrenList().size();
  def viewComponentId  = new Date().getTime();
  def rcontext = _ctx.getRequestContext() ;
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.UISimpleView','/ecmexplorer/javascript/');
  rcontext.getJavascriptManager().importJavascript('eXo.ecm.DMSBrowser','/ecm-wcm-extension/javascript/') ;  
  rcontext.getJavascriptManager().addJavascript("eXo.ecm.UISimpleView.initAllEvent('${componentId}-$viewComponentId', '$enableDragAndDrop');");
 	rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.ECMUtils.initClipboard('clip_button','1','$size')");
%>
<div id="$componentId">
	<div id="${componentId}-$viewComponentId">
		<%if(!uicomponent.isSystemWorkspace()) {%>
			<div style="position: relative; top: 0px; left: 0px; width: 0px; height: 0px">
				<div class="JCRMoveIcon" style="display: none;"><div class="MoveNode"><span>{number}</span></div></div>
				<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; display: none;" >
					<div class="UIRightClickPopupMenu" style="display: block;">
						<div class="UIRightPopupMenuContainer" onmousedown="event.cancelBubble = true;" onkeydown="event.cancelBubble = true;">
								<%
												for(itemContext in managersMultiItemContext) {
													action = itemContext.getUIExtensionName();
											%>
													<a class="MenuItem" style="display: block;" onclick=eXo.ecm.UISimpleView.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; display: none;">
						<div class="UIRightClickPopupMenu" style="display: block;">
							<div class="UIRightPopupMenuContainer" onmousedown="event.cancelBubble = true;" onkeydown="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>
		<%}%>	
		<div class="UIThumbnailsView" style="overflow-y: auto; overflow-x: hidden;">
		  <div class="ActionIconsContainer">
		    <%
		      int i = 0;
		      def permlink;
			    for(data in uicomponent.getChildrenList()) {
		    		  i++;
		          def isPreferenceNode = uicomponent.isPreferenceNode(data) ;
		          def preferenceWS = data.getSession().getWorkspace().getName() ;
		          String name = data.getPath().substring(data.getPath().lastIndexOf("/") + 1) ;
              String title = uiWorkingArea.getTitle(data);              
		          String nodePath = data.getPath();
		          String actionLink = uicomponent.event("ChangeNode", Utils.formatNodeName(data.path), new Parameter("workspaceName", preferenceWS));
		          String strActs = "<div class=\"RightClickCustomItem\" style=\"display: none;\">" ;
		          //Begin permlink
		          permLinkComponent =  uiWorkingArea.getPermlink(data);
	            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>";
              } 
	            if (!data.isNodeType(Utils.EXO_RESTORELOCATION) && !Utils.isTrashHomeNode(data)) {	            
			          //Begin WebDav Action
	              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) {											
									}
									String webDavPath = data.getPath().contains("%27") ? data.getPath().replaceAll("%27","%2527") : data.getPath(); 
							  	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 + 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",act.getName())] ;
            strActs += "<a class=\"MenuItem\" style='display: block;' onclick=\"return eXo.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\" href=\"" + uiCustomActionComponent.event("Custom",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$i' 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>" ;
		          def rightClickMenu = "" ;
              Boolean isLocked = false;
              String lockedLabel = "";
		          String isFavourite = "false";
		          String isInTrash = "false";
		          String isMediaType = "false";
		          String isTrashHome = "false";
              String hiddenStyle = (data.isNodeType("exo:hiddenable"))?"color: #A0A0A0;":"";
              if (data.isLocked()) {
                isLocked = true;
                lockedLabel  = "("+_ctx.appRes("UIDocumentWorkspace.tooltip.LockedBy")+" "+data.getLock().getLockOwner()+")";
              }
		  				//data.getProperty("exo:favouriter");    
		          if (uicomponent.isFavouriter(data)) isFavourite = "true";
		          if (data.isNodeType("exo:restoreLocation")) isInTrash = "true";
		          if (uicomponent.isMediaType(data)) isMediaType = "true";
		          if(!uicomponent.isSystemWorkspace()) rightClickMenu = contextMenu.getJSOnclickShowPopup(preferenceWS + ":" + Utils.formatNodeName(nodePath), uicomponent.getActionsList(data)) ;
		          
		        %>   
		      <div class="ActionIconBox" locked="<%=isLocked%>"
		      													 trashHome="$isTrashHome" 
		      													 removeFavourite="$isFavourite"
	      														 inTrash="$isInTrash"
	      														 mediaType="$isMediaType"  
		      													 <%=rightClickMenu%> 
		      													 style="padding: 4px 0px 4px 0px; height: auto;"
		       													 objectId="<%=URLEncoder.encode(Utils.formatNodeName(data.getPath()), "utf-8")%>" workspaceName="$preferenceWS" ondblclick="$actionLink">
		        <div style="height: auto; width: auto; border: none; -moz-user-select: none;" unselectable="on">
							<div class="NodeLabel">
								<div class="ActionIcon">
									<div style="display: block;" class="Icon48x48 default48x48Icon <%=Utils.getNodeTypeIcon(data, "48x48Icon")%>">
                    <%if(isLocked) {%>
                      <div class="IconLocked"></div>
                    <%}%>
									  <%if(uicomponent.isSymLink(data)) {%>
  									  <div class="Link"></div>
									  <%}%>
									</div>
								</div>
							</div>			        
			        <div class="ActionIconLabel" style="width: auto; overflow: hidden;">
			          <a class="ActionLabel" style="$hiddenStyle" title="<%=title%> $lockedLabel"><%=title%></a>
			        </div>
			      </div>
			      $strActs
		      </div>
		    <%}%>
		    
		  </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>