Projet

Général

Profil

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

root / drupal7 / sites / all / modules / jquery_update / replace / misc / 1.9 / overlay-parent.js @ 2c8c2b87

1
/**
2
 * Modified by ericduran for jQuery Update compatibility.
3
 *
4
 * Patches overlay-parent.js for jQuery 1.9.1 compatibility.
5
 */
6

    
7
/**
8
 * @file
9
 * Attaches the behaviors for the Overlay parent pages.
10
 */
11

    
12
(function ($) {
13

    
14
/**
15
 * Open the overlay, or load content into it, when an admin link is clicked.
16
 */
17
Drupal.behaviors.overlayParent = {
18
  attach: function (context, settings) {
19
    if (Drupal.overlay.isOpen) {
20
      Drupal.overlay.makeDocumentUntabbable(context);
21
    }
22

    
23
    if (this.processed) {
24
      return;
25
    }
26
    this.processed = true;
27

    
28
    $(window)
29
      // When the hash (URL fragment) changes, open the overlay if needed.
30
      .bind('hashchange.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOperateByURLFragment'))
31
      // Trigger the hashchange handler once, after the page is loaded, so that
32
      // permalinks open the overlay.
33
      .triggerHandler('hashchange.drupal-overlay');
34

    
35
    $(document)
36
      // Instead of binding a click event handler to every link we bind one to
37
      // the document and only handle events that bubble up. This allows other
38
      // scripts to bind their own handlers to links and also to prevent
39
      // overlay's handling.
40
      .bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOverrideLink'));
41
  }
42
};
43

    
44
/**
45
 * Overlay object for parent windows.
46
 *
47
 * Events
48
 * Overlay triggers a number of events that can be used by other scripts.
49
 * - drupalOverlayOpen: This event is triggered when the overlay is opened.
50
 * - drupalOverlayBeforeClose: This event is triggered when the overlay attempts
51
 *   to close. If an event handler returns false, the close will be prevented.
52
 * - drupalOverlayClose: This event is triggered when the overlay is closed.
53
 * - drupalOverlayBeforeLoad: This event is triggered right before a new URL
54
 *   is loaded into the overlay.
55
 * - drupalOverlayReady: This event is triggered when the DOM of the overlay
56
 *   child document is fully loaded.
57
 * - drupalOverlayLoad: This event is triggered when the overlay is finished
58
 *   loading.
59
 * - drupalOverlayResize: This event is triggered when the overlay is being
60
 *   resized to match the parent window.
61
 */
62
Drupal.overlay = Drupal.overlay || {
63
  isOpen: false,
64
  isOpening: false,
65
  isClosing: false,
66
  isLoading: false
67
};
68

    
69
Drupal.overlay.prototype = {};
70

    
71
/**
72
 * Open the overlay.
73
 *
74
 * @param url
75
 *   The URL of the page to open in the overlay.
76
 *
77
 * @return
78
 *   TRUE if the overlay was opened, FALSE otherwise.
79
 */
80
Drupal.overlay.open = function (url) {
81
  // Just one overlay is allowed.
82
  if (this.isOpen || this.isOpening) {
83
    return this.load(url);
84
  }
85
  this.isOpening = true;
86
  // Store the original document title.
87
  this.originalTitle = document.title;
88

    
89
  // Create the dialog and related DOM elements.
90
  this.create();
91

    
92
  this.isOpening = false;
93
  this.isOpen = true;
94
  $(document.documentElement).addClass('overlay-open');
95
  this.makeDocumentUntabbable();
96

    
97
  // Allow other scripts to respond to this event.
98
  $(document).trigger('drupalOverlayOpen');
99

    
100
  return this.load(url);
101
};
102

    
103
/**
104
 * Create the underlying markup and behaviors for the overlay.
105
 */
106
Drupal.overlay.create = function () {
107
  this.$container = $(Drupal.theme('overlayContainer'))
108
    .appendTo(document.body);
109

    
110
  // Overlay uses transparent iframes that cover the full parent window.
111
  // When the overlay is open the scrollbar of the parent window is hidden.
112
  // Because some browsers show a white iframe background for a short moment
113
  // while loading a page into an iframe, overlay uses two iframes. By loading
114
  // the page in a hidden (inactive) iframe the user doesn't see the white
115
  // background. When the page is loaded the active and inactive iframes
116
  // are switched.
117
  this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement'))
118
    .appendTo(this.$container);
119

    
120
  this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
121
    .appendTo(this.$container);
122

    
123
  this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild'));
124
  this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild'));
125

    
126
  // Add a second class "drupal-overlay-open" to indicate these event handlers
127
  // should only be bound when the overlay is open.
128
  var eventClass = '.drupal-overlay.drupal-overlay-open';
129
  $(window)
130
    .bind('resize' + eventClass, $.proxy(this, 'eventhandlerOuterResize'));
131
  $(document)
132
    .bind('drupalOverlayLoad' + eventClass, $.proxy(this, 'eventhandlerOuterResize'))
133
    .bind('drupalOverlayReady' + eventClass +
134
          ' drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerSyncURLFragment'))
135
    .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRefreshPage'))
136
    .bind('drupalOverlayBeforeClose' + eventClass +
137
          ' drupalOverlayBeforeLoad' + eventClass +
138
          ' drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerDispatchEvent'));
