Projet

Général

Profil

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

root / drupal7 / modules / overlay / overlay-parent.js @ db2d93dd

1
/**
2
 * @file
3
 * Attaches the behaviors for the Overlay parent pages.
4
 */
5

    
6
(function ($) {
7

    
8
/**
9
 * Open the overlay, or load content into it, when an admin link is clicked.
10
 */
11
Drupal.behaviors.overlayParent = {
12
  attach: function (context, settings) {
13
    if (Drupal.overlay.isOpen) {
14
      Drupal.overlay.makeDocumentUntabbable(context);
15
    }
16

    
17
    if (this.processed) {
18
      return;
19
    }
20
    this.processed = true;
21

    
22
    $(window)
23
      // When the hash (URL fragment) changes, open the overlay if needed.
24
      .bind('hashchange.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOperateByURLFragment'))
25
      // Trigger the hashchange handler once, after the page is loaded, so that
26
      // permalinks open the overlay.
27
      .triggerHandler('hashchange.drupal-overlay');
28

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

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

    
63
Drupal.overlay.prototype = {};
64

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

    
83
  // Create the dialog and related DOM elements.
84
  this.create();
85

    
86
  this.isOpening = false;
87
  this.isOpen = true;
88
  $(document.documentElement).addClass('overlay-open');
89
  this.makeDocumentUntabbable();
90

    
91
  // Allow other scripts to respond to this event.
92
  $(document).trigger('drupalOverlayOpen');
93

    
94
  return this.load(url);
95
};
96

    
97
/**
98
 * Create the underlying markup and behaviors for the overlay.
99
 */
100
Drupal.overlay.create = function () {
101
  this.$container = $(Drupal.theme('overlayContainer'))
102
    .appendTo(document.body);
103

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

    
114
  this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement'))
115
    .appendTo(this.$container);
116

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

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

    
134
  if ($('.overlay-displace-top, .overlay-displace-bottom').length) {
135
    $(document)
136
      .bind('drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerAlterDisplacedElements'))
137
      .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRestoreDisplacedElements'));
138
  }
139
};
140

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

    
155
  // Allow other scripts to respond to this event.
156
  $(document).trigger('drupalOverlayBeforeLoad');
157

    
158
  $(document.documentElement).addClass('overlay-loading');
159

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

    
163
  // location.replace doesn't create a history entry. location.href does.
164
  // In this case, we want location.replace, as we're creating the history
165
  // entry using URL fragments.
166
  iframeDocument.location.replace(url);
167

    
168
  return true;
169
};
170

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

    
183
  // Allow other scripts to respond to this event.
184
  var event = $.Event('drupalOverlayBeforeClose');
185
  $(document).trigger(event);
186
  // If a handler returned false, the close will be prevented.
187
  if (event.isDefaultPrevented()) {
188
    return false;
189
  }
190

    
191
  this.isClosing = true;
192
  this.isOpen = false;
193
  $(document.documentElement).removeClass('overlay-open');
194
  // Restore the original document title.
195
  document.title = this.originalTitle;
196
  this.makeDocumentTabbable();
197

    
198
  // Allow other scripts to respond to this event.
199
  $(document).trigger('drupalOverlayClose');
200

    
201
  // When the iframe is still loading don't destroy it immediately but after
202
  // the content is loaded (see Drupal.overlay.loadChild).
203
  if (!this.isLoading) {
204
    this.destroy();
205
    this.isClosing = false;
206
  }
207
  return true;
208
};
209

    
210
/**
211
 * Destroy the overlay.
212
 */
213
Drupal.overlay.destroy = function () {
214
  $([document, window]).unbind('.drupal-overlay-open');
215
  this.$container.remove();
216

    
217
  this.$container = null;
218
  this.$iframeA = null;
219
  this.$iframeB = null;
220

    
221
  this.iframeWindow = null;
222
};
223

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

    
234
  // If the link is already open, force the hashchange event to simulate reload.
235
  if (window.location.href == link.href) {
236
    $(window).triggerHandler('hashchange.drupal-overlay');
237
  }
238

    
239
  window.location.href = link.href;
240
  return true;
