Projet

Général

Profil

Paste
Télécharger (36,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / js / views-admin.js @ 4003efde

1
/**
2
 * @file
3
 * Some basic behaviors and utility functions for Views UI.
4
 */
5
Drupal.viewsUi = {};
6

    
7
Drupal.behaviors.viewsUiEditView = {};
8

    
9
/**
10
 * Improve the user experience of the views edit interface.
11
 */
12
Drupal.behaviors.viewsUiEditView.attach = function (context, settings) {
13
  // Only show the SQL rewrite warning when the user has chosen the
14
  // corresponding checkbox.
15
  jQuery('#edit-query-options-disable-sql-rewrite').click(function () {
16
    jQuery('.sql-rewrite-warning').toggleClass('js-hide');
17
  });
18
};
19

    
20
Drupal.behaviors.viewsUiAddView = {};
21

    
22
/**
23
 * In the add view wizard, use the view name to prepopulate form fields such as
24
 * page title and menu link.
25
 */
26
Drupal.behaviors.viewsUiAddView.attach = function (context, settings) {
27
  var $ = jQuery;
28
  var exclude, replace, suffix;
29
  // Set up regular expressions to allow only numbers, letters, and dashes.
30
  exclude = new RegExp('[^a-z0-9\\-]+', 'g');
31
  replace = '-';
32

    
33
  // The page title, block title, and menu link fields can all be prepopulated
34
  // with the view name - no regular expression needed.
35
  var $fields = $(context).find('[id^="edit-page-title"], [id^="edit-block-title"], [id^="edit-page-link-properties-title"]');
36
  if ($fields.length) {
37
    if (!this.fieldsFiller) {
38
      this.fieldsFiller = new Drupal.viewsUi.FormFieldFiller($fields);
39
    }
40
    else {
41
      // After an AJAX response, this.fieldsFiller will still have event
42
      // handlers bound to the old version of the form fields (which don't exist
43
      // anymore). The event handlers need to be unbound and then rebound to the
44
      // new markup. Note that jQuery.live is difficult to make work in this
45
      // case because the IDs of the form fields change on every AJAX response.
46
      this.fieldsFiller.rebind($fields);
47
    }
48
  }
49

    
50
  // Prepopulate the path field with a URLified version of the view name.
51
  var $pathField = $(context).find('[id^="edit-page-path"]');
52
  if ($pathField.length) {
53
    if (!this.pathFiller) {
54
      this.pathFiller = new Drupal.viewsUi.FormFieldFiller($pathField, exclude, replace);
55
    }
56
    else {
57
      this.pathFiller.rebind($pathField);
58
    }
59
  }
60

    
61
  // Populate the RSS feed field with a URLified version of the view name, and
62
  // an .xml suffix (to make it unique).
63
  var $feedField = $(context).find('[id^="edit-page-feed-properties-path"]');
64
  if ($feedField.length) {
65
    if (!this.feedFiller) {
66
      suffix = '.xml';
67
      this.feedFiller = new Drupal.viewsUi.FormFieldFiller($feedField, exclude, replace, suffix);
68
    }
69
    else {
70
      this.feedFiller.rebind($feedField);
71
    }
72
  }
73
};
74

    
75
/**
76
 * Constructor for the Drupal.viewsUi.FormFieldFiller object.
77
 *
78
 * Prepopulates a form field based on the view name.
79
 *
80
 * @param $target
81
 *   A jQuery object representing the form field to prepopulate.
82
 * @param exclude
83
 *   Optional. A regular expression representing characters to exclude from the
84
 *   target field.
85
 * @param replace
86
 *   Optional. A string to use as the replacement value for disallowed
87
 *   characters.
88
 * @param suffix
89
 *   Optional. A suffix to append at the end of the target field content.
90
 */
91
Drupal.viewsUi.FormFieldFiller = function ($target, exclude, replace, suffix) {
92
  var $ = jQuery;
93
  this.source = $('#edit-human-name');
94
  this.target = $target;
95
  this.exclude = exclude || false;
96
  this.replace = replace || '';
97
  this.suffix = suffix || '';
98

    
99
  // Create bound versions of this instance's object methods to use as event
100
  // handlers. This will let us easily unbind those specific handlers later on.
101
  // NOTE: jQuery.proxy will not work for this because it assumes we want only
102
  // one bound version of an object method, whereas we need one version per
103
  // object instance.
104
  var self = this;
105
  this.populate = function () {return self._populate.call(self);};
106
  this.unbind = function () {return self._unbind.call(self);};
107

    
108
  this.bind();
109
  // Object constructor; no return value.
110
};
111

    
112
/**
113
 * Bind the form-filling behavior.
114
 */
115
Drupal.viewsUi.FormFieldFiller.prototype.bind = function () {
116
  this.unbind();
117
  // Populate the form field when the source changes.
118
  this.source.bind('keyup.viewsUi change.viewsUi', this.populate);
119
  // Quit populating the field as soon as it gets focus.
120
  this.target.bind('focus.viewsUi', this.unbind);
121
};
122

    
123
/**
124
 * Get the source form field value as altered by the passed-in parameters.
125
 */
126
Drupal.viewsUi.FormFieldFiller.prototype.getTransliterated = function () {
127
  var from = this.source.val();
128
  if (this.exclude) {
129
    from = from.toLowerCase().replace(this.exclude, this.replace);
130
  }
131
  return from + this.suffix;
132
};
133

    
134
/**
135
 * Populate the target form field with the altered source field value.
136
 */
137
Drupal.viewsUi.FormFieldFiller.prototype._populate = function () {
138
  var transliterated = this.getTransliterated();
139
  this.target.val(transliterated);
140
};
141

    
142
/**
143
 * Stop prepopulating the form fields.
144
 */
145
Drupal.viewsUi.FormFieldFiller.prototype._unbind = function () {
146
  this.source.unbind('keyup.viewsUi change.viewsUi', this.populate);
147
  this.target.unbind('focus.viewsUi', this.unbind);
148
};
149

    
150
/**
151
 * Bind event handlers to the new form fields, after they're replaced via AJAX.
152
 */
153
Drupal.viewsUi.FormFieldFiller.prototype.rebind = function ($fields) {
154
  this.target = $fields;
155
  this.bind();
156
}
157

    
158
Drupal.behaviors.addItemForm = {};
159
Drupal.behaviors.addItemForm.attach = function (context) {
160
  var $ = jQuery;
161
  // The add item form may have an id of views-ui-add-item-form--n.
162
  var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();
163
  // Make sure we don't add more than one event handler to the same form.
164
  $form = $form.once('views-ui-add-item-form');
165
  if ($form.length) {
166
    new Drupal.viewsUi.addItemForm($form);
167
  }
168
}
169

    
170
Drupal.viewsUi.addItemForm = function($form) {
171
  this.$form = $form;
172
  this.$form.find('.views-filterable-options :checkbox').click(jQuery.proxy(this.handleCheck, this));
173
  // Find the wrapper of the displayed text.
174
  this.$selected_div = this.$form.find('.views-selected-options').parent();
175
  this.$selected_div.hide();
176
  this.checkedItems = [];
177
}
178

    
179
Drupal.viewsUi.addItemForm.prototype.handleCheck = function (event) {
180
  var $target = jQuery(event.target);
181
  var label = jQuery.trim($target.next().text());
182
  // Add/remove the checked item to the list.
183
  if ($target.is(':checked')) {
184
    this.$selected_div.show();
185
    this.checkedItems.push(label);
186
  }
187
  else {
188
    var length = this.checkedItems.length;
189
    var position = jQuery.inArray(label, this.checkedItems);
190
    // Delete the item from the list and take sure that the list doesn't have
191
    // undefined items left.
192
    for (var i = 0; i < this.checkedItems.length; i++) {
193
      if (i == position) {
194
        this.checkedItems.splice(i, 1);
195
        i--;
196
        break;
197
      }
198
    }
199
    // Hide it again if none item is selected.
200
    if (this.checkedItems.length == 0) {
201
      this.$selected_div.hide();
202
    }
203
  }
204
  this.refreshCheckedItems();
205
}
206

    
207

    
208
/**
209
 * Refresh the display of the checked items.
210
 */
211
Drupal.viewsUi.addItemForm.prototype.refreshCheckedItems = function() {
212
  // Perhaps we should precache the text div, too.
213
  this.$selected_div.find('.views-selected-options').html(Drupal.checkPlain(this.checkedItems.join(', ')));
214
  Drupal.viewsUi.resizeModal('', true);
215
}
216

    
217

    
218
/**
219
 * The input field items that add displays must be rendered as <input> elements.
220
 * The following behavior detaches the <input> elements from the DOM, wraps them
221
 * in an unordered list, then appends them to the list of tabs.
222
 */
223
Drupal.behaviors.viewsUiRenderAddViewButton = {};
224

    
225
Drupal.behaviors.viewsUiRenderAddViewButton.attach = function (context, settings) {
226
  var $ = jQuery;
227
  // Build the add display menu and pull the display input buttons into it.
228
  var $menu = $('#views-display-menu-tabs', context).once('views-ui-render-add-view-button-processed');
229

    
230
  if (!$menu.length) {
231
    return;
232
  }
233
  var $addDisplayDropdown = $('<li class="add"><a href="#"><span class="icon add"></span>' + Drupal.t('Add') + '</a><ul class="action-list" style="display:none;"></ul></li>');
234
  var $displayButtons = $menu.nextAll('.add-display').detach();
235
  $displayButtons.appendTo($addDisplayDropdown.find('.action-list')).wrap('<li>')
236
    .parent().first().addClass('first').end().last().addClass('last');
237
  // Remove the 'Add ' prefix from the button labels since they're being palced
238
  // in an 'Add' dropdown.
239
  // @todo This assumes English, but so does $addDisplayDropdown above. Add
240
  //   support for translation.
241
  $displayButtons.each(function () {
242
    var label = $(this).val();
243
    if (label.substr(0, 4) == 'Add ') {
244
      $(this).val(label.substr(4));
245
    }
246
  });
247
  $addDisplayDropdown.appendTo($menu);
248

    
249
  // Add the click handler for the add display button.
250
  $('li.add > a', $menu).bind('click', function (event) {
251
    event.preventDefault();
252
    var $trigger = $(this);
253
    Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
254
  });
255
  // Add a mouseleave handler to close the dropdown when the user mouses
256
  // away from the item. We use mouseleave instead of mouseout because
257
  // the user is going to trigger mouseout when she moves from the trigger
258
  // link to the sub menu items.
259
  //
260
  // We use the 'li.add' selector because the open class on this item will be
261
  // toggled on and off and we want the handler to take effect in the cases
262
  // that the class is present, but not when it isn't.
263
  $menu.delegate('li.add', 'mouseleave', function (event) {
264
    var $this = $(this);
265
    var $trigger = $this.children('a[href="#"]');
266
    if ($this.children('.action-list').is(':visible')) {
267
      Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu($trigger);
268
    }
269
  });
270
};
271

    
272
/**
273
 * @note [@jessebeach] I feel like the following should be a more generic function and
274
 * not written specifically for this UI, but I'm not sure where to put it.
275
 */
276
Drupal.behaviors.viewsUiRenderAddViewButton.toggleMenu = function ($trigger) {
277
  $trigger.parent().toggleClass('open');
278
  $trigger.next().slideToggle('fast');
279
}
280

    
281

    
282
Drupal.behaviors.viewsUiSearchOptions = {};
283

    
284
Drupal.behaviors.viewsUiSearchOptions.attach = function (context) {
285
  var $ = jQuery;
286
  // The add item form may have an id of views-ui-add-item-form--n.
287
  var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();
288
  // Make sure we don't add more than one event handler to the same form.
289
  $form = $form.once('views-ui-filter-options');
290
  if ($form.length) {
291
    new Drupal.viewsUi.OptionsSearch($form);
292
  }
293
};
294

    
295
/**
296
 * Constructor for the viewsUi.OptionsSearch object.
297
 *
298
 * The OptionsSearch object filters the available options on a form according
299
 * to the user's search term. Typing in "taxonomy" will show only those options
300
 * containing "taxonomy" in their label.
301
 */
302
Drupal.viewsUi.OptionsSearch = function ($form) {
303
  this.$form = $form;
304
  // Add a keyup handler to the search box.
305
  this.$searchBox = this.$form.find('#edit-options-search');
306
  this.$searchBox.keyup(jQuery.proxy(this.handleKeyup, this));
307
  // Get a list of option labels and their corresponding divs and maintain it
308
  // in memory, so we have as little overhead as possible at keyup time.
309
  this.options = this.getOptions(this.$form.find('.filterable-option'));
310
  // Restripe on initial loading.
311
  this.handleKeyup();
312
  // Trap the ENTER key in the search box so that it doesn't submit the form.
313
  this.$searchBox.keypress(function(event) {
314
    if (event.which == 13) {
315
      event.preventDefault();
316
    }
317
  });
318
};
319

    
320
/**
321
 * Assemble a list of all the filterable options on the form.
322
 *
323
 * @param $allOptions
324
 *   A jQuery object representing the rows of filterable options to be
325
 *   shown and hidden depending on the user's search terms.
326
 */
327
Drupal.viewsUi.OptionsSearch.prototype.getOptions = function ($allOptions) {
328
  var $ = jQuery;
329
  var i, $label, $description, $option;
330
  var options = [];
331
  var length = $allOptions.length;
332
  for (i = 0; i < length; i++) {
333
    $option = $($allOptions[i]);
334
    $label = $option.find('label');
335
    $description = $option.find('div.description');
336
    options[i] = {
337
      // Search on the lowercase version of the label text + description.
338
      'searchText': $label.text().toLowerCase() + " " + $description.text().toLowerCase(),
339
      // Maintain a reference to the jQuery object for each row, so we don't
340
      // have to create a new object inside the performance-sensitive keyup
341
      // handler.
342
      '$div': $option
343
    }
344
  }
345
  return options;
346
};
347

    
348
/**
349
 * Keyup handler for the search box that hides or shows the relevant options.
350
 */
351
Drupal.viewsUi.OptionsSearch.prototype.handleKeyup = function (event) {
352
  var found, i, j, option, search, words, wordsLength, zebraClass, zebraCounter;
353

    
354
  // Determine the user's search query. The search text has been converted to
355
  // lowercase.
356
  search = (this.$searchBox.val() || '').toLowerCase();
357
  words = search.split(' ');
358
  wordsLength = words.length;
359

    
360
  // Start the counter for restriping rows.
361
  zebraCounter = 0;
362

    
363
  // Search through the search texts in the form for matching text.
364
  var length = this.options.length;
365
  for (i = 0; i < length; i++) {
366
    // Use a local variable for the option being searched, for performance.
367
    option = this.options[i];
368
    found = true;
369
    // Each word in the search string has to match the item in order for the
370
    // item to be shown.
371
    for (j = 0; j < wordsLength; j++) {
372
      if (option.searchText.indexOf(words[j]) === -1) {
373
        found = false;
374
      }
375
    }
376
    if (found) {
377
      // Show the checkbox row, and restripe it.
378
      zebraClass = (zebraCounter % 2) ? 'odd' : 'even';
379
      option.$div.show();
380
      option.$div.removeClass('even odd');
381
      option.$div.addClass(zebraClass);
382
      zebraCounter++;
383
    }
384
    else {
385
      // The search string wasn't found; hide this item.
386
      option.$div.hide();
387
    }
388
  }
389
};
390

    
391

    
392
Drupal.behaviors.viewsUiPreview = {};
393
Drupal.behaviors.viewsUiPreview.attach = function (context, settings) {
394
  var $ = jQuery;
395

    
396
  // Only act on the edit view form.
397
  var contextualFiltersBucket = $('.views-display-column .views-ui-display-tab-bucket.contextual-filters', context);
398
  if (contextualFiltersBucket.length == 0) {
399
    return;
400
  }
401

    
402
  // If the display has no contextual filters, hide the form where you enter
403
  // the contextual filters for the live preview. If it has contextual filters,
404
  // show the form.
405
  var contextualFilters = $('.views-display-setting a', contextualFiltersBucket);
406
  if (contextualFilters.length) {
407
    $('#preview-args').parent().show();
408
  }
409
  else {
410
    $('#preview-args').parent().hide();
411
  }
412

    
413
  // Executes an initial preview.
414
  if ($('#edit-displays-live-preview').once('edit-displays-live-preview').is(':checked')) {
415
    $('#preview-submit').once('edit-displays-live-preview').click();
416
  }
417
};
418

    
419

    
420
Drupal.behaviors.viewsUiRearrangeFilter = {};
421
Drupal.behaviors.viewsUiRearrangeFilter.attach = function (context, settings) {
422
  var $ = jQuery;
423
  // Only act on the rearrange filter form.
424
  if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag['views-rearrange-filters'] == 'undefined') {
425
    return;
426
  }
427

    
428
  var table = $('#views-rearrange-filters', context).once('views-rearrange-filters');
429
  var operator = $('.form-item-filter-groups-operator', context).once('views-rearrange-filters');
430
  if (table.length) {
431
    new Drupal.viewsUi.rearrangeFilterHandler(table, operator);
432
  }
433
};
434

    
435
/**
436
 * Improve the UI of the rearrange filters dialog box.
437
 */