139

    
140
  if ($('.overlay-displace-top, .overlay-displace-bottom').length) {
141
    $(document)
142
      .bind('drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerAlterDisplacedElements'))
143
      .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRestoreDisplacedElements'));
144
  }
145
};
146

    
147
/**
148
 * Load the given URL into the overlay iframe.
149
 *
150
 * Use this method to change the URL being loaded in the overlay if it is
151
 * already open.
152
 *
153
 * @return
154
 *   TRUE if URL is loaded into the overlay, FALSE otherwise.
155
 */
156
Drupal.overlay.load = function (url) {
157
  if (!this.isOpen) {
158
    return false;
159
  }
160

    
161
  // Allow other scripts to respond to this event.
162
  $(document).trigger('drupalOverlayBeforeLoad');
163

    
164
  $(document.documentElement).addClass('overlay-loading');
165

    
166
  // The contentDocument property is not supported in IE until IE8.
167
  var iframeDocument = this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document;
168

    
169
  // location.replace doesn't create a history entry. location.href does.
170
  // In this case, we want location.replace, as we're creating the history
171
  // entry using URL fragments.
172
  iframeDocument.location.replace(url);
173

    
174
  return true;
175
};
176

    
177
/**
178
 * Close the overlay and remove markup related to it from the document.
179
 *
180
 * @return
181
 *   TRUE if the overlay was closed, FALSE otherwise.
182
 */
183
Drupal.overlay.close = function () {
184
  // Prevent double execution when close is requested more than once.
185
  if (!this.isOpen || this.isClosing) {
186
    return false;
187
  }
188

    
189
  // Allow other scripts to respond to this event.
190
  var event = $.Event('drupalOverlayBeforeClose');
191
  $(document).trigger(event);
192
  // If a handler returned false, the close will be prevented.
193
  if (event.isDefaultPrevented()) {
194
    return false;
195
  }
196

    
197
  this.isClosing = true;
198
  this.isOpen = false;
199
  $(document.documentElement).removeClass('overlay-open');
200
  // Restore the original document title.
201
  document.title = this.originalTitle;
202
  this.makeDocumentTabbable();
203

    
204
  // Allow other scripts to respond to this event.
205
  $(document).trigger('drupalOverlayClose');
206

    
207
  // When the iframe is still loading don't destroy it immediately but after
208
  // the content is loaded (see Drupal.overlay.loadChild).
209
  if (!this.isLoading) {
210
    this.destroy();
211
    this.isClosing = false;
212
  }
213
  return true;
214
};
215

    
216
/**
217
 * Destroy the overlay.
218
 */
219
Drupal.overlay.destroy = function () {
220
  $([document, window]).unbind('.drupal-overlay-open');
221
  this.$container.remove();
222

    
223
  this.$container = null;
224
  this.$iframeA = null;
225
  this.$iframeB = null;
226

    
227
  this.iframeWindow = null;
228
};
229

    
230
/**
231
 * Redirect the overlay parent window to the given URL.
232
 *
233
 * @param url
234
 *   Can be an absolute URL or a relative link to the domain root.
235
 */
236
Drupal.overlay.redirect = function (url) {
237
  // Create a native Link object, so we can use its object methods.
238
  var link = $(url.link(url)).get(0);
239

    
240
  // If the link is already open, force the hashchange event to simulate reload.
241
  if (window.location.href == link.href) {
242
    $(window).triggerHandler('hashchange.drupal-overlay');
243
  }
244

    
245
  window.location.href = link.href;
246
  return true;
247
};
248

    
249
/**
250
 * Bind the child window.
251
 *
252
 * Note that this function is fired earlier than Drupal.overlay.loadChild.
253
 */
