Projet

Général

Profil

Paste
Télécharger (35,7 ko) Statistiques
| Branche: | Révision:

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

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
 * Event handler: resizes overlay according to the size of the parent window.
400
 *
401
 * @param event
402
 *   Event being triggered, with the following restrictions:
403
 *   - event.type: any
404
 *   - event.currentTarget: any
405
 */
406
Drupal.overlay.eventhandlerOuterResize = function (event) {
407
  // Proceed only if the overlay still exists.
408
  if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
409
    return;
410
  }
411

    
412
  // IE6 uses position:absolute instead of position:fixed.
413
  if (typeof document.body.style.maxHeight != 'string') {
414
    this.activeFrame.height($(window).height());
415
  }
416

    
417
  // Allow other scripts to respond to this event.
418
  $(document).trigger('drupalOverlayResize');
419
};
420

    
421
/**
422
 * Event handler: resizes displaced elements so they won't overlap the scrollbar
423
 * of overlay's iframe.
424
 *
425
 * @param event
426
 *   Event being triggered, with the following restrictions:
427
 *   - event.type: any
428
 *   - event.currentTarget: any
429
 */
430
Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) {
431
  // Proceed only if the overlay still exists.
432
  if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
433
    return;
434
  }
435

    
436
  $(this.iframeWindow.document.body).css({
437
    marginTop: Drupal.overlay.getDisplacement('top'),
438
    marginBottom: Drupal.overlay.getDisplacement('bottom')
439
  })
440
  // IE7 isn't reflowing the document immediately.
441
  // @todo This might be fixed in a cleaner way.
442
  .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
443

    
444
  var documentHeight = this.iframeWindow.document.body.clientHeight;
445
  var documentWidth = this.iframeWindow.document.body.clientWidth;
446
  // IE6 doesn't support maxWidth, use width instead.
447
  var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
448

    
449
  if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') {
450
    // We can't use element.clientLeft to detect whether scrollbars are placed
451
    // on the left side of the element when direction is set to "rtl" as most
452
    // browsers dont't support it correctly.
453
    // http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html
454
    // There seems to be absolutely no way to detect whether the scrollbar
455
    // is on the left side in Opera; always expect scrollbar to be on the left.
456
    if ($.browser.opera) {
457
      Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft;
458
    }
459
    else if (this.iframeWindow.document.documentElement.clientLeft) {
460
      Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft;
461
    }
462
    else {
463
      var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body);
464
      var el2 = $('<div></div>').appendTo(el1);
465
      Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft);
466
      el1.remove();
467
    }
468
  }
469

    
470
  // Consider any element that should be visible above the overlay (such as
471
  // a toolbar).
472
  $('.overlay-displace-top, .overlay-displace-bottom').each(function () {
473
    var data = $(this).data();
474
    var maxWidth = documentWidth;
475
    // In IE, Shadow filter makes element to overlap the scrollbar with 1px.
476
    if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) {
477
      maxWidth -= 1;
478
    }
479

    
480
    if (Drupal.overlay.leftSidedScrollbarOffset) {
481
      $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
482
    }
483

    
484
    // Prevent displaced elements overlapping window's scrollbar.
485
    var currentMaxWidth = parseInt($(this).css(maxWidthName));
486
    if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
487
      $(this).css(maxWidthName, maxWidth);
488
      (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
489
    }
490

    
491
    // Use a more rigorous approach if the displaced element still overlaps
492
    // window's scrollbar; clip the element on the right.
493
    var offset = $(this).offset();
494
    var offsetRight = offset.left + $(this).outerWidth();
495
    if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) {
496
      if (Drupal.overlay.leftSidedScrollbarOffset) {
497
        $(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)');
498
      }
499
      else {
500
        $(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)');
501
      }
502
      (data.drupalOverlay = data.drupalOverlay || {}).clip = true;
503
    }
504
  });
505
};
506

    
507
/**
508
 * Event handler: restores size of displaced elements as they were before
509
 * overlay was opened.
510
 *
511
 * @param event
512
 *   Event being triggered, with the following restrictions:
513
 *   - event.type: any
514
 *   - event.currentTarget: any
515
 */
516
Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) {
517
  var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom');
518
  try {
519
    $displacedElements.css({ maxWidth: '', clip: '' });
520
  }
521
  // IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512).
522
  catch (err) {
523
    $displacedElements.attr('style', function (index, attr) {
524
      return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, '');
525
    });
526
  }
527
};
528

    
529
/**
530
 * Event handler: overrides href of administrative links to be opened in
531
 * the overlay.
532
 *
533
 * This click event handler should be bound to any document (for example the
534
 * overlay iframe) of which you want links to open in the overlay.
535
 *
536
 * @param event
537
 *   Event being triggered, with the following restrictions:
538
 *   - event.type: click, mouseup
539
 *   - event.currentTarget: document
540
 *
541
 * @see Drupal.overlayChild.behaviors.addClickHandler
542
 */