241
};
242

    
243
/**
244
 * Bind the child window.
245
 *
246
 * Note that this function is fired earlier than Drupal.overlay.loadChild.
247
 */
248
Drupal.overlay.bindChild = function (iframeWindow, isClosing) {
249
  this.iframeWindow = iframeWindow;
250

    
251
  // We are done if the child window is closing.
252
  if (isClosing || this.isClosing || !this.isOpen) {
253
    return;
254
  }
255

    
256
  // Allow other scripts to respond to this event.
257
  $(document).trigger('drupalOverlayReady');
258
};
259

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

    
276
  this.isLoading = false;
277
  $(document.documentElement).removeClass('overlay-loading');
278
  event.data.sibling.removeClass('overlay-active').attr({ 'tabindex': -1 });
279

    
280
  // Only continue when overlay is still open and not closing.
281
  if (this.isOpen && !this.isClosing) {
282
    // And child document is an actual overlayChild.
283
    if (iframeWindow.Drupal && iframeWindow.Drupal.overlayChild) {
284
      // Replace the document title with title of iframe.
285
      document.title = iframeWindow.document.title;
286

    
287
      this.activeFrame = $(iframe)
288
        .addClass('overlay-active')
289
        // Add a title attribute to the iframe for accessibility.
290
        .attr('title', Drupal.t('@title dialog', { '@title': iframeWindow.jQuery('#overlay-title').text() })).removeAttr('tabindex');
291
      this.inactiveFrame = event.data.sibling;
292

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

    
296
      // Move the focus to just before the "skip to main content" link inside
297
      // the overlay.
298
      this.activeFrame.focus();
299
      var skipLink = iframeWindow.jQuery('a:first');
300
      Drupal.overlay.setFocusBefore(skipLink, iframeWindow.document);
301

    
302
      // Allow other scripts to respond to this event.
303
      $(document).trigger('drupalOverlayLoad');
304
    }
305
    else {
306
      window.location = iframeWindow.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, '');
307
    }
308
  }
309
  else {
310
    this.destroy();
311
  }
312
};
313

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

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

    
357
  var path = this.getPath(url);
358

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

    
375
  return this.adminPathRegExp.exec(path) && !this.nonAdminPathRegExp.exec(path);
376
};
377

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

    
392
/**
393
 * Event handler: resizes overlay according to the size of the parent window.
394
 *
395
 * @param event
396
 *   Event being triggered, with the following restrictions:
397
 *   - event.type: any
398
 *   - event.currentTarget: any
399
 */
400
Drupal.overlay.eventhandlerOuterResize = function (event) {
401
  // Proceed only if the overlay still exists.
402
  if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) {
403
    return;
404
  }
405

    
406
  // IE6 uses position:absolute instead of position:fixed.
407
  if (typeof document.body.style.maxHeight != 'string') {
408
    this.activeFrame.height($(window).height());
409
  }
410

    
411
  // Allow other scripts to respond to this event.
412
  $(document).trigger('drupalOverlayResize');
413
};
414

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

    
430
  $(this.iframeWindow.document.body).css({
431
    marginTop: Drupal.overlay.getDisplacement('top'),
432
    marginBottom: Drupal.overlay.getDisplacement('bottom')
433
  })
434
  // IE7 isn't reflowing the document immediately.
435
  // @todo This might be fixed in a cleaner way.
436
  .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow');
437

    
438
  var documentHeight = this.iframeWindow.document.body.clientHeight;
439
  var documentWidth = this.iframeWindow.document.body.clientWidth;
440
  // IE6 doesn't support maxWidth, use width instead.
441
  var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width';
442

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

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

    
474
    if (Drupal.overlay.leftSidedScrollbarOffset) {
475
      $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset);
476
    }
477

    
478
    // Prevent displaced elements overlapping window's scrollbar.
479
    var currentMaxWidth = parseInt($(this).css(maxWidthName));