254
Drupal.overlay.bindChild = function (iframeWindow, isClosing) {
255
  this.iframeWindow = iframeWindow;
256

    
257
  // We are done if the child window is closing.
258
  if (isClosing || this.isClosing || !this.isOpen) {
259
    return;
260
  }
261

    
262
  // Allow other scripts to respond to this event.
263
  $(document).trigger('drupalOverlayReady');
264
};
265

    
266
/**
267
 * Event handler: load event handler for the overlay iframe.
268
 *
269
 * @param event
270
 *   Event being triggered, with the following restrictions:
271
 *   - event.type: load
272
 *   - event.currentTarget: iframe
273
 */
274
Drupal.overlay.loadChild = function (event) {
275
  var iframe = event.data.self;
276
  var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
277
  var iframeWindow = iframeDocument.defaultView || iframeDocument.parentWindow;
278
  if (iframeWindow.location == 'about:blank') {
279
    return;
280
  }
281

    
282
  this.isLoading = false;
283
  $(document.documentElement).removeClass('overlay-loading');
284
  event.data.sibling.removeClass('overlay-active').attr({ 'tabindex': -1 });
285

    
286
  // Only continue when overlay is still open and not closing.
287
  if (this.isOpen && !this.isClosing) {
288
    // And child document is an actual overlayChild.
289
    if (iframeWindow.Drupal && iframeWindow.Drupal.overlayChild) {
290
      // Replace the document title with title of iframe.
291
      document.title = iframeWindow.document.title;
292

    
293
      this.activeFrame = $(iframe)
294
        .addClass('overlay-active')
295
        // Add a title attribute to the iframe for accessibility.
296
        .attr('title', Drupal.t('@title dialog', { '@title': iframeWindow.jQuery('#overlay-title').text() })).removeAttr('tabindex');
297
      this.inactiveFrame = event.data.sibling;
298

    
299
      // Load an empty document into the inactive iframe.
300
      (this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document).location.replace('about:blank');
301

    
302
      // Move the focus to just before the "skip to main content" link inside
303
      // the overlay.
304
      this.activeFrame.focus();
305
      var skipLink = iframeWindow.jQuery('a:first');
306
      Drupal.overlay.setFocusBefore(skipLink, iframeWindow.document);
307

    
308
      // Allow other scripts to respond to this event.
309
      $(document).trigger('drupalOverlayLoad');
310
    }
311
    else {
312
      window.location = iframeWindow.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, '');
313
    }
314
  }
315
  else {
316
    this.destroy();
317
  }
318
};
319

    
320
/**
321
 * Creates a placeholder element to receive document focus.
322
 *
323
 * Setting the document focus to a link will make it visible, even if it's a
324
 * "skip to main content" link that should normally be visible only when the
325
 * user tabs to it. This function can be used to set the document focus to
326
 * just before such an invisible link.
327
 *
328
 * @param $element
329
 *   The jQuery element that should receive focus on the next tab press.
330
 * @param document
331
 *   The iframe window element to which the placeholder should be added. The
332
 *   placeholder element has to be created inside the same iframe as the element
333
 *   it precedes, to keep IE happy. (http://bugs.jquery.com/ticket/4059)
334
 */
335
Drupal.overlay.setFocusBefore = function ($element, document) {
336
  // Create an anchor inside the placeholder document.
337
  var placeholder = document.createElement('a');
338
  var $placeholder = $(placeholder).addClass('element-invisible').attr('href', '#');
339
  // Put the placeholder where it belongs, and set the document focus to it.
340
  $placeholder.insertBefore($element);
341
  $placeholder.focus();
342
  // Make the placeholder disappear as soon as it loses focus, so that it
343
  // doesn't appear in the tab order again.
344
  $placeholder.one('blur', function () {
345
    $(this).remove();
346
  });
347
};
348

    
349
/**
350
 * Check if the given link is in the administrative section of the site.
351
 *
352
 * @param url
353
 *   The URL to be tested.
354
 *
355
 * @return boolean
356
 *   TRUE if the URL represents an administrative link, FALSE otherwise.
357
 */
