<%--
  Copyright 1997-2009 Day Management AG
  Barfuesserplatz 6, 4001 Basel, Switzerland
  All Rights Reserved.

  This software is the confidential and proprietary information of
  Day Management AG, ("Confidential Information"). You shall not
  disclose such Confidential Information and shall use it only in
  accordance with the terms of the license agreement you entered into
  with Day.

  ==============================================================================

  Add To Lightbox component

--%><%@page session="false" import="com.day.cq.i18n.I18n" contentType="text/html; charset=utf-8"%>
<%@include file="/libs/wcm/global.jsp"%><%
    I18n i18n = new I18n(slingRequest);
    String title = i18n.get(properties.get("title", "Lightbox"));
    String addText = i18n.get(properties.get("addText", "Add Asset"));
    String addRenditionsText = i18n.get(properties.get("addRenditionsText", "Add Renditions"));
    String removeText = i18n.get(properties.get("removeText", "Remove"));
    String downloadText = i18n.get(properties.get("downloadText", "Download"));
    String refreshText = i18n.get(properties.get("refreshText", "Refresh"));
    String clearText= i18n.get(properties.get("clearAll", "Clear All"));
    String allowThumbnails = i18n.get(properties.get("allowThumbnails","off"));
%><div class="title level1"><%= xssAPI.encodeForHTML(title) %></div>
<script type="text/javascript">
    function CQ_dam_lightboxAction_add(selection) {
       var paths = [];
       for (var i = 0; i < selection.length; i++) {
           paths.push(selection[i]["jcr:path"]);
       }
       CQ.Ext.Ajax.request({
           "url":CQ.Util.externalize("/libs/dam/lightbox"),
           "method":"POST",
           "callback":function(options, success, xhr) {
               var response = CQ.HTTP.buildPostResponseFromHTML(xhr.responseText);
               var status = response.headers[CQ.utils.HTTP.HEADER_STATUS];
               if (status == 200) {
                   CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
               }
           },
           "params":{
               "path":paths,
               "_charset_":"utf-8",
               "cmd":"add"
           },
           "scope":this
       });
    }   
    function CQ_dam_lightboxAction_addRendition(selection) {
		var paths = [];
		var renditionsStore = new Object();
		renditionsStore["renditions"] = new Array();
		for (var i = 0; i < selection.length; i++) {

			var assetPath = selection[i]["jcr:path"];


			var assetName = assetPath.substring(assetPath.lastIndexOf("/") + 1);
                        var getRenditions = CQ.HTTP.eval(assetPath+"/jcr:content/renditions.4.json");

			var imageLength = selection[i]["jcr:content"]["metadata"]["tiff:ImageLength"];
			var imageWidth = selection[i]["jcr:content"]["metadata"]["tiff:ImageWidth"];


			String.prototype.startsWith = function (str) {
				return (this.match("^" + str) == str)
			}
			
			for (var rend in getRenditions) {
                
                var rendition = rend.toString();
                var imageExtension = rendition.substring(rendition.lastIndexOf(".") + 1);
                    
                if (!rendition.startsWith("jcr:") 
                        <% if (allowThumbnails.equals("off")) { %>
                                  && !rendition.startsWith("cq5dam.thumbnail") && !rendition.startsWith("cq5dam.web")<% } %>
                   )
                {
                    var renditionProps = getRenditions[rend]["jcr:content"];
                    var renditionHandler = renditionProps["rendition.handler.id"];
                    
                    //check if it is a proxy rendition by looking at the handler
                    var isProxyRendition = false;
                    if (!renditionHandler || renditionHandler == "jcr.default" ) {
                        isProxyRendition = false;
                    } else  {
                        isProxyRendition = true;
                    }
                        
                    if (!isProxyRendition) {
                        
                        var iconPath = CQ.HTTP.externalize(assetPath + "/jcr:content/renditions/" + CQ.HTTP.encodePath("cq5dam.thumbnail.48.48.png"), true);
                        var path = CQ.HTTP.externalize(assetPath + "/jcr:content/renditions/" + CQ.HTTP.encodePath(rend), true);
                        
                        var renditionName = rendition.substring(0, rendition.lastIndexOf("."));
                        var height = renditionName.substring(renditionName.lastIndexOf(".") + 1);
                        renditionName = renditionName.substring(0, renditionName.lastIndexOf("."));
                        var width = renditionName.substring(renditionName.lastIndexOf(".") + 1);
                        
                        var rObj = new Object();
                        rObj["name"] = new Object();
                        
                        if (rend == "original") {
                            rObj["name"] = assetName;
    
                        } else {
                            rObj["name"] = rendition;
    
                        }
                        
                        rObj["path"] = path;
                        // If is image extension os of following types we can show the actual thumbs
                        if (imageExtension == "jpg" || imageExtension == "jpeg" || imageExtension == "png") {
                            rObj["imgURL"] = path + ".thumb.48.48.png";
                        } else {
                            rObj["imgURL"] = iconPath;
                        }
    
    
                        if (imageWidth != undefined && imageLength != undefined) {
                            rObj["size"] = imageWidth + " &times; " + imageLength;
                        }
                        
                        renditionsStore["renditions"].push(rObj);
                    }
                }
			}
		}

		if (selection.length > 0) {
			// Generic fields array to use in both store defs.
			var fields = [
				{name:'name', mapping:'name'},
				{name:'imgURL', mapping:'imgURL'},
				{name:'size', mapping:'size'},
				{name:'path', mapping:'path'}
			];

			// create the data store
			var gridStore = new CQ.Ext.data.JsonStore({
				fields:fields,
				data:renditionsStore,
				root:'renditions'
			});

			//gridStore.load();

			// Column Model shortcut array
			var cols = [
				{ id:'name', header:"Record Name", width:160, sortable:true, dataIndex:'name'},
				{header:"column1", width:50, sortable:true, dataIndex:'column1'},
				{header:"column2", width:50, sortable:true, dataIndex:'column2'}
			];

			var tpl = new CQ.Ext.XTemplate( 
				'<tpl for= "." >'+
				'<div class = "rendition-item">'+
				'<table ><tr>'+
				'<td><div class="thumbnail"' +
				'style="background-image:url(\'{imgURL}\');"></div></td>' +
				'<td align="center" vertical-align="middle"><div style="padding:10px'+
				'10px;font-size:11px;font-weight:normal;" id="{name}">{name}</div></td></tr>'+
				'</table>' +
				'</div>' +
				'</tpl>'
			   );

			var iconTemplate = new CQ.Ext.XTemplate( 
				'<div class = "rendition-item"> '+         
				'<div class = "thumbnail"' +
				'style="background-image:url(\'{imgURL}\');"></div>' +
				'</div>'
			   );

			var sm = new CQ.Ext.grid.CheckboxSelectionModel();
			var renditionGrid = new CQ.Ext.grid.GridPanel({
				ds:gridStore,
				cm:new CQ.Ext.grid.ColumnModel([
					sm,
					{id:'icon', width:200, xtype:'templatecolumn', tpl:iconTemplate, dataIndex:'imgURL'},
					{header:"Name", width:120, sortable:true, xtype:'templatecolumn', tpl:'{name}', dataIndex:'name'},
					{header:"Size", width:200, sortable:true, xtype:'templatecolumn', tpl:'{size}', dataIndex:'size'}
				]),
				sm:sm,
				autoHeight:true,
				autoWidth:true,
				autoScroll:false,
				margins:"0 0 0 0",
				fitToFrame:true,
				renderTo:document.body,
				iconCls:'icon-grid'
			});
			var renditionDataView = new CQ.Ext.DataView({
				store:gridStore,
				tpl:tpl,
				autoHeight:true,
				singleSelect:true,
				multiSelect:true,
				id:'renditions-grid',
				overClass:'x-view-over',
				itemSelector:'.rendition-item',
				emptyText:'No images to display',
				listeners:{
					"selectionchange":function () {

					}
				}
			});

			var config = CQ.WCM.getDialogConfig({
				"xtype":"panel",
				"padding":"0 0 0 0",
				"items":[renditionGrid]
			});
			var ae = this;
			config = CQ.Util.applyDefaults(config, {
				"title":CQ.I18n.getMessage("Choose Renditions"),
				"success":function () {
					alert("Hello World");
				},
				"failure":function (form, action) {

				},
				"height":354,
				"width":500,
				"padding":'0',
				"okText":CQ.I18n.getMessage("Add"),
				"params":{
					"dimensions":"140,100/48,48/319,319"
				}
			});
			
			var dialog = CQ.Util.build(config, true);
			dialog.on("beforesubmit", function () {
				var records = renditionGrid.getSelectionModel().selections.items;
				var paths = [];
				for (var i = 0; i < records.length; i++) {
					paths.push(records[i].data["path"]);
				}
				CQ.Ext.Ajax.request({
					"url":CQ.Util.externalize("/libs/dam/lightbox"),
					"method":"POST",
					"callback":function (options, success, xhr) {
						var response = CQ.HTTP.buildPostResponseFromHTML(xhr.responseText);
						var status = response.headers[CQ.utils.HTTP.HEADER_STATUS];
						if (status == 200) {
							CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
						}
					},
					"params":{
						"renditionPath":paths,
						"_charset_":"utf-8",
						"cmd":"add"
					},
					"scope":this
				});
			});
			dialog.show();
		}
}
    
    function CQ_dam_lightboxAction_remove(selection) {
        var paths = [];
        for (var i = 0; i < selection.length; i++) {
            paths.push(selection[i]["path"]);
        }
        CQ.Ext.Ajax.request({
            "url":CQ.Util.externalize("/libs/dam/lightbox"),
            "method":"POST",
            "callback":function(options, success, xhr) {
                var response = CQ.HTTP.buildPostResponseFromHTML(xhr.responseText);
                var status = response.headers[CQ.utils.HTTP.HEADER_STATUS];
                if (status == 200) {
                    CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
                }
            },
            "params":{
                "path":paths,
                "_charset_":"utf-8",
                "cmd":"remove"
            },
            "scope":this
        });
    }
    function CQ_dam_lightboxAction_clear() {
       
        CQ.Ext.Ajax.request({
            "url":CQ.Util.externalize("/libs/dam/lightbox"),
            "method":"POST",
            "callback":function(options, success, xhr) {
                var response = CQ.HTTP.buildPostResponseFromHTML(xhr.responseText);
                var status = response.headers[CQ.utils.HTTP.HEADER_STATUS];
                if (status == 200) {
                    CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
                }
            },
            "params":{
                "_charset_":"utf-8",
                "cmd":"clear"
            },
            "scope":this
        });
    }
    var lightbox;

    CQ.Ext.onLoad(function() {

        var template =
                '<table><tbody>' +
                    '<tr><td class="padding-cell top" colspan="2"><div /></td></tr>' +
                    '<tpl for=".">' +
                        '<tr><td colspan="2" class="line"></td></tr>' +
                        '<tr class="item">' +
                            '<td class="thumbnail-cell"><div style="background-image:url(\'{[CQ.HTTP.externalize(CQ.HTTP.encodePath(values.path),true)]}.thumb.48.48.png\');" /></td>' +
                            '<td class="title-cell"><div>{[CQ.shared.XSS.getXSSValue(values.title)]}</div></td>' +
                        '</tr>' +
                    '</tpl>' +
                    '<tr><td class="padding-cell bottom" colspan="2"><div /></td></tr>' +
                '</tbody></table>';
//                '</tpl>';


        var proxyConfig = CQ.Util.applyDefaults(proxyConfig, {
            "url": "/libs/dam/lightbox.json",
            "method": "GET"
        });

        var storeConfig = CQ.Util.applyDefaults(storeConfig, {
            "autoLoad": true,
            "proxy": new CQ.Ext.data.HttpProxy(proxyConfig),
            "reader": new CQ.Ext.data.JsonReader({
                "totalProperty": "results",
                "root": "entries",
                "fields": [
                        "path","title","damPath"
                        ],
                "id": "path"
            }),
            "baseParams": {
                "_charset_": "utf-8"
            },
            "listeners": {
                "load": function(store, records, options) {
                    store.records = records;
                }
            }
        });


        var config = {
            "xtype": "panel",
            "renderTo":"cq-dam-lightbox",
            "height":200,
            "multiSelect": true,
            "id": "dam-lightbox",
            "bodyCssClass": "dam-lightbox-body",

            "items": {
                "xtype": "dataview",
                "id": "dam-lightbox-dataview",
                "store": new CQ.Ext.data.GroupingStore(storeConfig),
                "cls": "lightbox",
                "layout": "fit",
                "loadingText": CQ.I18n.getMessage("Loading content..."),
                "multiSelect": true,
                "singleSelect": true,
                "overClass": "x-view-over",
                "emptyText": CQ.I18n.getMessage("No content items to display"),
                "tpl": template,
                "itemSelector": ".item"
            }

        };
        lightbox = CQ.Util.build(config);
    });

    function CQ_dam_lightboxAction_getSelection(dataView) {
        try {
            var r = dataView.getSelectedRecords();
            var s = [];
            for (var i = 0; i < r.length; i++) {
                s.push(r[i].json);
            }
            return s;
        }
        catch (e) {
            return [];
        }
    }

    function CQ_dam_lightboxAction_download() {
       var dataView = CQ.Ext.getCmp("dam-lightbox-dataview");
       var items = dataView.store.data.items;
       CQ.Ext.Ajax.request({
           url:"/libs/dam/drm",
           method:"POST",
           params: {
               "checkDRMStatus" : true
           },
           success:function (response, opts) {
               if (response.responseText.indexOf("DRM ENABLED") > -1) {
                   var dlg = new CQ.wcm.LicenseBox(items);
                   if (dlg.licensable) {
                       dlg.on("beforesubmit", function () {
                           CQ_dam_lightboxAction_download_after_license_agreement();

                       });
                       dlg.show();
                   } else {
                       CQ_dam_lightboxAction_download_after_license_agreement();

                   }
               } else {
                   CQ_dam_lightboxAction_download_after_license_agreement();
               }

           },
           failure:function (response, opts) {
            alert(response.status);
           }
     });
   }
	
    function CQ_dam_lightboxAction_download_after_license_agreement() {
        var selection = [];
        try {
            var dataView = CQ.Ext.getCmp("dam-lightbox-dataview");
            var items = dataView.store.data.items;
            for (var i = 0; i < items.length; i++) {
                selection.push({
                    "jcr:path": items[i].id
                });
            }
        }
        catch (e) {}
        CQ.dam.Util.downloadAsset(selection);
    }
	
    function CQ_dam_lightboxAction_refresh() {
        CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
    }

    function CQ_dam_lightboxAction_refresh() {
        CQ.Ext.getCmp('dam-lightbox-dataview').store.reload();
    }

</script>

<a href="javascript:CQ_dam_lightboxAction_add(CQ.search.Util.getSelection());"><%= xssAPI.encodeForHTML(addText) %></a>&nbsp;|
<a href="javascript:CQ_dam_lightboxAction_addRendition(CQ.search.Util.getSelection());"><%= xssAPI.encodeForHTML(addRenditionsText) %></a>&nbsp;|
<a href="javascript:CQ_dam_lightboxAction_remove(CQ_dam_lightboxAction_getSelection(CQ.Ext.getCmp('dam-lightbox-dataview')));"><%= xssAPI.encodeForHTML(removeText) %></a>&nbsp;|
<a href="javascript:CQ_dam_lightboxAction_download();"><%= xssAPI.encodeForHTML(downloadText) %></a>
<a href="javascript:CQ_dam_lightboxAction_refresh();"><%= xssAPI.encodeForHTML(refreshText) %></a> |
<a href="javascript:CQ_dam_lightboxAction_clear();"><%= xssAPI.encodeForHTML(clearText) %></a>
<div id="cq-dam-lightbox" style=""></div>
<%--<div id="cq-dam-lightbox" style="height:200px"></div>--%>