543
Drupal.overlay.eventhandlerOverrideLink = function (event) {
544
  // In some browsers the click event isn't fired for right-clicks. Use the
545
  // mouseup event for right-clicks and the click event for everything else.
546
  if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) {
547
    return;
548
  }
549

    
550
  var $target = $(event.target);
551

    
552
  // Only continue if clicked target (or one of its parents) is a link.
553
  if (!$target.is('a')) {
554
    $target = $target.closest('a');
555
    if (!$target.length) {
556
      return;
557
    }
558
  }
559

    
560
  // Never open links in the overlay that contain the overlay-exclude class.
561
  if ($target.hasClass('overlay-exclude')) {
562
    return;
563
  }
564

    
565
  // Close the overlay when the link contains the overlay-close class.
566
  if ($target.hasClass('overlay-close')) {
567
    // Clearing the overlay URL fragment will close the overlay.
568
    $.bbq.removeState('overlay');
569
    return;
570
  }
571

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

    
630
        // When the link has a destination query parameter and that destination
631
        // is an admin link we need to fragmentize it. This will make it reopen
632
        // in the overlay.
633
        var params = $.deparam.querystring(href);
634
        if (params.destination && this.isAdminLink(params.destination)) {
635
          var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination });
636
          $target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination }));
637
        }
638

    
639
        // Make the link open in the immediate parent of the frame, unless the
640
        // link already has a different target.
641
        if (!$target.attr('target')) {
642
          $target.attr('target', '_parent');
643
        }
644
      }
645
    }
646
  }
647
};
648

    
649
/**
650
 * Event handler: opens or closes the overlay based on the current URL fragment.
651
 *
652
 * @param event
653
 *   Event being triggered, with the following restrictions:
654
 *   - event.type: hashchange
655
 *   - event.currentTarget: document
656
 */
657
Drupal.overlay.eventhandlerOperateByURLFragment = function (event) {
658
  // If we changed the hash to reflect an internal redirect in the overlay,
659
  // its location has already been changed, so don't do anything.
660
  if ($.data(window.location, window.location.href) === 'redirect') {
661
    $.data(window.location, window.location.href, null);
662
    return;
663
  }
664

    
665
  // Get the overlay URL from the current URL fragment.
666
  var state = $.bbq.getState('overlay');
667
  if (state) {
668
    // Append render variable, so the server side can choose the right
669
    // rendering and add child frame code to the page if needed.
670
    var url = $.param.querystring(Drupal.settings.basePath + state, { render: 'overlay' });
671

    
672
    this.open(url);
673
    this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
674
  }
675
  // If there is no overlay URL in the fragment and the overlay is (still)
676
  // open, close the overlay.
677
  else if (this.isOpen && !this.isClosing) {
678
    this.close();
679
    this.resetActiveClass(this.getPath(window.location));
680
  }
681
};
682

    
683
/**
684
 * Event handler: makes sure the internal overlay URL is reflected in the parent
685
 * URL fragment.
686
 *
687
 * Normally the parent URL fragment determines the overlay location. However, if
688
 * the overlay redirects internally, the parent doesn't get informed, and the
689
 * parent URL fragment will be out of date. This is a sanity check to make
690
 * sure we're in the right place.
691
 *
692
 * The parent URL fragment is also not updated automatically when overlay's
693
 * open, close or load functions are used directly (instead of through
694
 * eventhandlerOperateByURLFragment).
695
 *
696
 * @param event
697
 *   Event being triggered, with the following restrictions:
698
 *   - event.type: drupalOverlayReady, drupalOverlayClose
699
 *   - event.currentTarget: document
700
 */
701
Drupal.overlay.eventhandlerSyncURLFragment = function (event) {
702
  if (this.isOpen) {
703
    var expected = $.bbq.getState('overlay');
704
    // This is just a sanity check, so we're comparing paths, not query strings.
705
    if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) {
706
      // There may have been a redirect inside the child overlay window that the
707
      // parent wasn't aware of. Update the parent URL fragment appropriately.
708
      var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location);
709
      // Set a 'redirect' flag on the new location so the hashchange event handler
710
      // knows not to change the overlay's content.
711
      $.data(window.location, newLocation, 'redirect');
712
      // Use location.replace() so we don't create an extra history entry.
713
      window.location.replace(newLocation);
714
    }
715
  }
716
  else {
717
    $.bbq.removeState('overlay');
718
  }