358
Drupal.overlay.isAdminLink = function (url) {
359
  if (Drupal.overlay.isExternalLink(url)) {
360
    return false;
361
  }
362

    
363
  var path = this.getPath(url);
364

    
365
  // Turn the list of administrative paths into a regular expression.
366
  if (!this.adminPathRegExp) {
367
    var prefix = '';
368
    if (Drupal.settings.overlay.pathPrefixes.length) {
369
      // Allow path prefixes used for language negatiation followed by slash,
370
      // and the empty string.
371
      prefix = '(' + Drupal.settings.overlay.pathPrefixes.join('/|') + '/|)';
372
    }
373
    var adminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.admin.replace(/\s+/g, '|') + ')$';
374
    var nonAdminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.non_admin.replace(/\s+/g, '|') + ')$';
375
    adminPaths = adminPaths.replace(/\*/g, '.*');
376
    nonAdminPaths = nonAdminPaths.replace(/\*/g, '.*');
377
    this.adminPathRegExp = new RegExp(adminPaths);
378
    this.nonAdminPathRegExp = new RegExp(nonAdminPaths);
379
  }
380

    
381
  return this.adminPathRegExp.exec(path) && !this.nonAdminPathRegExp.exec(path);
382
};
383

    
384
/**
385
 * Determine whether a link is external to the site.
386
 *
387
 * @param url
388
 *   The URL to be tested.
389
 *
390
 * @return boolean
391
 *   TRUE if the URL is external to the site, FALSE otherwise.
392
 */
393
Drupal.overlay.isExternalLink = function (url) {
394
  var re = RegExp('^((f|ht)tps?:)?//(?!' + window.location.host + ')');
395
  return re.test(url);
396
};
397

    
398
/**
399
 * Constructs an internal URL (relative to this site) from the provided path.
400
 *
401
 * For example, if the provided path is 'admin' and the site is installed at
402
 * http://example.com/drupal, this function will return '/drupal/admin'.
403
 *
404
 * @param path
405
 *   The internal path, without any leading slash.
406
 *
407
 * @return
408
 *   The internal URL derived from the provided path, or null if a valid
409
 *   internal path cannot be constructed (for example, if an attempt to create
410
 *   an external link is detected).
411
 */
412
Drupal.overlay.getInternalUrl = function (path) {
413
  var url = Drupal.settings.basePath + path;
414
  if (!this.isExternalLink(url)) {
415
    return url;
416
  }
417
};
418

    
419
/**
420
 * Event handler: resizes overlay according to the size of the parent window.
421
 *
422
 * @param event
423
 *   Event being triggered, with the following restrictions:
424
 *   - event.type: any
425
 *   - event.currentTarget: any
426
 */
427
Drupal.overlay.eventhandlerOuterResize = function (event) {
428
  // Proceed only if the overlay still exists.
429
  if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
430
    return;
431
  }
432

    
433
  // IE6 uses position:absolute instead of position:fixed.
434
  if (typeof document.body.style.maxHeight != 'string') {
435
    this.activeFrame.height($(window).height());
436
  }
437

    
438
  // Allow other scripts to respond to this event.
439
  $(document).trigger('drupalOverlayResize');
440
};
441

    
442
/**
443
 * Event handler: resizes displaced elements so they won't overlap the scrollbar
444
 * of overlay's iframe.
445
 *
446
 * @param event
447
 *   Event being triggered, with the following restrictions:
448
 *   - event.type: any
449
 *   - event.currentTarget: any
450
 */
451
Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) {
452
  // Proceed only if the overlay still exists.
453
  if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
454
    return;
455
  }
456

    
457
  $(this.iframeWindow.document.body).css({
458
    marginTop: Drupal.overlay.getDisplacement('top'),
459
    marginBottom: Drupal.overlay.getDisplacement('bottom')
460
  })
461
  // IE7 isn't reflowing the document immediately.
462
  // @todo This might be fixed in a cleaner way.
463
  .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
464

    
465
  var documentHeight = this.iframeWindow.document.body.clientHeight;
466
  var documentWidth = this.iframeWindow.document.body.clientWidth;
467
  // IE6 doesn't support maxWidth, use width instead.
468
  var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
469

    
470
  if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') {
471
    // We can't use element.clientLeft to detect whether scrollbars are placed
472
    // on the left side of the element when direction is set to "rtl" as most
473
    // browsers dont't support it correctly.
474
    // http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html
475
    // There seems to be absolutely no way to detect whether the scrollbar
476
    // is on the left side in Opera; always expect scrollbar to be on the left.
477
    if ($.browser.opera) {
478
      Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft;
479
    }
480
    else if (this.iframeWindow.document.documentElement.clientLeft) {
481
      Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft;
482
    }
483
    else {
484
      var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body);
485
      var el2 = $('<div></div>').appendTo(el1);
486
      Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft);
487
      el1.remove();
488
    }
489
  }
490

    
491
  // Consider any element that should be visible above the overlay (such as
492
  // a toolbar).
