summaryrefslogtreecommitdiff
path: root/sites/all/modules/media_browser_plus/js/media_browser_plus.js
blob: 76aa6b1936d46158301c6c10a67c4a37e8403fe0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 * http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
 */
;(function ( $, window, document, undefined ) {
  // Create the defaults once
  var pluginName = 'mbp',
    defaults = {
      folderManagementEnabled: false,
      fileIdRegexp: /^.*media-item-([0-9]*).*$/,
      folderIdRegexp: /^.*folder-id-([0-9]*).*$/,
      mbpActionRegexp: /^.*mbp-action-(.*?)( .*|)$/,
      actions: {}
    };

  // The actual plugin constructor
  function MBP( element, options ) {
    var plugin = this;
    this.element = $(element);
    this.options = $.extend( {}, defaults, options) ;
    this._defaults = defaults;
    this._name = pluginName;

    // Add static methods.

    this.removeItemFromBasket = function(item) {
      // Extract file id and store it - in cookie and exposed form.
      var file_id = this.id.replace(plugin.options.fileIdRegexp, '$1');
      $('input[name=mbp_basket_files]', plugin.element).val($('input[name=mbp_basket_files]', plugin.element).val().replace(file_id, '').replace('  ', ' '));
      $.cookie(
        'Drupal.visitor.mbp.basket',
        $('input[name=mbp_basket_files]', plugin.element).val(),
        {path: Drupal.settings.basePath}
      );
      // Update links.
      $('a[href*="mbp_basket_files="]', plugin.element).each(function(index, link) {
        link.href = link.href.replace(/(&|)mbp_basket_files=.*?(\#|\&|$)/, '$1mbp_basket_files=' + encodeURIComponent($('input[name=mbp_basket_files]', plugin.element).val()) +  '$2');
      });
      $(this).remove();
    };

    this.addItemToBasked = function (item) {
      if (!$('.mbp-file-basket-list', plugin.element).find('#' + item.id).length) {
        // Extract file id and store it - in cookie and exposed form.
        var file_id = item.id.replace(plugin.options.fileIdRegexp, '$1');
        $('input[name=mbp_basket_files]', plugin.element).val($('input[name=mbp_basket_files]', plugin.element).val() + ' ' + file_id);
        $.cookie(
          'Drupal.visitor.mbp.basket',
          $('input[name=mbp_basket_files]', plugin.element).val(),
          {path: Drupal.settings.basePath}
        );
        // Update links.
        $('a[href*="mbp_basket_files="]', plugin.element).each(function(index, link) {
          link.href = link.href.replace(/(&|)mbp_basket_files=.*?(\#|\&|$)/, '$1mbp_basket_files=' + encodeURIComponent($('input[name=mbp_basket_files]', plugin.element).val()) +  '$2');
        });
        // Add item to list.
        $('.mbp-file-basket-list', plugin.element).append(item);
        $(item)
          .click(plugin.removeItemFromBasket)
          .find('a').click(function(e) {
            e.preventDefault();
          });
      }
    }

    this.init();
  }

  MBP.prototype.init = function () {
    var plugin = this;
    $('.mbp-folders li', this.element).bind('click.mbp', function(e) {
      // A click on the icon just opens the folder structure.
      if (!$(e.target).hasClass('icon')) {
        plugin.loadFiles($(this).children('div.folder-name').attr('class').replace(plugin.options.folderIdRegexp, '$1'));
      }
      else {
        if ($(this).hasClass('open')) {
          plugin.folderClose($(this));
        }
        else {
          plugin.folderOpen($(this));
        }
      }
      e.stopPropagation();
    });

    // Hide exposed folder filter.
    $('div.form-item-mbp-current-folder:has(:input[name=mbp_current_folder])', this.element).hide();
    // Initialize the folder structure.
    var currentFolder = $(':input[name=mbp_current_folder]', this.element).val();
    if (currentFolder) {
      this.element
        .find('li:has(>.folder-id-' + currentFolder + ')').addClass('active')
        .find('ol:first').show();
      var folder = $('.folder-id-' + currentFolder, this.element).show();
      folder.parents('ol').show();
      folder.parents('li').addClass('open');
    }

    // Enable drag n drop.
    if (this.options.files_draggable) {
      $('.mbp-file-list li', this.element).draggable({
        iframeFix: true,
        opacity: 0.7,
        revert: 'invalid',
        zIndex: 999,
        helper: function(){
          // Support grouping of draggables.
          var selected = $('li:has(input.vbo-select:checked)', plugin.element);
          if (selected.length === 0) {
            selected = $(this);
          }
          var container = $('<div/>').attr('id', 'draggingContainer');
          container.append(selected.clone());
          return container;
        }
      });
    }
    // @todo Add folder management.
    if (this.options.folders_draggable) {
//      $('.mbp-folders li', this.element).draggable({
//        iframeFix: true,
//        opacity: 0.7,
//        revert: 'invalid'
//      });
    }
    if (this.options.files_draggable || this.options.folders_draggable) {
      $('.mbp-folders li div.folder-name', this.element).droppable({
        hoverClass: 'drag-hover',
        tolerance: 'pointer',
        drop: function(event, ui) {
          if (ui.helper.data('mbpDragHoverTimeout')) {
            window.clearTimeout(ui.helper.data('mbpDragHoverTimeout'));
          }
          var target = $(this);
          var folder_id = target.attr('class').replace(plugin.options.folderIdRegexp, '$1');
          // Since we support grouping of draggables iterate over each item.
          ui.helper.find('li').each(function(index, item){
            item = $(item);
            var file_id = item.attr('id').replace(plugin.options.fileIdRegexp, '$1');
            var url = Drupal.settings.basePath + 'admin/content/file/' + file_id + '/move-to-folder/' + folder_id;
            // Add throbber to folder.
            target.prepend('<div class="ajax-progress ajax-progress-throbber media-item-' + file_id + '"><div class="throbber">&nbsp;</div></div>');
            $('#' + item.attr('id'), plugin.element).remove();
            $.ajax({
              url: url,
              success: function(data) {
                target.find('.ajax-progress.media-item-' + file_id).remove();
              },
              error: function(data) {
                alert(Drupal.t('An error occured, please refresh the page and try again.'));
                target.find('.ajax-progress.media-item-' + file_id).remove();
              }
            });
          });
        },
        over: function(event, ui) {
          // Open subfolder after 1 second hovering.
          if (ui.helper.data('mbpDragHoverTimeout')) {
            window.clearTimeout(ui.helper.data('mbpDragHoverTimeout'));
          }
          var target = $(this);
          ui.helper.data('mbpDragHoverTimeout', window.setTimeout(function(){
            //@todo Figure out why subfolders aren't initialized droppables.
            plugin.folderOpen(target.parent());
          }, 1000));
        },
        out: function(event, ui ) {
          if (ui.helper.data('mbpDragHoverTimeout')) {
            window.clearTimeout(ui.helper.data('mbpDragHoverTimeout'));
            ui.helper.data('mbpDragHoverTimeout', false);
          }
        }
      });
    }

    // Make media basked.
    if (this.options.media_basket ) {
      $('.mbp-file-basket-list li', this.element)
        .click(this.removeItemFromBasket);
      $('.mbp-file-basket input[name=mbp_basket_files_download]', this.element).click(function() {
        window.setTimeout(function(){
          $('.mbp-file-basket-list li', plugin.element).trigger('click');
        }, 1000);
        window.location.href = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'admin/content/file/download-multiple/' + $('input[name=mbp_basket_files]', plugin.element).val();
      });

      if (this.options.files_draggable) {
        $('.mbp-file-basket', this.element).droppable({
          hoverClass: 'drag-hover',
          drop: function(event, ui) {
            var target = $(this);
            ui.helper.find('li').each(function(index, item){
              plugin.addItemToBasked(item);
            });
          }
        });
      }
    }

    // Hide the vbo checkboxes and handle them by JS.
    $('.mbp-file-list li:has(.vbo-select)', this.element)
      .bind('click.mbp', function(e) {
        if (!$(e.target).hasClass('vbo-select')) {
          $(this).find('input.vbo-select')
            .attr('checked', !$(this).find('input.vbo-select').attr('checked'))
            .trigger('change');
        }
      });
    $('.mbp-file-list li input.vbo-select', this.element)
      .bind('change.mbp', function(e) {
        var media_item = $('#media-item-' + this.value + ' .media-item', plugin.element);
        if (this.checked) {
          media_item.addClass('selected');
        }
        else {
          media_item.removeClass('selected');
        }
      })
      .hide();
    $('.vbo-select-this-page', this.element).click(function() {
      $('input.vbo-select', this.element)
        .attr('checked', this.checked)
        .trigger('change');
    });
    $('.vbo-select-all-pages', this.element).click(function() {
      $('input.vbo-select', this.element)
        .attr('checked', this.checked)
        .trigger('change');
    });
    // If there are links and vbo selects navigate only on dbl clicks.
    $('.mbp-file-list li:has(.vbo-select):has(a)', this.element)
      .bind('dblclick.mbp', function(e) {
        window.location.href = $(this).find('a').attr('href');
      })
      .find('a').bind('click.mbp', function(e) {
        e.preventDefault();
      });

    // Register actions
    for (var action in this.options.actions) {
      if (this[action + 'Files']) {
        $('.mbp-action-' + action, this.element).bind('click.mbp',function() {
          var action = $(this).attr('class').replace(plugin.options.mbpActionRegexp, '$1');
          plugin[action + 'Files']();
        });
      }
    }
  };

  MBP.prototype.destroy = function () {
    $('.mbp-folders li', this.element)
      .unbind('.mbp')
      .draggable('destroy')
      .droppable('destroy');
    $('.mbp-file-list li', this.element)
      .unbind('.mbp')
      .draggable('destroy')
      .find('input.vbo-select')
      .unbind('.mbp')
      .show();
    $('div.views-exposed-widget:has(:input[name=mbp_current_folder])', this.element).show();
    $('.mbp-action-', this.element).unbind('.mbp');
  };

  MBP.prototype.folderOpen = function(folder) {
    $(folder)
      .addClass('open')
      .find('ol:first').show();
  }

  MBP.prototype.folderClose = function(folder) {
    $(folder)
      .removeClass('open')
      .find('ol').hide();
  }

  // Loads the files of a folder.
  MBP.prototype.loadFiles = function(folder_id) {
    if ($(':input[name=mbp_current_folder]', this.element).length && $(':input[name=mbp_current_folder]', this.element).val() != folder_id) {
      $(':input[name=mbp_current_folder]', this.element).val(folder_id).trigger('change');
      $('li.active', this.element).removeClass('active');
      $('li:has(>.folder-id-' + folder_id + ')', this.element)
        .addClass('active')
        .prepend('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
    }
  }

  MBP.prototype.getSelectedFiles = function () {
    var fids = [];
    var plugin = this;
    $('.mbp-file-list li:has(.media-item.selected)', this.element).each(function(i, item) {
      fids.push(item.id.replace(plugin.options.fileIdRegexp, '$1'));
    });
    return fids;
  }

  MBP.prototype.deleteFiles = function () {
    var fids = this.getSelectedFiles();
    if (fids.length) {
      window.location.href = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'admin/content/file/delete-multiple/' + fids.join(' ');
    }
  }

  MBP.prototype.basketFiles = function () {
    var plugin = this;
    var items = $('.mbp-file-list li:has(.media-item.selected)', this.element)
    if (items.length) {
      items.each(function(index, item) {
        plugin.addItemToBasked(item);
      });
    }
  }

  MBP.prototype.editFiles = function () {
    var fids = this.getSelectedFiles();
    if (fids.length) {
      window.location.href = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'admin/content/file/edit-multiple/' + fids.join(' ');
    }
  }

  MBP.prototype.downloadFiles = function () {
    var fids = this.getSelectedFiles();
    if (fids.length) {
      window.location.href = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'admin/content/file/download-multiple/' + fids.join(' ');
    }
  }

  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName,
          new MBP( this, options ));
      }
      else {
        if (options == 'options') {
          return $.data(this, 'plugin_' + pluginName).options;
        }
      }
    });
  }

  Drupal.behaviors.media_browser_plus_views = {
    attach: function (context) {
      if (Drupal.settings.mbp.views) {
        for(var i in Drupal.settings.mbp.views) {
          var view_id = Drupal.settings.mbp.views[i].view_id;
          var view_display_id = Drupal.settings.mbp.views[i].view_display_id;
          $('.view-id-'  + view_id + '.view-display-id-' + view_display_id).mbp(Drupal.settings.mbp.views[i]);
        }
      }
    }
  }

})( jQuery, window, document );