<%
  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;
     
  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();
  String serverUrl= uicomponent.getWebDAVServerPrefix();
  String portalName = uicomponent.getPortalName();
  String restContextName = Utils.getRestContextName(portalName);
  String repository = uicomponent.getRepository(); 
  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().addOnLoadJavascript("function(){eXo.ecm.UISimpleView.initAllEvent('${componentId}-$viewComponentId', '$enableDragAndDrop');}");
 	rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.UISimpleView.setHeight");
 	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, 'MultiSelection')%>" symlink="<%=uiWorkingArea.getCreateLinkAction().event(UIWorkingArea.CREATE_LINK, 'MultiSelection')%>"></div>
				<div class="ItemContextMenu" style="background: #F6F6F6; position: absolute;	top: 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.UISimpleView.postGroupAction("<%=itemContext.event(action, 'MultiSelection')%>")> 	
													<div class="ItemIcon ${action}16x16Icon">
													<%=_ctx.appRes("ECMContextMenu.event." + action)%>
													</div>
								 			</a>
											<%
												}
											%>
        
						 </div>	
					 </div>
				</div>
				<div class="GroundContextMenu" style="background: #F6F6F6; position: absolute;	top: 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 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() + "&workspaceName=" + preferenceWS ;
		          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.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\">" 
    	          strActs +=  " <div class='MenuURLIcon ${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('"+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 + 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
	            }
        String subName ;
        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\" 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 = 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()+")";
              }
		  				//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>
			        <%
			          if(title.length() < 20) subName = title ;
			          else subName = title.substring(0,15) + "..." ;
			        %>
			        <div class="ActionIconLabel" style="width: auto;">
			          <a class="ActionLabel" title="<%=Text.unescapeIllegalJcrChars(title)%> $lockedLabel"><%=Text.unescapeIllegalJcrChars(subName)%></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>