493
  $('.overlay-displace-top, .overlay-displace-bottom').each(function () {
494
    var data = $(this).data();
495
    var maxWidth = documentWidth;
496
    // In IE, Shadow filter makes element to overlap the scrollbar with 1px.
497
    if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) {
498
      maxWidth -= 1;
499
    }
500

    
501
    if (Drupal.overlay.leftSidedScrollbarOffset) {
502
      $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
503
    }
504

    
505
    // Prevent displaced elements overlapping window's scrollbar.
506
    var currentMaxWidth = parseInt($(this).css(maxWidthName));
507
    if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
508
      $(this).css(maxWidthName, maxWidth);
509
      (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
510
    }
511

    
512
    // Use a more rigorous approach if the displaced element still overlaps
513
    // window's scrollbar; clip the element on the right.
514
    var offset = $(this).offset();
515
    var offsetRight = offset.left + $(this).outerWidth();
516
    if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) {
517
      if (Drupal.overlay.leftSidedScrollbarOffset) {
518
        $(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)');
519
      }
520
      else {
521
        $(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)');
522
      }
523
      (data.drupalOverlay = data.drupalOverlay || {}).clip = true;
524
    }
525
  });
526
};
527

    
528
/**
529
 * Event handler: restores size of displaced elements as they were before
530
 * overlay was opened.
531
 *
532
 * @param event
533
 *   Event being triggered, with the following restrictions:
534
 *   - event.type: any
535
 *   - event.currentTarget: any
536
 */
537
Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) {
538
  var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom');
539
  try {
540
    $displacedElements.css({ maxWidth: '', clip: '' });
541
  }
542
  // IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512).
543
  catch (err) {
544
    $displacedElements.attr('style', function (index, attr) {
545
      return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, '');
546
    });
547
  }
548
};
549

    
550
/**
551
 * Event handler: overrides href of administrative links to be opened in
552
 * the overlay.
553
 *
554
 * This click event handler should be bound to any document (for example the
555
 * overlay iframe) of which you want links to open in the overlay.
556
 *
557
 * @param event
558
 *   Event being triggered, with the following restrictions:
559
 *   - event.type: click, mouseup
560
 *   - event.currentTarget: document
561
 *
562
 * @see Drupal.overlayChild.behaviors.addClickHandler
563
 */
564
Drupal.overlay.eventhandlerOverrideLink = function (event) {
565
  // In some browsers the click event isn't fired for right-clicks. Use the
566
  // mouseup event for right-clicks and the click event for everything else.
567
  if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) {
568
    return;
569
  }
570

    
571
  var $target = $(event.target);
572

    
573
  // Only continue if clicked target (or one of its parents) is a link.
574
  if (!$target.is('a')) {
575
    $target = $target.closest('a');
576
    if (!$target.length) {
577
      return;
578
    }
579
  }
580

    
581
  // Never open links in the overlay that contain the overlay-exclude class.
582
  if ($target.hasClass('overlay-exclude')) {
583
    return;
584
  }
585

    
586
  // Close the overlay when the link contains the overlay-close class.
587
  if ($target.hasClass('overlay-close')) {
588
    // Clearing the overlay URL fragment will close the overlay.
589
    $.bbq.removeState('overlay');
590
    return;
591
  }
592

    
593
  var target = $target[0];
594
  var href = target.href;
595
  // Only handle links that have an href attribute and use the HTTP(S) protocol.
596
  if (href != undefined && href != '' && target.protocol.match(/^https?\:/)) {
597
    var anchor = href.replace(target.ownerDocument.location.href, '');
598
    // Skip anchor links.
599
    if (anchor.length == 0 || anchor.charAt(0) == '#') {
600
      return;
601
    }
602
    // Open admin links in the overlay.
603
    else if (this.isAdminLink(href)) {
604
      // If the link contains the overlay-restore class and the overlay-context
605
      // state is set, also update the parent window's location.
606
      var parentLocation = ($target.hasClass('overlay-restore') && typeof $.bbq.getState('overlay-context') == 'string')
607
        ? this.getInternalUrl($.bbq.getState('overlay-context'))
608
        : null;
609
      href = this.fragmentizeLink($target.get(0), parentLocation);
610
      // Only override default behavior when left-clicking and user is not
611
      // pressing the ALT, CTRL, META (Command key on the Macintosh keyboard)
612
      // or SHIFT key.
613
      if (event.button == 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
614
        // Redirect to a fragmentized href. This will trigger a hashchange event.
615
        this.redirect(href);
616
        // Prevent default action and further propagation of the event.
617
        return false;
618
      }
619
      // Otherwise alter clicked link's href. This is being picked up by
620
      // the default action handler.
621
      else {
622
        $target
623
          // Restore link's href attribute on blur or next click.
624
          .one('blur mousedown', { target: target, href: target.href }, function (event) { $(event.data.target).attr('href', event.data.href); })
625
          .attr('href', href);
626
      }
627
    }
628
    // Non-admin links should close the overlay and open in the main window,
629
    // which is the default action for a link. We only need to handle them
630
    // if the overlay is open and the clicked link is inside the overlay iframe.
631
    else if (this.isOpen && target.ownerDocument === this.iframeWindow.document) {
632
      // Open external links in the immediate parent of the frame, unless the
633
      // link already has a different target.
634
      if (target.hostname != window.location.hostname) {
635
        if (!$target.attr('target')) {
636
          $target.attr('target', '_parent');
637
        }
638
      }
639
      else {
640
        // Add the overlay-context state to the link, so "overlay-restore" links
641
        // can restore the context.
642
        if ($target[0].hash) {
643
          // Leave links with an existing fragment alone. Adding an extra
644
          // parameter to a link like "node/1#section-1" breaks the link.
645
        }
646
        else {
647
          // For links with no existing fragment, add the overlay context.
648
          $target.attr('href', $.param.fragment(href, { 'overlay-context': this.getPath(window.location) + window.location.search }));
649
        }
650

    
651
        // When the link has a destination query parameter and that destination
652
        // is an admin link we need to fragmentize it. This will make it reopen
653
        // in the overlay.
654
        var params = $.deparam.querystring(href);
655
        if (params.destination && this.isAdminLink(params.destination)) {
656
          var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination });
657
          $target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination }));