480
    if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) {
481
      $(this).css(maxWidthName, maxWidth);
482
      (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true;
483
    }
484

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

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

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

    
544
  var $target = $(event.target);
545

    
546
  // Only continue if clicked target (or one of its parents) is a link.
547
  if (!$target.is('a')) {
548
    $target = $target.closest('a');
549
    if (!$target.length) {
550
      return;
551
    }
552
  }
553

    
554
  // Never open links in the overlay that contain the overlay-exclude class.
555
  if ($target.hasClass('overlay-exclude')) {
556
    return;
557
  }
558

    
559
  // Close the overlay when the link contains the overlay-close class.
560
  if ($target.hasClass('overlay-close')) {
561
    // Clearing the overlay URL fragment will close the overlay.
562
    $.bbq.removeState('overlay');
563
    return;
564
  }
565

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

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

    
633
        // Make the link open in the immediate parent of the frame, unless the
634
        // link already has a different target.
635
        if (!$target.attr('target')) {
636
          $target.attr('target', '_parent');
637
        }
638
      }
639
    }
640
  }
641
};
642

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

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

    
666
    this.open(url);
667
    this.resetActiveClass(this.getPath(Drupal.settings.basePath + state));
668
  }
669
  // If there is no overlay URL in the fragment and the overlay is (still)
670
  // open, close the overlay.
671
  else if (this.isOpen && !this.isClosing) {
672
    this.close();
673
    this.resetActiveClass(this.getPath(window.location));
674
  }
675
};
676

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

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

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

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

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

    
771
  // Assemble and return the overlay-ready link.
772
  return $.param.fragment(parentLocation || window.location.href, { overlay: destination });
773
};
774

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

    
800
/**
801
 * Reset the active class on links in displaced elements according to
802
 * given path.
803
 *
804
 * @param activePath
805
 *   Path to match links against.
806
 */
807
Drupal.overlay.resetActiveClass = function(activePath) {
808
  var self = this;
809
  var windowDomain = window.location.protocol + window.location.hostname;
810

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

    
820
    // A link matches if it is part of the active trail of activePath, except
821
    // for frontpage links.
822
    if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) {
823
      $(this).addClass('active');
824
    }
825
  });
826
};
827

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

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

    
860
  return path;
861
};
862

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

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

    
892
/**
893
 * Makes elements outside the overlay unreachable via the tab key.
894
 *
895
 * @param context
896
 *   The part of the DOM that should have its tabindexes changed. Defaults to
897
 *   the entire page.
898
 */
899
Drupal.overlay.makeDocumentUntabbable = function (context) {
900
  // Manipulating tabindexes for the entire document is unacceptably slow in IE6
901
  // and IE7, so in those browsers, the underlying page will still be reachable
902
  // via the tab key. However, we still make the links within the Disable
903
  // message unreachable, because the same message also exists within the
904
  // child document. The duplicate copy in the underlying document is only for
905
  // assisting screen-reader users navigating the document with reading commands
906
  // that follow markup order rather than tab order.
907
  if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
908
    $('#overlay-disable-message a', context).attr('tabindex', -1);
909
    return;
910
  }
911

    
912
  context = context || document.body;
913
  var $overlay, $tabbable, $hasTabindex;
914

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

    
923
  // Set tabindex to -1 on everything outside the overlay and toolbars, so that
924
  // the underlying page is unreachable.
925

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

    
939
/**
940
 * Restores the original tabindex value of a group of elements.
941
 *
942
 * @param context
943
 *   The part of the DOM that should have its tabindexes restored. Defaults to
944
 *   the entire page.
945
 */
946
Drupal.overlay.makeDocumentTabbable = function (context) {
947
  // Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those
948
  // browsers, the underlying page was never made unreachable via tab, so
949
  // there is no work to be done here.
950
  if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
951
    return;
952
  }
953

    
954
  var $needsTabindex;
955
  context = context || document.body;
956

    
957
  // Make the underlying document tabbable again by removing all existing
958
  // tabindex attributes.
959
  var $tabindex = $('[tabindex]', context);
960
  if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {
961
    // removeAttr('tabindex') is broken in IE6-7, but the DOM function
962
    // removeAttribute works.
963
    var i;
964
    var length = $tabindex.length;
965
    for (i = 0; i < length; i++) {
966
      $tabindex[i].removeAttribute('tabIndex');
967
    }
968
  }
969
  else {
970
    $tabindex.removeAttr('tabindex');
971
  }
972

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

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

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

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

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

    
1015
})(jQuery);