438
Drupal.viewsUi.rearrangeFilterHandler = function (table, operator) {
439
  var $ = jQuery;
440
  // Keep a reference to the <table> being altered and to the div containing
441
  // the filter groups operator dropdown (if it exists).
442
  this.table = table;
443
  this.operator = operator;
444
  this.hasGroupOperator = this.operator.length > 0;
445

    
446
  // Keep a reference to all draggable rows within the table.
447
  this.draggableRows = $('.draggable', table);
448

    
449
  // Keep a reference to the buttons for adding and removing filter groups.
450
  this.addGroupButton = $('input#views-add-group');
451
  this.removeGroupButtons = $('input.views-remove-group', table);
452

    
453
  // Add links that duplicate the functionality of the (hidden) add and remove
454
  // buttons.
455
  this.insertAddRemoveFilterGroupLinks();
456

    
457
  // When there is a filter groups operator dropdown on the page, create
458
  // duplicates of the dropdown between each pair of filter groups.
459
  if (this.hasGroupOperator) {
460
    this.dropdowns = this.duplicateGroupsOperator();
461
    this.syncGroupsOperators();
462
  }
463

    
464
  // Add methods to the tableDrag instance to account for operator cells (which
465
  // span multiple rows), the operator labels next to each filter (e.g., "And"
466
  // or "Or"), the filter groups, and other special aspects of this tableDrag
467
  // instance.
468
  this.modifyTableDrag();
469

    
470
  // Initialize the operator labels (e.g., "And" or "Or") that are displayed
471
  // next to the filters in each group, and bind a handler so that they change
472
  // based on the values of the operator dropdown within that group.
473
  this.redrawOperatorLabels();
474
  $('.views-group-title select', table)
475
    .once('views-rearrange-filter-handler')
476
    .bind('change.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
477

    
478
  // Bind handlers so that when a "Remove" link is clicked, we:
479
  // - Update the rowspans of cells containing an operator dropdown (since they
480
  //   need to change to reflect the number of rows in each group).
481
  // - Redraw the operator labels next to the filters in the group (since the
482
  //   filter that is currently displayed last in each group is not supposed to
483
  //   have a label display next to it).
484
  $('a.views-groups-remove-link', this.table)
485
    .once('views-rearrange-filter-handler')
486
    .bind('click.views-rearrange-filter-handler', $.proxy(this, 'updateRowspans'))
487
    .bind('click.views-rearrange-filter-handler', $.proxy(this, 'redrawOperatorLabels'));
488
};
489

    
490
/**
491
 * Insert links that allow filter groups to be added and removed.
492
 */
493
Drupal.viewsUi.rearrangeFilterHandler.prototype.insertAddRemoveFilterGroupLinks = function () {
494
  var $ = jQuery;
495

    
496
  // Insert a link for adding a new group at the top of the page, and make it
497
  // match the action links styling used in a typical page.tpl.php. Note that
498
  // Drupal does not provide a theme function for this markup, so this is the
499
  // best we can do.
500
  $('<ul class="action-links"><li><a id="views-add-group-link" href="#">' + this.addGroupButton.val() + '</a></li></ul>')
501
    .prependTo(this.table.parent())
502
    // When the link is clicked, dynamically click the hidden form button for
503
    // adding a new filter group.
504
    .once('views-rearrange-filter-handler')
505
    .bind('click.views-rearrange-filter-handler', $.proxy(this, 'clickAddGroupButton'));
506

    
507
  // Find each (visually hidden) button for removing a filter group and insert
508
  // a link next to it.
509
  var length = this.removeGroupButtons.length;
510
  for (i = 0; i < length; i++) {
511
    var $removeGroupButton = $(this.removeGroupButtons[i]);
512
    var buttonId = $removeGroupButton.attr('id');
513
    $('<a href="#" class="views-remove-group-link">' + Drupal.t('Remove group') + '</a>')
514
      .insertBefore($removeGroupButton)
515
      // When the link is clicked, dynamically click the corresponding form
516
      // button.
517
      .once('views-rearrange-filter-handler')
518
      .bind('click.views-rearrange-filter-handler', {buttonId: buttonId}, $.proxy(this, 'clickRemoveGroupButton'));
519
  }
520
};
521

    
522
/**
523
 * Dynamically click the button that adds a new filter group.
524
 */
525
Drupal.viewsUi.rearrangeFilterHandler.prototype.clickAddGroupButton = function () {
526
  // Due to conflicts between Drupal core's AJAX system and the Views AJAX
527
  // system, the only way to get this to work seems to be to trigger both the
528
  // .mousedown() and .submit() events.
529
  this.addGroupButton.mousedown();
530
  this.addGroupButton.submit();
531
  return false;
532
};
533

    
534
/**
535
 * Dynamically click a button for removing a filter group.
536
 *
537
 * @param event
538
 *   Event being triggered, with event.data.buttonId set to the ID of the
539
 *   form button that should be clicked.
540
 */
541
Drupal.viewsUi.rearrangeFilterHandler.prototype.clickRemoveGroupButton = function (event) {
542
  // For some reason, here we only need to trigger .submit(), unlike for
543
  // Drupal.viewsUi.rearrangeFilterHandler.prototype.clickAddGroupButton()
544
  // where we had to trigger .mousedown() also.
545
  jQuery('input#' + event.data.buttonId, this.table).submit();
546
  return false;
547
};
548

    
549
/**
550
 * Move the groups operator so that it's between the first two groups, and
551
 * duplicate it between any subsequent groups.
552
 */
553
Drupal.viewsUi.rearrangeFilterHandler.prototype.duplicateGroupsOperator = function () {
554
  var $ = jQuery;
555
  var dropdowns, newRow;
556

    
557
  var titleRows = $('tr.views-group-title'), titleRow;
558

    
559
  // Get rid of the explanatory text around the operator; its placement is
560
  // explanatory enough.
561
  this.operator.find('label').add('div.description').addClass('element-invisible');
562
  this.operator.find('select').addClass('form-select');
563

    
564
  // Keep a list of the operator dropdowns, so we can sync their behavior later.
565
  dropdowns = this.operator;
566

    
567
  // Move the operator to a new row just above the second group.
568
  titleRow = $('tr#views-group-title-2');
569
  newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
570
  newRow.find('td').append(this.operator);
571
  newRow.insertBefore(titleRow);
572
  var i, length = titleRows.length;
573
  // Starting with the third group, copy the operator to a new row above the
574
  // group title.
575
  for (i = 2; i < length; i++) {
576
    titleRow = $(titleRows[i]);
577
    // Make a copy of the operator dropdown and put it in a new table row.
578
    var fakeOperator = this.operator.clone();
579
    fakeOperator.attr('id', '');
580
    newRow = $('<tr class="filter-group-operator-row"><td colspan="5"></td></tr>');
581
    newRow.find('td').append(fakeOperator);
582
    newRow.insertBefore(titleRow);
583
    dropdowns = dropdowns.add(fakeOperator);
584
  }
585

    
586
  return dropdowns;
587
};
588

    
589
/**
590
 * Make the duplicated groups operators change in sync with each other.
591
 */
592
Drupal.viewsUi.rearrangeFilterHandler.prototype.syncGroupsOperators = function () {
593
  if (this.dropdowns.length < 2) {
594
    // We only have one dropdown (or none at all), so there's nothing to sync.
595
    return;
596
  }
597

    
598
  this.dropdowns.change(jQuery.proxy(this, 'operatorChangeHandler'));
599
};
600

    
601
/**
602
 * Click handler for the operators that appear between filter groups.
603
 *
604
 * Forces all operator dropdowns to have the same value.
605
 */
606
Drupal.viewsUi.rearrangeFilterHandler.prototype.operatorChangeHandler = function (event) {
607
  var $ = jQuery;
608
  var $target = $(event.target);
609
  var operators = this.dropdowns.find('select').not($target);
610

    
611
  // Change the other operators to match this new value.
612
  operators.val($target.val());
613
};
614

    
615
Drupal.viewsUi.rearrangeFilterHandler.prototype.modifyTableDrag = function () {
616
  var tableDrag = Drupal.tableDrag['views-rearrange-filters'];
617
  var filterHandler = this;
618

    
619
  /**
620
   * Override the row.onSwap method from tabledrag.js.
621
   *
622
   * When a row is dragged to another place in the table, several things need
623
   * to occur.
624
   * - The row needs to be moved so that it's within one of the filter groups.
625
   * - The operator cells that span multiple rows need their rowspan attributes
626
   *   updated to reflect the number of rows in each group.
627
   * - The operator labels that are displayed next to each filter need to be
628
   *   redrawn, to account for the row's new location.
629
   */
630
  tableDrag.row.prototype.onSwap = function () {
631
    if (filterHandler.hasGroupOperator) {
632
      // Make sure the row that just got moved (this.group) is inside one of
633
      // the filter groups (i.e. below an empty marker row or a draggable). If
634
      // it isn't, move it down one.
635
      var thisRow = jQuery(this.group);
636
      var previousRow = thisRow.prev('tr');
637
      if (previousRow.length && !previousRow.hasClass('group-message') && !previousRow.hasClass('draggable')) {
638
        // Move the dragged row down one.
639
        var next = thisRow.next();
640
        if (next.is('tr')) {
641
          this.swap('after', next);
642
        }
643
      }
644
      filterHandler.updateRowspans();
645
    }
646
    // Redraw the operator labels that are displayed next to each filter, to
647
    // account for the row's new location.
648
    filterHandler.redrawOperatorLabels();
649
  };
650

    
651
  /**
652
   * Override the onDrop method from tabledrag.js.
653
   */
654
  tableDrag.onDrop = function () {
655
    var $ = jQuery;
656

    
657
    // If the tabledrag change marker (i.e., the "*") has been inserted inside
658
    // a row after the operator label (i.e., "And" or "Or") rearrange the items
659
    // so the operator label continues to appear last.
660
    var changeMarker = $(this.oldRowElement).find('.tabledrag-changed');
661
    if (changeMarker.length) {
662
      // Search for occurrences of the operator label before the change marker,
663
      // and reverse them.
664
      var operatorLabel = changeMarker.prevAll('.views-operator-label');
665
      if (operatorLabel.length) {
666
        operatorLabel.insertAfter(changeMarker);
667
      }
668
    }
669

    
670
    // Make sure the "group" dropdown is properly updated when rows are dragged
671
    // into an empty filter group. This is borrowed heavily from the block.js
672
    // Implements tableDrag.onDrop().
673
    var groupRow = $(this.rowObject.element).prevAll('tr.group-message').get(0);
674
    var groupName = groupRow.className.replace(/([^ ]+[ ]+)*group-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
675
    var groupField = $('select.views-group-select', this.rowObject.element);
676
    if ($(this.rowObject.element).prev('tr').is('.group-message') && !groupField.is('.views-group-select-' + groupName)) {
677
      var oldGroupName = groupField.attr('class').replace(/([^ ]+[ ]+)*views-group-select-([^ ]+)([ ]+[^ ]+)*/, '$2');
678
      groupField.removeClass('views-group-select-' + oldGroupName).addClass('views-group-select-' + groupName);
679
      groupField.val(groupName);
680
    }
681
  };
682
};
683

    
684

    
685
/**
686
 * Redraw the operator labels that are displayed next to each filter.
687
 */
688
Drupal.viewsUi.rearrangeFilterHandler.prototype.redrawOperatorLabels = function () {
689
  var $ = jQuery;
690
  for (i = 0; i < this.draggableRows.length; i++) {
691
    // Within the row, the operator labels are displayed inside the first table
692
    // cell (next to the filter name).
693
    var $draggableRow = $(this.draggableRows[i]);
694
    var $firstCell = $('td:first', $draggableRow);
695
    if ($firstCell.length) {
696
      // The value of the operator label ("And" or "Or") is taken from the
697
      // first operator dropdown we encounter, going backwards from the current
698
      // row. This dropdown is the one associated with the current row's filter
699
      // group.
700
      var operatorValue = $draggableRow.prevAll('.views-group-title').find('option:selected').html();
701
      var operatorLabel = '<span class="views-operator-label">' + operatorValue + '</span>';
702
      // If the next visible row after this one is a draggable filter row,
703
      // display the operator label next to the current row. (Checking for
704
      // visibility is necessary here since the "Remove" links hide the removed
705
      // row but don't actually remove it from the document).
706
      var $nextRow = $draggableRow.nextAll(':visible').eq(0);
707
      var $existingOperatorLabel = $firstCell.find('.views-operator-label');
708
      if ($nextRow.hasClass('draggable')) {
709
        // If an operator label was already there, replace it with the new one.
710
        if ($existingOperatorLabel.length) {
711
          $existingOperatorLabel.replaceWith(operatorLabel);
712
        }
713
        // Otherwise, append the operator label to the end of the table cell.
714
        else {
715
          $firstCell.append(operatorLabel);
716
        }
717
      }
718
      // If the next row doesn't contain a filter, then this is the last row
719
      // in the group. We don't want to display the operator there (since
720
      // operators should only display between two related filters, e.g.
721
      // "filter1 AND filter2 AND filter3"). So we remove any existing label
722
      // that this row has.
723
      else {
724
        $existingOperatorLabel.remove();
725
      }
726
    }
727
  }
728
};
729

    
730
/**
731
 * Update the rowspan attribute of each cell containing an operator dropdown.
732
 */
733
Drupal.viewsUi.rearrangeFilterHandler.prototype.updateRowspans = function () {
734
  var $ = jQuery;
735
  var i, $row, $currentEmptyRow, draggableCount, $operatorCell;
736
  var rows = $(this.table).find('tr');
737
  var length = rows.length;
738
  for (i = 0; i < length; i++) {
739
    $row = $(rows[i]);
740
    if ($row.hasClass('views-group-title')) {
741
      // This row is a title row.
742
      // Keep a reference to the cell containing the dropdown operator.
743
      $operatorCell = $($row.find('td.group-operator'));
744
      // Assume this filter group is empty, until we find otherwise.
745
      draggableCount = 0;
746
      $currentEmptyRow = $row.next('tr');
747
      $currentEmptyRow.removeClass('group-populated').addClass('group-empty');
748
      // The cell with the dropdown operator should span the title row and
749
      // the "this group is empty" row.
750
      $operatorCell.attr('rowspan', 2);
751
    }
752
    else if (($row).hasClass('draggable') && $row.is(':visible')) {
753
      // We've found a visible filter row, so we now know the group isn't empty.
754
      draggableCount++;
755
      $currentEmptyRow.removeClass('group-empty').addClass('group-populated');
756
      // The operator cell should span all draggable rows, plus the title.
757
      $operatorCell.attr('rowspan', draggableCount + 1);
758
    }
759
  }
760
};
761

    
762
Drupal.behaviors.viewsFilterConfigSelectAll = {};
763

    
764
/**
765
 * Add a select all checkbox, which checks each checkbox at once.
766
 */
767
Drupal.behaviors.viewsFilterConfigSelectAll.attach = function(context) {
768
  var $ = jQuery;
769
  // Show the select all checkbox.
770
  $('#views-ui-config-item-form div.form-item-options-value-all', context).once(function() {
771
    $(this).show();
772
  })
773
    .find('input[type=checkbox]')
774
    .click(function() {
775
      var checked = $(this).is(':checked');
776
      // Update all checkbox beside the select all checkbox.
777
      $(this).parents('.form-checkboxes').find('input[type=checkbox]').each(function() {
778
        $(this).attr('checked', checked);
779
      });
780
    });
781
  // Uncheck the select all checkbox if any of the others are unchecked.
782
  $('#views-ui-config-item-form div.form-type-checkbox').not($('.form-item-options-value-all')).find('input[type=checkbox]').each(function() {
783
    $(this).click(function() {
784
      if ($(this).is('checked') == 0) {
785
        $('#edit-options-value-all').removeAttr('checked');
786
      }
787
    });
788
  });
789
};
790

    
791
/**
792
 * Ensure the desired default button is used when a form is implicitly submitted via an ENTER press on textfields, radios, and checkboxes.
793
 *
794
 * @see http://www.w3.org/TR/html5/association-of-controls-and-forms.html#implicit-submission
795
 */
796
Drupal.behaviors.viewsImplicitFormSubmission = {};
797
Drupal.behaviors.viewsImplicitFormSubmission.attach = function (context, settings) {
798
  var $ = jQuery;
799
  $(':text, :password, :radio, :checkbox', context).once('viewsImplicitFormSubmission', function() {
800
    $(this).keypress(function(event) {
801
      if (event.which == 13) {
802
        var formId = this.form.id;
803
        if (formId && settings.viewsImplicitFormSubmission && settings.viewsImplicitFormSubmission[formId] && settings.viewsImplicitFormSubmission[formId].defaultButton) {
804
          event.preventDefault();
805
          var buttonId = settings.viewsImplicitFormSubmission[formId].defaultButton;
806
          var $button = $('#' + buttonId, this.form);
807
          if ($button.length == 1 && $button.is(':enabled')) {
808
            if (Drupal.ajax && Drupal.ajax[buttonId]) {
809
              $button.trigger(Drupal.ajax[buttonId].element_settings.event);
810
            }
811
            else {
812
              $button.click();
813
            }
814
          }
815
        }
816
      }
817
    });
818
  });
819
};
820

    
821
/**
822
 * Remove icon class from elements that are themed as buttons or dropbuttons.
823
 */
824
Drupal.behaviors.viewsRemoveIconClass = {};
825
Drupal.behaviors.viewsRemoveIconClass.attach = function (context, settings) {
826
  jQuery('.ctools-button', context).once('RemoveIconClass', function () {
827
    var $ = jQuery;
828
    var $this = $(this);
829
    $('.icon', $this).removeClass('icon');
830
    $('.horizontal', $this).removeClass('horizontal');
831
  });
832
};
833

    
834
/**
835
 * Change "Expose filter" buttons into checkboxes.
836
 */
837
Drupal.behaviors.viewsUiCheckboxify = {};
838
Drupal.behaviors.viewsUiCheckboxify.attach = function (context, settings) {
839
  var $ = jQuery;
840
  var $buttons = $('#edit-options-expose-button-button, #edit-options-group-button-button').once('views-ui-checkboxify');
841
  var length = $buttons.length;
842
  var i;
843
  for (i = 0; i < length; i++) {
844
    new Drupal.viewsUi.Checkboxifier($buttons[i]);
845
  }
846
};
847

    
848
/**
849
 * Change the default widget to select the default group according to the
850
 * selected widget for the exposed group.
851
 */
852
Drupal.behaviors.viewsUiChangeDefaultWidget = {};
853
Drupal.behaviors.viewsUiChangeDefaultWidget.attach = function (context, settings) {
854
  var $ = jQuery;
855
  function change_default_widget(multiple) {
856
    if (multiple) {
857
      $('input.default-radios').hide();
858
      $('td.any-default-radios-row').parent().hide();
859
      $('input.default-checkboxes').show();
860
    }
861
    else {
862
      $('input.default-checkboxes').hide();
863
      $('td.any-default-radios-row').parent().show();
864
      $('input.default-radios').show();
865
    }
866
  }
867
  // Update on widget change.
868
  $('input[name="options[group_info][multiple]"]').change(function() {
869
    change_default_widget($(this).attr("checked"));
870
  });
871
  // Update the first time the form is rendered.
872
  $('input[name="options[group_info][multiple]"]').trigger('change');
873
};
874

    
875
/**
876
 * Attaches an expose filter button to a checkbox that triggers its click event.
877
 *
878
 * @param button
879
 *   The DOM object representing the button to be checkboxified.
880
 */
881
Drupal.viewsUi.Checkboxifier = function (button) {
882
  var $ = jQuery;
883
  this.$button = $(button);
884
  this.$parent = this.$button.parent('div.views-expose, div.views-grouped');
885
  this.$input = this.$parent.find('input:checkbox, input:radio');
886
  // Hide the button and its description.
887
  this.$button.hide();
888
  this.$parent.find('.exposed-description, .grouped-description').hide();
889

    
890
  this.$input.click($.proxy(this, 'clickHandler'));
891

    
892
};
893

    
894
/**
895
 * When the checkbox is checked or unchecked, simulate a button press.
896
 */
897
Drupal.viewsUi.Checkboxifier.prototype.clickHandler = function (e) {
898
  this.$button.mousedown();
899
  this.$button.submit();
900
};
901

    
902
/**
903
 * Change the Apply button text based upon the override select state.
904
 */
905
Drupal.behaviors.viewsUiOverrideSelect = {};
906
Drupal.behaviors.viewsUiOverrideSelect.attach = function (context, settings) {
907
  var $ = jQuery;
908
  $('#edit-override-dropdown', context).once('views-ui-override-button-text', function() {
909
    // Closures! :(
910
    var $submit = $('#edit-submit', context);
911
    var old_value = $submit.val();
912

    
913
    $submit.once('views-ui-override-button-text')
914
      .bind('mouseup', function() {
915
        $(this).val(old_value);
916
        return true;
917
      });
918

    
919
    $(this).bind('change', function() {
920
      if ($(this).val() == 'default') {
921
        $submit.val(Drupal.t('Apply (all displays)'));
922
      }
923
      else if ($(this).val() == 'default_revert') {
924
        $submit.val(Drupal.t('Revert to default'));
925
      }
926
      else {
927
        $submit.val(Drupal.t('Apply (this display)'));
928
      }
929
    })
930
      .trigger('change');
931
  });
932

    
933
};
934

    
935
Drupal.viewsUi.resizeModal = function (e, no_shrink) {
936
  var $ = jQuery;
937
  var $modal = $('.views-ui-dialog');
938
  var $scroll = $('.scroll', $modal);
939
  if ($modal.length == 0 || $modal.css('display') == 'none') {
940
    return;
941
  }
942

    
943
  var maxWidth = parseInt($(window).width() * .85);
944
  // 70% of window.
945
  var minWidth = parseInt($(window).width() * .6);
946
  // 70% of window.
947
  // Set the modal to the minwidth so that our width calculation of
948
  // children works.
949
  $modal.css('width', minWidth);
950
  var width = minWidth;
951

    
952
  // Don't let the window get more than 80% of the display high.
953
  var maxHeight = parseInt($(window).height() * .8);
954
  var minHeight = 200;
955
  if (no_shrink) {
956
    minHeight = $modal.height();
957
  }
958

    
959
  if (minHeight > maxHeight) {
960
    minHeight = maxHeight;
961
  }
962

    
963
  var height = 0;
964

    
965
  // Calculate the height of the 'scroll' region.
966
  var scrollHeight = 0;
967

    
968
  scrollHeight += parseInt($scroll.css('padding-top'));
969
  scrollHeight += parseInt($scroll.css('padding-bottom'));
970

    
971
  $scroll.children().each(function() {
972
    var w = $(this).innerWidth();
973
    if (w > width) {
974
      width = w;
975
    }
976
    scrollHeight += $(this).outerHeight(true);
977
  });
978

    
979
  // Now, calculate what the difference between the scroll and the modal
980
  // will be.
981
  var difference = 0;
982
  difference += parseInt($scroll.css('padding-top'));
983
  difference += parseInt($scroll.css('padding-bottom'));
984
  difference += $('.views-override').outerHeight(true) || 0;
985
  difference += $('.views-messages').outerHeight(true) || 0;
986
  difference += $('#views-ajax-title').outerHeight(true) || 0;
987
  difference += $('.views-add-form-selected').outerHeight(true) || 0;
988
  difference += $('.form-buttons', $modal).outerHeight(true) || 0;
989

    
990
  height = scrollHeight + difference;
991

    
992
  if (height > maxHeight) {
993
    height = maxHeight;
994
    scrollHeight = maxHeight - difference;
995
  }
996
  else if (height < minHeight) {
997
    height = minHeight;
998
    scrollHeight = minHeight - difference;
999
  }
1000

    
1001
  if (width > maxWidth) {
1002
    width = maxWidth;
1003
  }
1004

    
1005
  // Get where we should move content to.
1006
  var top = ($(window).height() / 2) - (height / 2);
1007
  var left = ($(window).width() / 2) - (width / 2);
1008

    
1009
  $modal.css({
1010
    'top': top + 'px',
1011
    'left': left + 'px',
1012
    'width': width + 'px',
1013
    'height': height + 'px'
1014
  });
1015

    
1016
  // Ensure inner popup height matches.
1017
  $(Drupal.settings.views.ajax.popup).css('height', height + 'px');
1018

    
1019
  $scroll.css({
1020
    'height': scrollHeight + 'px',
1021
    'max-height': scrollHeight + 'px'
1022
  });
1023

    
1024
};
1025

    
1026
jQuery(function() {
1027
  jQuery(window).bind('resize', Drupal.viewsUi.resizeModal);
1028
  jQuery(window).bind('scroll', Drupal.viewsUi.resizeModal);
1029
});