<%
	import java.util.List;
	import java.util.ArrayList;
	import javax.jcr.Node;
	import javax.jcr.NodeIterator;
	import org.exoplatform.services.wcm.core.NodeLocation;
	import org.exoplatform.webui.core.UIComponent;
  import org.exoplatform.services.jcr.util.Text;
  import org.exoplatform.container.PortalContainer;
  import org.exoplatform.wcm.webui.Utils;
  import javax.imageio.ImageIO;
  import javax.imageio.stream.ImageInputStream;
  import javax.imageio.ImageReader;

	UIComponent uiParent = uicomponent.getParent();
	
	public boolean isVersionable(Node node) throws Exception {
    return node.isNodeType("mix:versionable");
  }	

	public Node getFileLangNode(Node currentNode) throws Exception {
    if(currentNode.isNodeType("nt:unstructured")) {
      if(currentNode.getNodes().getSize() > 0) {
        NodeIterator nodeIter = currentNode.getNodes() ;
        while(nodeIter.hasNext()) {
          Node ntFile = nodeIter.nextNode() ;
          if(ntFile.getPrimaryNodeType().getName().equals("nt:file")) {
            return ntFile ;
          }
        }
        return currentNode ;
      }
    }
    return currentNode ;
  }

  def originalNode = uiParent.getOriginalNode();
  def currentNode = getFileLangNode(uiParent.getNode());
  def binarySrc = Utils.getWebdavURL(currentNode);
  def contentNode = currentNode.getNode("jcr:content") ;
  def mimeType = contentNode.getProperty("jcr:mimeType").getString() ;
  List<String> unsupportMimeTypeText = new ArrayList<String>();
  unsupportMimeTypeText.add("text/rtf");
    
  
  public String formatNodeName(String text) {
    return text.replaceAll("'", "\\\\'") ;
  }
  
  public long getFileSize(Node contentNode) throws Exception {
    long size = contentNode.getProperty("jcr:data").getLength()/1024;      	        
    return size;
  }
  
  String rndString = String.valueOf(new Date().getTime());
  
	def dcTitle = "";
	if(contentNode.hasProperty("dc:title")) {
    StringBuilder sB = new StringBuilder();
	  def i=0;
	  for(title in contentNode.getProperty("dc:title").getValues()) {
		  if (i > 0) sB.append("; ");
			sB.append(title.getString());
			i++;			        	    
		}
	  dcTitle=sB.toString();
  }

  String imageWidthStr = "610";
  try {
  	ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next();
  	ImageInputStream iis = ImageIO.createImageInputStream(contentNode.getProperty("jcr:data").getStream());
  	reader.setInput(iis, true);
  	def imageWidth = reader.getWidth(0);
  	iis.close();
  	reader.dispose();
  	
  	if (imageWidth < 40)
  	  imageWidthStr = "40";
  	else if (imageWidth < 610)
  	  imageWidthStr = imageWidth + "";
  	
  } catch (Exception e) {}
  
%>
  <div style="text-align:center">
    <a title="$dcTitle" onclick="javascript:window.open('$binarySrc');" style="cursor:pointer"><image src="$binarySrc" width="$imageWidthStr"/></a>
  </div>