719
};
720

    
721
/**
722
 * Event handler: if the child window suggested that the parent refresh on
723
 * close, force a page refresh.
724
 *
725
 * @param event
726
 *   Event being triggered, with the following restrictions:
727
 *   - event.type: drupalOverlayClose
728
 *   - event.currentTarget: document
729
 */
730
Drupal.overlay.eventhandlerRefreshPage = function (event) {
731
  if (Drupal.overlay.refreshPage) {
732
    window.location.reload(true);
733
  }
734
};
735

    
736
/**
737
 * Event handler: dispatches events to the overlay document.
738
 *
739
 * @param event
740
 *   Event being triggered, with the following restrictions:
741
 *   - event.type: any
742
 *   - event.currentTarget: any
743
 */
744
Drupal.overlay.eventhandlerDispatchEvent = function (event) {
745
  if (this.iframeWindow && this.iframeWindow.document) {
746
    this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event);
747
  }
748
};
749

    
750
/**
751
 * Make a regular admin link into a URL that will trigger the overlay to open.
752
 *
753
 * @param link
754
 *   A JavaScript Link object (i.e. an <a> element).
755
 * @param parentLocation
756
 *   (optional) URL to override the parent window's location with.
757
 *
758
 * @return
759
 *   A URL that will trigger the overlay (in the form
760
 *   /node/1#overlay=admin/config).
761
 */
762
Drupal.overlay.fragmentizeLink = function (link, parentLocation) {
763
  // Don't operate on links that are already overlay-ready.
764
  var params = $.deparam.fragment(link.href);
765
  if (params.overlay) {
766
    return link.href;
767
  }
768

    
769
  // Determine the link's original destination. Set ignorePathFromQueryString to
770
  // true to prevent transforming this link into a clean URL while clean URLs
771
  // may be disabled.
772
  var path = this.getPath(link, true);
773
  // Preserve existing query and fragment parameters in the URL, except for
774
  // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment.
775
  var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash;
776

    
777
  // Assemble and return the overlay-ready link.
778
  return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
779
};
780

    
781
/**
782
 * Refresh any regions of the page that are displayed outside the overlay.
783
 *
784
 * @param data
785
 *   An array of objects with information on the page regions to be refreshed.
786
 *   For each object, the key is a CSS class identifying the region to be
787
 *   refreshed, and the value represents the section of the Drupal $page array
788
 *   corresponding to this region.
789
 */
790
Drupal.overlay.refreshRegions = function (data) {
791
  $.each(data, function () {
792
    var region_info = this;
793
    $.each(region_info, function (regionClass) {
794
      var regionName = region_info[regionClass];
795
      var regionSelector = '.' + regionClass;
796
      // Allow special behaviors to detach.
797
      Drupal.detachBehaviors($(regionSelector));
798
      $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) {
799
        $(regionSelector).replaceWith($(newElement));
800
        Drupal.attachBehaviors($(regionSelector), Drupal.settings);
801
      });
802
    });
803
  });
804
};
805

    
806
/**
807
 * Reset the active class on links in displaced elements according to
808
 * given path.
809
 *
810
 * @param activePath
811
 *   Path to match links against.
812
 */
813
Drupal.overlay.resetActiveClass = function(activePath) {
814
  var self = this;
815
  var windowDomain = window.location.protocol + window.location.hostname;
816

    
817
  $('.overlay-displace-top, .overlay-displace-bottom')
818
  .find('a[href]')
819
  // Remove active class from all links in displaced elements.
820
  .removeClass('active')
821
  // Add active class to links that match activePath.
822
  .each(function () {
823
    var linkDomain = this.protocol + this.hostname;
824
    var linkPath = self.getPath(this);
825

    
826
    // A link matches if it is part of the active trail of activePath, except
827
    // for frontpage links.
828
    if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
829
      $(this).addClass('active');
830
    }
831
  });
832
};
833

    
834
/**
835
 * Helper function to get the (corrected) Drupal path of a link.
836
 *
837
 * @param link
838
 *   Link object or string to get the Drupal path from.
839
 * @param ignorePathFromQueryString
840
 *   Boolean whether to ignore path from query string if path appears empty.
841
 *
842
 * @return
843
 *   The Drupal path.
844
 */
845
Drupal.overlay.getPath = function (link, ignorePathFromQueryString) {
846
  if (typeof link == 'string') {
847
    // Create a native Link object, so we can use its object methods.
848
    link = $(link.link(link)).get(0);
849
  }
850

    
851
  var path = link.pathname;
852
  // Ensure a leading slash on the path, omitted in some browsers.
853
  if (path.charAt(0) != '/') {
854
    path = '/' + path;
855
  }
856
  path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), '');
857
  if (path == '' && !ignorePathFromQueryString) {
858
    // If the path appears empty, it might mean the path is represented in the
859
    // query string (clean URLs are not used).
860
    var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search);