658
        }
659

    
660
        // Make the link open in the immediate parent of the frame, unless the
661
        // link already has a different target.
662
        if (!$target.attr('target')) {
663
          $target.attr('target', '_parent');
664
        }
665
      }
666
    }
667
  }
668
};
669

    
670
/**
671
 * Event handler: opens or closes the overlay based on the current URL fragment.
672
 *
673
 * @param event
674
 *   Event being triggered, with the following restrictions:
675
 *   - event.type: hashchange
676
 *   - event.currentTarget: document
677
 */
678
Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
679
  // If we changed the hash to reflect an internal redirect in the overlay,
680
  // its location has already been changed, so don't do anything.
681
  if ($.data(window.location, window.location.href) === 'redirect') {
682
    $.data(window.location, window.location.href, null);
683
    return;
684
  }
685

    
686
  // Get the overlay URL from the current URL fragment.
687
  var internalUrl = null;
688
  var state = $.bbq.getState('overlay');
689
  if (state) {
690
    internalUrl = this.getInternalUrl(state);
691
  }
692
  if (internalUrl) {
693
    // Append render variable, so the server side can choose the right
694
    // rendering and add child frame code to the page if needed.
695
    var url = $.param.querystring(internalUrl, { render: 'overlay' });
696

    
697
    this.open(url);
698
    this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
699
  }
700
  // If there is no overlay URL in the fragment and the overlay is (still)
701
  // open, close the overlay.
702
  else if (this.isOpen && !this.isClosing) {
703
    this.close();
704
    this.resetActiveClass(this.getPath(window.location));
705
  }
706
};
707

    
708
/**
709
 * Event handler: makes sure the internal overlay URL is reflected in the parent
710
 * URL fragment.
711
 *
712
 * Normally the parent URL fragment determines the overlay location. However, if
713
 * the overlay redirects internally, the parent doesn't get informed, and the
714
 * parent URL fragment will be out of date. This is a sanity check to make
715
 * sure we're in the right place.
716
 *
717
 * The parent URL fragment is also not updated automatically when overlay's
718
 * open, close or load functions are used directly (instead of through
719
 * eventhandlerOperateByURLFragment).
720
 *
721
 * @param event
722
 *   Event being triggered, with the following restrictions:
723
 *   - event.type: drupalOverlayReady, drupalOverlayClose
724
 *   - event.currentTarget: document
725
 */
726
Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
727
  if (this.isOpen) {
728
    var expected = $.bbq.getState('overlay');
729
    // This is just a sanity check, so we're comparing paths, not query strings.
730
    if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
731
      // There may have been a redirect inside the child overlay window that the
732
      // parent wasn't aware of. Update the parent URL fragment appropriately.
733
      var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
734
      // Set a 'redirect' flag on the new location so the hashchange event handler
735
      // knows not to change the overlay's content.
736
      $.data(window.location, newLocation, 'redirect');
737
      // Use location.replace() so we don't create an extra history entry.
738
      window.location.replace(newLocation);
739
    }
740
  }
741
  else {
742
    $.bbq.removeState('overlay');
743
  }
744
};
745

    
746
/**
747
 * Event handler: if the child window suggested that the parent refresh on
748
 * close, force a page refresh.
749
 *
750
 * @param event
751
 *   Event being triggered, with the following restrictions:
752
 *   - event.type: drupalOverlayClose
753
 *   - event.currentTarget: document
754
 */
