var container, gridForm, grid;

function initPlaylistView(playlist){
  container = parent.viewport.getComponent('center-panel');

  var dataStore = new Ext.data.SimpleStore({
    fields: ['thumbnail', 'type', 'title', 'description', 'tags', 'handle']
  });
  dataStore.loadData(playlist.entries);

  var colModel = new Ext.grid.ColumnModel([
    {
      header: 'Thumbnail',
      renderer : function(v, p, record){
        return v ? '<img border="0" alt="" src="' + contextPath + v + '" />' : '';
      }
    },
    {header: 'Type'},
    {
      id: 'title',
      header: 'Title'
    },
    {
      id: 'description',
      header: 'Description'
    },
    {
      id: 'tags',
      header: 'Tags'
    }
  ]);

  var tbar = [
    {
      text: playlist.msgs.addEntry,
      icon: contextPath + '/.resources/media/icons/ico16-add.png',
      iconCls: 'button-add',
      handler: function(){
        //parent.openWindow('.magnolia/dialogs/playlistentry.html?mgnlPath=' + playlist.handle + '&mgnlRepository=playlists');
        var mgnlWin = parent.parent;
        mgnlWin.setNewMedia = function(nodeid, uuid, file, thumb){
          Ext.Ajax.request({
            form: 'addEntryForm',
            params: {
              mgnlPath: playlist.handle,
              media: uuid
            },
            success: function(){
              parent.openPlaylist(playlist.handle);
            },
            failure: function(){
              // todo
            }
          });
        };
        mgnlWin.mgnlOpenWindow('/.magnolia/pages/mediaBrowser.html?nodeid=media&selectMedia=true&mgnlCK=' + mgnlWin.mgnlGetCacheKiller(), 800, 500);
      }
    },
    {
      id: 'removeEntryBtn',
      text: playlist.msgs.removeEntry,
      icon: contextPath + '/.resources/media/icons/ico16-remove.png',
      iconCls: 'button-remove',
      disabled: true,
      handler: function(){
        Ext.MessageBox.confirm('Confirm', 'Are you sure?', function(btn){
          if (btn != 'yes') return;
          var s = grid.getSelectionModel().getSelections();
          for(var i = 0, r; r = s[i]; i++){
            removeEntry(r);
          }
        });
      }
    }
  ];

  function removeEntry(r){
    Ext.Ajax.request({
      method: 'post',
      url: contextPath + '/.magnolia/trees/playlists.html',
      params: {
        browseMode: false,
        deleteNode: r.data['handle'].match(/\/?([^\/]+)$/)[1],
        mgnlCK: (new Date()).getTime(),
        path: playlist.handle,
        treeMode: 'snippet'
      },
      success: function(){
        grid.store.remove(r);
      }
    });
  }

  var dd = new Ext.ux.dd.GridDragDropRowOrder({});

  gridForm = new Ext.FormPanel({
    id: 'playlist-form',
    frame: true,
    labelAlign: 'left',
    layout: 'column',
    items: [{
      columnWidth: 0.6,
      layout: 'fit',
      items: {
        xtype: 'grid',
        id: 'playlistEntries',
        viewConfig: {
          forceFit: true,
          autoFill : true
        },
        store: dataStore,
        cm: colModel,
        selModel: new Ext.grid.RowSelectionModel(),
        autoSizeColumns: true,
        enableColLock: false,
        tbar: tbar,
        stripeRows: true,
        plugins: [dd]
      }
    },{
      columnWidth: 0.4,
      xtype: 'fieldset',
      labelWidth: 90,
      title: 'Playlist details',
      defaults: {width: 140},  // Default config options for child items
      defaultType: 'textfield',
      autoHeight: true,
      bodyStyle: Ext.isIE ? 'padding:0 0 5px 15px;' : 'padding:10px 15px;',
      border: false,
      style: {
        "margin-left": "10px", // when you add custom margin in IE 6...
        "margin-right": Ext.isIE6 ? (Ext.isStrict ? "-10px" : "-13px") : "0"  // you have to adjust for it somewhere else
      },
      items: [{
        xtype: 'hidden',
        name: 'command',
        value: 'save'
      }, {
        xtype: 'hidden',
        name: 'mgnlCK',
        value: (new Date()).getTime()
      }, {
        xtype: 'hidden',
        name: 'path',
        value: playlist.handle
      }, {
        fieldLabel: 'Title',
        name: 'title',
        value: playlist.title,
        anchor: '100% none'
      }, {
        xtype: 'textarea',
        fieldLabel: 'Description',
        name: 'description',
        value: playlist.description,
        anchor: '100% none'
      }],
      buttons: [{
        text: 'Save',
        handler: function(){
          if(gridForm.getForm().isValid()){
            gridForm.getForm().submit({
              url: contextPath + '/.magnolia/pages/playlistView.html',
              success: function(){
                // todo
              }
            });
          }
        }
      }]
    }],
    renderTo: Ext.getBody()
  });

  grid = Ext.getCmp('playlistEntries');

  dd.on('beforerowmove', function(dropTarget, i1, i2){
    if (i2 > i1 && i2 == grid.store.data.length - 1) return false;
    Ext.Ajax.request({
      method: 'post',
      url: contextPath + '/.magnolia/trees/playlists.html',
      params: {
        browseMode: false,
        mgnlCK: (new Date()).getTime(),
        pasteType: 0,
        path: playlist.handle,
        pathClipboard: grid.store.getAt(i1).data['handle'],
        pathSelected: grid.store.getAt(i2 + (i1 < i2 ? 1 : 0)).data['handle'],
        treeAction: 0,
        treeMode: 'snippet'
      }
    });
  });
  grid.getSelectionModel().on('selectionchange', function(sm){
    Ext.getCmp('removeEntryBtn').setDisabled(sm.getCount() < 1);
  });

  container.on('bodyresize', resizeGrid);
  resizeGrid();
}

function disposePlaylistView(){
  if (!container) return;
  container.un('bodyresize', resizeGrid);
  delete container;
}

function resizeGrid(){
  gridForm.setWidth(container.body.getWidth(true));
  grid.setHeight(container.body.getHeight(true) - 13);
};