861
    if (match && match.length == 4) {
862
      path = match[2];
863
    }
864
  }
865

    
866
  return path;
867
};
868

    
869
/**
870
 * Get the total displacement of given region.
871
 *
872
 * @param region
873
 *   Region name. Either "top" or "bottom".
874
 *
875
 * @return
876
 *   The total displacement of given region in pixels.
877
 */
878
Drupal.overlay.getDisplacement = function (region) {
879
  var displacement = 0;
880
  var lastDisplaced = $('.overlay-displace-' + region + ':last');
881
  if (lastDisplaced.length) {
882
    displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight();
883

    
884
    // In modern browsers (including IE9), when box-shadow is defined, use the
885
    // normal height.
886
    var cssBoxShadowValue = lastDisplaced.css('box-shadow');
887
    var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
888
    // In IE8 and below, we use the shadow filter to apply box-shadow styles to
889
    // the toolbar. It adds some extra height that we need to remove.
890
    if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) {
891
      displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength;
892
      displacement = Math.max(0, displacement);
893
    }
894
  }
895
  return displacement;
896
};
897

    
898
/**
899
 * Makes elements outside the overlay unreachable via the tab key.
900
 *
901
 * @param context
902
 *   The part of the DOM that should have its tabindexes changed. Defaults to
903
 *   the entire page.
904
 */
905
Drupal.overlay.makeDocumentUntabbable = function (context) {
906

    
907
  context = context || document.body;
908
  var $overlay, $tabbable, $hasTabindex;
909

    
910
  // Determine which elements on the page already have a tabindex.
911
  $hasTabindex = $('[tabindex] :not(.overlay-element)', context);
912
  // Record the tabindex for each element, so we can restore it later.
913
  $hasTabindex.each(Drupal.overlay._recordTabindex);
914
  // Add the tabbable elements from the current context to any that we might
915
  // have previously recorded.
916
  Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex);
917

    
918
  // Set tabindex to -1 on everything outside the overlay and toolbars, so that
919
  // the underlying page is unreachable.
920

    
921
  // By default, browsers make a, area, button, input, object, select, textarea,
922
  // and iframe elements reachable via the tab key.
923
  $tabbable = $('a, area, button, input, object, select, textarea, iframe');
924
  // If another element (like a div) has a tabindex, it's also tabbable.
925
  $tabbable = $tabbable.add($hasTabindex);
926
  // Leave links inside the overlay and toolbars alone.
927
  $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*');
928
  $tabbable = $tabbable.not($overlay);
929
  // We now have a list of everything in the underlying document that could
930
  // possibly be reachable via the tab key. Make it all unreachable.
931
  $tabbable.attr('tabindex', -1);
932
};
933

    
934
/**
935
 * Restores the original tabindex value of a group of elements.
936
 *
937
 * @param context
938
 *   The part of the DOM that should have its tabindexes restored. Defaults to
939
 *   the entire page.
940
 */
941
Drupal.overlay.makeDocumentTabbable = function (context) {
942

    
943
  var $needsTabindex;
944
  context = context || document.body;
945

    
946
  // Make the underlying document tabbable again by removing all existing
947
  // tabindex attributes.
948
  var $tabindex = $('[tabindex]', context);
949
  $tabindex.removeAttr('tabindex');
950

    
951
  // Restore the tabindex attributes that existed before the overlay was opened.
952
  $needsTabindex = $(Drupal.overlay._hasTabindex, context);
953
  $needsTabindex.each(Drupal.overlay._restoreTabindex);
954
  Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex);
955
};
956

    
957
/**
958
 * Record the tabindex for an element, using $.data.
959
 *
960
 * Meant to be used as a jQuery.fn.each callback.
961
 */
962
Drupal.overlay._recordTabindex = function () {
963
  var $element = $(this);
964
  var tabindex = $(this).attr('tabindex');
965
  $element.data('drupalOverlayOriginalTabIndex', tabindex);
966
};
967

    
968
/**
969
 * Restore an element's original tabindex.
970
 *
971
 * Meant to be used as a jQuery.fn.each callback.
972
 */
973
Drupal.overlay._restoreTabindex = function () {
974
  var $element = $(this);
975
  var tabindex = $element.data('drupalOverlayOriginalTabIndex');
976
  $element.attr('tabindex', tabindex);
977
};
978

    
979
/**
980
 * Theme function to create the overlay iframe element.
981
 */
982
Drupal.theme.prototype.overlayContainer = function () {
983
  return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>';
984
};
985

    
986
/**
987
 * Theme function to create an overlay iframe element.
988
 */
989
Drupal.theme.prototype.overlayElement = function (url) {
990
  return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>';
991
};
992

    
993
})(jQuery);