755
Drupal.overlay.eventhandlerRefreshPage = function (event) {
756
  if (Drupal.overlay.refreshPage) {
757
    window.location.reload(true);
758
  }
759
};
760

    
761
/**
762
 * Event handler: dispatches events to the overlay document.
763
 *
764
 * @param event
765
 *   Event being triggered, with the following restrictions:
766
 *   - event.type: any
767
 *   - event.currentTarget: any
768
 */
769
Drupal.overlay.eventhandlerDispatchEvent = function (event) {
770
  if (this.iframeWindow && this.iframeWindow.document) {
771
    this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
772
  }
773
};
774

    
775
/**
776
 * Make a regular admin link into a URL that will trigger the overlay to open.
777
 *
778
 * @param link
779
 *   A JavaScript Link object (i.e. an <a> element).
780
 * @param parentLocation
781
 *   (optional) URL to override the parent window's location with.
782
 *
783
 * @return
784
 *   A URL that will trigger the overlay (in the form
785
 *   /node/1#overlay=admin/config).
786
 */
787
Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
788
  // Don't operate on links that are already overlay-ready.
789
  var params = $.deparam.fragment(link.href);
790
  if (params.overlay) {
791
    return link.href;
792
  }
793

    
794
  // Determine the link's original destination. Set ignorePathFromQueryString to
795
  // true to prevent transforming this link into a clean URL while clean URLs
796
  // may be disabled.
797
  var path = this.getPath(link, true);
798
  // Preserve existing query and fragment parameters in the URL, except for
799
  // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
800
  var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
801

    
802
  // Assemble and return the overlay-ready link.
803
  return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
804
};
805

    
806
/**
807
 * Refresh any regions of the page that are displayed outside the overlay.
808
 *
809
 * @param data
810
 *   An array of objects with information on the page regions to be refreshed.
811
 *   For each object, the key is a CSS class identifying the region to be
812
 *   refreshed, and the value represents the section of the Drupal $page array
813
 *   corresponding to this region.
814
 */
815
Drupal.overlay.refreshRegions = function (data) {
816
  $.each(data, function () {
817
    var region_info = this;
818
    $.each(region_info, function (regionClass) {
819
      var regionName = region_info[regionClass];
820
      var regionSelector = '.' + regionClass;
821
      // Allow special behaviors to detach.
822
      Drupal.detachBehaviors($(regionSelector));
823
      $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
824
        $(regionSelector).replaceWith($(newElement));
825
        Drupal.attachBehaviors($(regionSelector), Drupal.settings);
826
      });
827
    });
828
  });
829
};
830

    
831
/**
832
 * Reset the active class on links in displaced elements according to
833
 * given path.
834
 *
835
 * @param activePath
836
 *   Path to match links against.
837
 */
838
Drupal.overlay.resetActiveClass = function(activePath) {
839
  var self = this;
840
  var windowDomain = window.location.protocol + window.location.hostname;
841

    
842
  $('.overlay-displace-top, .overlay-displace-bottom')
843
  .find('a[href]')
844
  // Remove active class from all links in displaced elements.
845
  .removeClass('active')
846
  // Add active class to links that match activePath.
847
  .each(function () {
848
    var linkDomain = this.protocol + this.hostname;
849
    var linkPath = self.getPath(this);
850

    
851
    // A link matches if it is part of the active trail of activePath, except
852
    // for frontpage links.
853
    if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
854
      $(this).addClass('active');
855
    }
856
  });
857
};
858

    
859
/**
860
 * Helper function to get the (corrected) Drupal path of a link.
861
 *
862
 * @param link
863
 *   Link object or string to get the Drupal path from.
864
 * @param ignorePathFromQueryString
865
 *   Boolean whether to ignore path from query string if path appears empty.
866
 *
867
 * @return
868
 *   The Drupal path.
869
 */
870
Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
871
  if (typeof link == 'string') {
872
    // Create a native Link object, so we can use its object methods.
873
    link = $(link.link(link)).get(0);
874
  }
875

    
876
  var path = link.pathname;
877
  // Ensure a leading slash on the path, omitted in some browsers.
878
  if (path.charAt(0) != '/') {
879
    path = '/' + path;
880
  }
881
  path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
882
  if (path == '' && !ignorePathFromQueryString) {
883
    // If the path appears empty, it might mean the path is represented in the
884
    // query string (clean URLs are not used).
885
    var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
886
    if (match && match.length == 4) {
887
      path = match[2];
888
    }
889
  }
890

    
891
  return path;
892
};
893

    
894
/**
895
 * Get the total displacement of given region.
896
 *
897
 * @param region
898
 *   Region name. Either "top" or "bottom".
899
 *
900
 * @return
901
 *   The total displacement of given region in pixels.
902
 */
903
Drupal.overlay.getDisplacement = function (region) {
904
  var displacement = 0;
905
  var lastDisplaced = $('.overlay-displace-' + region + ':last');
906
  if (lastDisplaced.length) {
907
    displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
908

    
909
    // In modern browsers (including IE9), when box-shadow is defined, use the
910
    // normal height.
911
    var cssBoxShadowValue = lastDisplaced.css('box-shadow');
912
    var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
913
    // In IE8 and below, we use the shadow filter to apply box-shadow styles to
914
    // the toolbar. It adds some extra height that we need to remove.
915
    if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
916
      displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
917
      displacement = Math.max(0, displacement);
918
    }
919
  }
920
  return displacement;
921
};
922

    
923
/**
924
 * Makes elements outside the overlay unreachable via the tab key.
925
 *
926
 * @param context
927
 *   The part of the DOM that should have its tabindexes changed. Defaults to
928
 *   the entire page.
929
 */
930
Drupal.overlay.makeDocumentUntabbable = function (context) {
931

    
932
  context = context || document.body;
933
  var $overlay, $tabbable, $hasTabindex;
934

    
935
  // Determine which elements on the page already have a tabindex.
936
  $hasTabindex = $('[tabindex] :not(.overlay-element)', context);
937
  // Record the tabindex for each element, so we can restore it later.
938
  $hasTabindex.each(Drupal.overlay._recordTabindex);
939
  // Add the tabbable elements from the current context to any that we might
940
  // have previously recorded.
941
  Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
942

    
943
  // Set tabindex to -1 on everything outside the overlay and toolbars, so that
944
  // the underlying page is unreachable.
945

    
946
  // By default, browsers make a, area, button, input, object, select, textarea,
947
  // and iframe elements reachable via the tab key.
948
  $tabbable = $('a, area, button, input, object, select, textarea, iframe');
949
  // If another element (like a div) has a tabindex, it's also tabbable.
950
  $tabbable = $tabbable.add($hasTabindex);
951
  // Leave links inside the overlay and toolbars alone.
952
  $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
953
  $tabbable = $tabbable.not($overlay);
954
  // We now have a list of everything in the underlying document that could
955
  // possibly be reachable via the tab key. Make it all unreachable.
956
  $tabbable.attr('tabindex', -1);
957
};
958

    
959
/**
960
 * Restores the original tabindex value of a group of elements.
961
 *
962
 * @param context
963
 *   The part of the DOM that should have its tabindexes restored. Defaults to
964
 *   the entire page.
965
 */
966
Drupal.overlay.makeDocumentTabbable = function (context) {
967

    
968
  var $needsTabindex;
969
  context = context || document.body;
970

    
971
  // Make the underlying document tabbable again by removing all existing
972
  // tabindex attributes.
973
  var $tabindex = $('[tabindex]', context);
974
  $tabindex.removeAttr('tabindex');
975

    
976
  // Restore the tabindex attributes that existed before the overlay was opened.
977
  $needsTabindex = $(Drupal.overlay._hasTabindex, context);
978
  $needsTabindex.each(Drupal.overlay._restoreTabindex);
979
  Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
980
};
981

    
982
/**
983
 * Record the tabindex for an element, using $.data.
984
 *
985
 * Meant to be used as a jQuery.fn.each callback.
986
 */
987
Drupal.overlay._recordTabindex = function () {
988
  var $element = $(this);
989
  var tabindex = $(this).attr('tabindex');
990
  $element.data('drupalOverlayOriginalTabIndex', tabindex);
991
};
992

    
993
/**
994
 * Restore an element's original tabindex.
995
 *
996
 * Meant to be used as a jQuery.fn.each callback.
997
 */
998
Drupal.overlay._restoreTabindex = function () {
999
  var $element = $(this);
1000
  var tabindex = $element.data('drupalOverlayOriginalTabIndex');
1001
  $element.attr('tabindex', tabindex);
1002
};
1003

    
1004
/**
1005
 * Theme function to create the overlay iframe element.
1006
 */
1007
Drupal.theme.prototype.overlayContainer = function () {
1008
  return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
1009
};
1010

    
1011
/**
1012
 * Theme function to create an overlay iframe element.
1013
 */
1014
Drupal.theme.prototype.overlayElement = function (url) {
1015
  return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
1016
};
1017

    
1018
})(jQuery);