]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/history/history.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / history / history.js
1 /*
2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 3.3.0
6 build: 3167
7 */
8 YUI.add('history-base', function(Y) {
9
10 /**
11  * Provides browser history management functionality using a simple
12  * add/replace/get paradigm. This can be used to ensure that the browser's back
13  * and forward buttons work as the user expects and to provide bookmarkable URLs
14  * that return the user to the current application state, even in an Ajax
15  * application that doesn't perform full-page refreshes.
16  *
17  * @module history
18  * @since 3.2.0
19  */
20
21 /**
22  * Provides global state management backed by an object, but with no browser
23  * history integration. For actual browser history integration and back/forward
24  * support, use the history-html5 or history-hash modules.
25  *
26  * @module history
27  * @submodule history-base
28  * @class HistoryBase
29  * @uses EventTarget
30  * @constructor
31  * @param {Object} config (optional) configuration object, which may contain
32  *   zero or more of the following properties:
33  *
34  * <dl>
35  *   <dt>initialState (Object)</dt>
36  *   <dd>
37  *     Initial state to set, as an object hash of key/value pairs. This will be
38  *     merged into the current global state.
39  *   </dd>
40  * </dl>
41  */
42
43 var Lang      = Y.Lang,
44     Obj       = Y.Object,
45     GlobalEnv = YUI.namespace('Env.History'),
46     YArray    = Y.Array,
47
48     doc       = Y.config.doc,
49     docMode   = doc.documentMode,
50     win       = Y.config.win,
51
52     DEFAULT_OPTIONS = {merge: true},
53     EVT_CHANGE      = 'change',
54     SRC_ADD         = 'add',
55     SRC_REPLACE     = 'replace';
56
57 function HistoryBase() {
58     this._init.apply(this, arguments);
59 }
60
61 Y.augment(HistoryBase, Y.EventTarget, null, null, {
62     emitFacade : true,
63     prefix     : 'history',
64     preventable: false,
65     queueable  : true
66 });
67
68 if (!GlobalEnv._state) {
69     GlobalEnv._state = {};
70 }
71
72 // -- Private Methods ----------------------------------------------------------
73
74 /**
75  * Returns <code>true</code> if <i>value</i> is a simple object and not a
76  * function or an array.
77  *
78  * @method _isSimpleObject
79  * @param {mixed} value
80  * @return {Boolean}
81  * @private
82  */
83 function _isSimpleObject(value) {
84     return Lang.type(value) === 'object';
85 }
86
87 // -- Public Static Properties -------------------------------------------------
88
89 /**
90  * Name of this component.
91  *
92  * @property NAME
93  * @type String
94  * @static
95  */
96 HistoryBase.NAME = 'historyBase';
97
98 /**
99  * Constant used to identify state changes originating from the
100  * <code>add()</code> method.
101  *
102  * @property SRC_ADD
103  * @type String
104  * @static
105  * @final
106  */
107 HistoryBase.SRC_ADD = SRC_ADD;
108
109 /**
110  * Constant used to identify state changes originating from the
111  * <code>replace()</code> method.
112  *
113  * @property SRC_REPLACE
114  * @type String
115  * @static
116  * @final
117  */
118 HistoryBase.SRC_REPLACE = SRC_REPLACE;
119
120 /**
121  * Whether or not this browser supports the HTML5 History API.
122  *
123  * @property html5
124  * @type Boolean
125  * @static
126  */
127
128 // All HTML5-capable browsers except Gecko 2+ (Firefox 4+) correctly return
129 // true for 'onpopstate' in win. In order to support Gecko 2, we fall back to a
130 // UA sniff for now. (current as of Firefox 4.0b2)
131 HistoryBase.html5 = !!(win.history && win.history.pushState &&
132         win.history.replaceState && ('onpopstate' in win || Y.UA.gecko >= 2));
133
134 /**
135  * Whether or not this browser supports the <code>window.onhashchange</code>
136  * event natively. Note that even if this is <code>true</code>, you may
137  * still want to use HistoryHash's synthetic <code>hashchange</code> event
138  * since it normalizes implementation differences and fixes spec violations
139  * across various browsers.
140  *
141  * @property nativeHashChange
142  * @type Boolean
143  * @static
144  */
145
146 // Most browsers that support hashchange expose it on the window. Opera 10.6+
147 // exposes it on the document (but you can still attach to it on the window).
148 //
149 // IE8 supports the hashchange event, but only in IE8 Standards
150 // Mode. However, IE8 in IE7 compatibility mode still defines the
151 // event but never fires it, so we can't just detect the event. We also can't
152 // just UA sniff for IE8, since other browsers support this event as well.
153 HistoryBase.nativeHashChange = ('onhashchange' in win || 'onhashchange' in doc) &&
154         (!docMode || docMode > 7);
155
156 Y.mix(HistoryBase.prototype, {
157     // -- Initialization -------------------------------------------------------
158
159     /**
160      * Initializes this HistoryBase instance. This method is called by the
161      * constructor.
162      *
163      * @method _init
164      * @param {Object} config configuration object
165      * @protected
166      */
167     _init: function (config) {
168         var initialState;
169
170         /**
171          * Configuration object provided by the user on instantiation, or an
172          * empty object if one wasn't provided.
173          *
174          * @property _config
175          * @type Object
176          * @default {}
177          * @protected
178          */
179         config = this._config = config || {};
180
181         /**
182          * Resolved initial state: a merge of the user-supplied initial state
183          * (if any) and any initial state provided by a subclass. This may
184          * differ from <code>_config.initialState</code>. If neither the config
185          * nor a subclass supplies an initial state, this property will be
186          * <code>null</code>.
187          *
188          * @property _initialState
189          * @type Object|null
190          * @default {}
191          * @protected
192          */
193         initialState = this._initialState = this._initialState ||
194                 config.initialState || null;
195
196         /**
197          * Fired when the state changes. To be notified of all state changes
198          * regardless of the History or YUI instance that generated them,
199          * subscribe to this event on <code>Y.Global</code>. If you would rather
200          * be notified only about changes generated by this specific History
201          * instance, subscribe to this event on the instance.
202          *
203          * @event history:change
204          * @param {EventFacade} e Event facade with the following additional
205          *   properties:
206          *
207          * <dl>
208          *   <dt>changed (Object)</dt>
209          *   <dd>
210          *     Object hash of state items that have been added or changed. The
211          *     key is the item key, and the value is an object containing
212          *     <code>newVal</code> and <code>prevVal</code> properties
213          *     representing the values of the item both before and after the
214          *     change. If the item was newly added, <code>prevVal</code> will be
215          *     <code>undefined</code>.
216          *   </dd>
217          *
218          *   <dt>newVal (Object)</dt>
219          *   <dd>
220          *     Object hash of key/value pairs of all state items after the
221          *     change.
222          *   </dd>
223          *
224          *   <dt>prevVal (Object)</dt>
225          *   <dd>
226          *     Object hash of key/value pairs of all state items before the
227          *     change.
228          *   </dd>
229          *
230          *   <dt>removed (Object)</dt>
231          *   <dd>
232          *     Object hash of key/value pairs of state items that have been
233          *     removed. Values are the old values prior to removal.
234          *   </dd>
235          *
236          *   <dt>src (String)</dt>
237          *   <dd>
238          *     The source of the event. This can be used to selectively ignore
239          *     events generated by certain sources.
240          *   </dd>
241          * </dl>
242          */
243         this.publish(EVT_CHANGE, {
244             broadcast: 2,
245             defaultFn: this._defChangeFn
246         });
247
248         // If initialState was provided, merge it into the current state.
249         if (initialState) {
250             this.add(initialState);
251         }
252     },
253
254     // -- Public Methods -------------------------------------------------------
255
256     /**
257      * Adds a state entry with new values for the specified keys. By default,
258      * the new state will be merged into the existing state, and new values will
259      * override existing values. Specifying a <code>null</code> or
260      * <code>undefined</code> value will cause that key to be removed from the
261      * new state entry.
262      *
263      * @method add
264      * @param {Object} state Object hash of key/value pairs.
265      * @param {Object} options (optional) Zero or more of the following options:
266      *   <dl>
267      *     <dt>merge (Boolean)</dt>
268      *     <dd>
269      *       <p>
270      *       If <code>true</code> (the default), the new state will be merged
271      *       into the existing state. New values will override existing values,
272      *       and <code>null</code> or <code>undefined</code> values will be
273      *       removed from the state.
274      *       </p>
275      *
276      *       <p>
277      *       If <code>false</code>, the existing state will be discarded as a
278      *       whole and the new state will take its place.
279      *       </p>
280      *     </dd>
281      *   </dl>
282      * @chainable
283      */
284     add: function () {
285         var args = YArray(arguments, 0, true);
286         args.unshift(SRC_ADD);
287         return this._change.apply(this, args);
288     },
289
290     /**
291      * Adds a state entry with a new value for a single key. By default, the new
292      * value will be merged into the existing state values, and will override an
293      * existing value with the same key if there is one. Specifying a
294      * <code>null</code> or <code>undefined</code> value will cause the key to
295      * be removed from the new state entry.
296      *
297      * @method addValue
298      * @param {String} key State parameter key.
299      * @param {String} value New value.
300      * @param {Object} options (optional) Zero or more options. See
301      *   <code>add()</code> for a list of supported options.
302      * @chainable
303      */
304     addValue: function (key, value, options) {
305         var state = {};
306         state[key] = value;
307         return this._change(SRC_ADD, state, options);
308     },
309
310     /**
311      * Returns the current value of the state parameter specified by <i>key</i>,
312      * or an object hash of key/value pairs for all current state parameters if
313      * no key is specified.
314      *
315      * @method get
316      * @param {String} key (optional) State parameter key.
317      * @return {Object|String} Value of the specified state parameter, or an
318      *   object hash of key/value pairs for all current state parameters.
319      */
320     get: function (key) {
321         var state    = GlobalEnv._state,
322             isObject = _isSimpleObject(state);
323
324         if (key) {
325             return isObject && Obj.owns(state, key) ? state[key] : undefined;
326         } else {
327             return isObject ? Y.mix({}, state, true) : state; // mix provides a fast shallow clone.
328         }
329     },
330
331     /**
332      * Same as <code>add()</code> except that a new browser history entry will
333      * not be created. Instead, the current history entry will be replaced with
334      * the new state.
335      *
336      * @method replace
337      * @param {Object} state Object hash of key/value pairs.
338      * @param {Object} options (optional) Zero or more options. See
339      *   <code>add()</code> for a list of supported options.
340      * @chainable
341      */
342     replace: function () {
343         var args = YArray(arguments, 0, true);
344         args.unshift(SRC_REPLACE);
345         return this._change.apply(this, args);
346     },
347
348     /**
349      * Same as <code>addValue()</code> except that a new browser history entry
350      * will not be created. Instead, the current history entry will be replaced
351      * with the new state.
352      *
353      * @method replaceValue
354      * @param {String} key State parameter key.
355      * @param {String} value New value.
356      * @param {Object} options (optional) Zero or more options. See
357      *   <code>add()</code> for a list of supported options.
358      * @chainable
359      */
360     replaceValue: function (key, value, options) {
361         var state = {};
362         state[key] = value;
363         return this._change(SRC_REPLACE, state, options);
364     },
365
366     // -- Protected Methods ----------------------------------------------------
367
368     /**
369      * Changes the state. This method provides a common implementation shared by
370      * the public methods for changing state.
371      *
372      * @method _change
373      * @param {String} src Source of the change, for inclusion in event facades
374      *   to facilitate filtering.
375      * @param {Object} state Object hash of key/value pairs.
376      * @param {Object} options (optional) Zero or more options. See
377      *   <code>add()</code> for a list of supported options.
378      * @protected
379      * @chainable
380      */
381     _change: function (src, state, options) {
382         options = options ? Y.merge(DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;
383
384         if (options.merge && _isSimpleObject(state) &&
385                 _isSimpleObject(GlobalEnv._state)) {
386             state = Y.merge(GlobalEnv._state, state);
387         }
388
389         this._resolveChanges(src, state, options);
390         return this;
391     },
392
393     /**
394      * Called by _resolveChanges() when the state has changed. This method takes
395      * care of actually firing the necessary events.
396      *
397      * @method _fireEvents
398      * @param {String} src Source of the changes, for inclusion in event facades
399      *   to facilitate filtering.
400      * @param {Object} changes Resolved changes.
401      * @param {Object} options Zero or more options. See <code>add()</code> for
402      *   a list of supported options.
403      * @protected
404      */
405     _fireEvents: function (src, changes, options) {
406         // Fire the global change event.
407         this.fire(EVT_CHANGE, {
408             _options: options,
409             changed : changes.changed,
410             newVal  : changes.newState,
411             prevVal : changes.prevState,
412             removed : changes.removed,
413             src     : src
414         });
415
416         // Fire change/remove events for individual items.
417         Obj.each(changes.changed, function (value, key) {
418             this._fireChangeEvent(src, key, value);
419         }, this);
420
421         Obj.each(changes.removed, function (value, key) {
422             this._fireRemoveEvent(src, key, value);
423         }, this);
424     },
425
426     /**
427      * Fires a dynamic "[key]Change" event.
428      *
429      * @method _fireChangeEvent
430      * @param {String} src source of the change, for inclusion in event facades
431      *   to facilitate filtering
432      * @param {String} key key of the item that was changed
433      * @param {Object} value object hash containing <i>newVal</i> and
434      *   <i>prevVal</i> properties for the changed item
435      * @protected
436      */
437     _fireChangeEvent: function (src, key, value) {
438         /**
439          * <p>
440          * Dynamic event fired when an individual history item is added or
441          * changed. The name of this event depends on the name of the key that
442          * changed. To listen to change events for a key named "foo", subscribe
443          * to the <code>fooChange</code> event; for a key named "bar", subscribe
444          * to <code>barChange</code>, etc.
445          * </p>
446          *
447          * <p>
448          * Key-specific events are only fired for instance-level changes; that
449          * is, changes that were made via the same History instance on which the
450          * event is subscribed. To be notified of changes made by other History
451          * instances, subscribe to the global <code>history:change</code> event.
452          * </p>
453          *
454          * @event [key]Change
455          * @param {EventFacade} e Event facade with the following additional
456          *   properties:
457          *
458          * <dl>
459          *   <dt>newVal (mixed)</dt>
460          *   <dd>
461          *     The new value of the item after the change.
462          *   </dd>
463          *
464          *   <dt>prevVal (mixed)</dt>
465          *   <dd>
466          *     The previous value of the item before the change, or
467          *     <code>undefined</code> if the item was just added and has no
468          *     previous value.
469          *   </dd>
470          *
471          *   <dt>src (String)</dt>
472          *   <dd>
473          *     The source of the event. This can be used to selectively ignore
474          *     events generated by certain sources.
475          *   </dd>
476          * </dl>
477          */
478         this.fire(key + 'Change', {
479             newVal : value.newVal,
480             prevVal: value.prevVal,
481             src    : src
482         });
483     },
484
485     /**
486      * Fires a dynamic "[key]Remove" event.
487      *
488      * @method _fireRemoveEvent
489      * @param {String} src source of the change, for inclusion in event facades
490      *   to facilitate filtering
491      * @param {String} key key of the item that was removed
492      * @param {mixed} value value of the item prior to its removal
493      * @protected
494      */
495     _fireRemoveEvent: function (src, key, value) {
496         /**
497          * <p>
498          * Dynamic event fired when an individual history item is removed. The
499          * name of this event depends on the name of the key that was removed.
500          * To listen to remove events for a key named "foo", subscribe to the
501          * <code>fooRemove</code> event; for a key named "bar", subscribe to
502          * <code>barRemove</code>, etc.
503          * </p>
504          *
505          * <p>
506          * Key-specific events are only fired for instance-level changes; that
507          * is, changes that were made via the same History instance on which the
508          * event is subscribed. To be notified of changes made by other History
509          * instances, subscribe to the global <code>history:change</code> event.
510          * </p>
511          *
512          * @event [key]Remove
513          * @param {EventFacade} e Event facade with the following additional
514          *   properties:
515          *
516          * <dl>
517          *   <dt>prevVal (mixed)</dt>
518          *   <dd>
519          *     The value of the item before it was removed.
520          *   </dd>
521          *
522          *   <dt>src (String)</dt>
523          *   <dd>
524          *     The source of the event. This can be used to selectively ignore
525          *     events generated by certain sources.
526          *   </dd>
527          * </dl>
528          */
529         this.fire(key + 'Remove', {
530             prevVal: value,
531             src    : src
532         });
533     },
534
535     /**
536      * Resolves the changes (if any) between <i>newState</i> and the current
537      * state and fires appropriate events if things have changed.
538      *
539      * @method _resolveChanges
540      * @param {String} src source of the changes, for inclusion in event facades
541      *   to facilitate filtering
542      * @param {Object} newState object hash of key/value pairs representing the
543      *   new state
544      * @param {Object} options Zero or more options. See <code>add()</code> for
545      *   a list of supported options.
546      * @protected
547      */
548     _resolveChanges: function (src, newState, options) {
549         var changed   = {},
550             isChanged,
551             prevState = GlobalEnv._state,
552             removed   = {};
553
554         if (!newState) {
555             newState = {};
556         }
557
558         if (!options) {
559             options = {};
560         }
561
562         if (_isSimpleObject(newState) && _isSimpleObject(prevState)) {
563             // Figure out what was added or changed.
564             Obj.each(newState, function (newVal, key) {
565                 var prevVal = prevState[key];
566
567                 if (newVal !== prevVal) {
568                     changed[key] = {
569                         newVal : newVal,
570                         prevVal: prevVal
571                     };
572
573                     isChanged = true;
574                 }
575             }, this);
576
577             // Figure out what was removed.
578             Obj.each(prevState, function (prevVal, key) {
579                 if (!Obj.owns(newState, key) || newState[key] === null) {
580                     delete newState[key];
581                     removed[key] = prevVal;
582                     isChanged = true;
583                 }
584             }, this);
585         } else {
586             isChanged = newState !== prevState;
587         }
588
589         if (isChanged) {
590             this._fireEvents(src, {
591                 changed  : changed,
592                 newState : newState,
593                 prevState: prevState,
594                 removed  : removed
595             }, options);
596         }
597     },
598
599     /**
600      * Stores the specified state. Don't call this method directly; go through
601      * _resolveChanges() to ensure that changes are resolved and all events are
602      * fired properly.
603      *
604      * @method _storeState
605      * @param {String} src source of the changes
606      * @param {Object} newState new state to store
607      * @param {Object} options Zero or more options. See <code>add()</code> for
608      *   a list of supported options.
609      * @protected
610      */
611     _storeState: function (src, newState) {
612         // Note: the src and options params aren't used here, but they are used
613         // by subclasses.
614         GlobalEnv._state = newState || {};
615     },
616
617     // -- Protected Event Handlers ---------------------------------------------
618
619     /**
620      * Default <code>history:change</code> event handler.
621      *
622      * @method _defChangeFn
623      * @param {EventFacade} e state change event facade
624      * @protected
625      */
626     _defChangeFn: function (e) {
627         this._storeState(e.src, e.newVal, e._options);
628     }
629 }, true);
630
631 Y.HistoryBase = HistoryBase;
632
633
634 }, '3.3.0' ,{requires:['event-custom-complex']});
635 YUI.add('history-hash', function(Y) {
636
637 /**
638  * Provides browser history management backed by
639  * <code>window.location.hash</code>, as well as convenience methods for working
640  * with the location hash and a synthetic <code>hashchange</code> event that
641  * normalizes differences across browsers.
642  *
643  * @module history
644  * @submodule history-hash
645  * @since 3.2.0
646  * @class HistoryHash
647  * @extends HistoryBase
648  * @constructor
649  * @param {Object} config (optional) Configuration object. See the HistoryBase
650  *   documentation for details.
651  */
652
653 var HistoryBase = Y.HistoryBase,
654     Lang        = Y.Lang,
655     YArray      = Y.Array,
656     YObject     = Y.Object,
657     GlobalEnv   = YUI.namespace('Env.HistoryHash'),
658
659     SRC_HASH    = 'hash',
660
661     hashNotifiers,
662     oldHash,
663     oldUrl,
664     win             = Y.config.win,
665     location        = win.location,
666     useHistoryHTML5 = Y.config.useHistoryHTML5;
667
668 function HistoryHash() {
669     HistoryHash.superclass.constructor.apply(this, arguments);
670 }
671
672 Y.extend(HistoryHash, HistoryBase, {
673     // -- Initialization -------------------------------------------------------
674     _init: function (config) {
675         var bookmarkedState = HistoryHash.parseHash();
676
677         // If an initialState was provided, merge the bookmarked state into it
678         // (the bookmarked state wins).
679         config = config || {};
680
681         this._initialState = config.initialState ?
682                 Y.merge(config.initialState, bookmarkedState) : bookmarkedState;
683
684         // Subscribe to the synthetic hashchange event (defined below) to handle
685         // changes.
686         Y.after('hashchange', Y.bind(this._afterHashChange, this), win);
687
688         HistoryHash.superclass._init.apply(this, arguments);
689     },
690
691     // -- Protected Methods ----------------------------------------------------
692     _change: function (src, state, options) {
693         // Stringify all values to ensure that comparisons don't fail after
694         // they're coerced to strings in the location hash.
695         YObject.each(state, function (value, key) {
696             if (Lang.isValue(value)) {
697                 state[key] = value.toString();
698             }
699         });
700
701         return HistoryHash.superclass._change.call(this, src, state, options);
702     },
703
704     _storeState: function (src, newState) {
705         var decode  = HistoryHash.decode,
706             newHash = HistoryHash.createHash(newState);
707
708         HistoryHash.superclass._storeState.apply(this, arguments);
709
710         // Update the location hash with the changes, but only if the new hash
711         // actually differs from the current hash (this avoids creating multiple
712         // history entries for a single state).
713         //
714         // We always compare decoded hashes, since it's possible that the hash
715         // could be set incorrectly to a non-encoded value outside of
716         // HistoryHash.
717         if (src !== SRC_HASH && decode(HistoryHash.getHash()) !== decode(newHash)) {
718             HistoryHash[src === HistoryBase.SRC_REPLACE ? 'replaceHash' : 'setHash'](newHash);
719         }
720     },
721
722     // -- Protected Event Handlers ---------------------------------------------
723
724     /**
725      * Handler for hashchange events.
726      *
727      * @method _afterHashChange
728      * @param {Event} e
729      * @protected
730      */
731     _afterHashChange: function (e) {
732         this._resolveChanges(SRC_HASH, HistoryHash.parseHash(e.newHash), {});
733     }
734 }, {
735     // -- Public Static Properties ---------------------------------------------
736     NAME: 'historyHash',
737
738     /**
739      * Constant used to identify state changes originating from
740      * <code>hashchange</code> events.
741      *
742      * @property SRC_HASH
743      * @type String
744      * @static
745      * @final
746      */
747     SRC_HASH: SRC_HASH,
748
749     /**
750      * <p>
751      * Prefix to prepend when setting the hash fragment. For example, if the
752      * prefix is <code>!</code> and the hash fragment is set to
753      * <code>#foo=bar&baz=quux</code>, the final hash fragment in the URL will
754      * become <code>#!foo=bar&baz=quux</code>. This can be used to help make an
755      * Ajax application crawlable in accordance with Google's guidelines at
756      * <a href="http://code.google.com/web/ajaxcrawling/">http://code.google.com/web/ajaxcrawling/</a>.
757      * </p>
758      *
759      * <p>
760      * Note that this prefix applies to all HistoryHash instances. It's not
761      * possible for individual instances to use their own prefixes since they
762      * all operate on the same URL.
763      * </p>
764      *
765      * @property hashPrefix
766      * @type String
767      * @default ''
768      * @static
769      */
770     hashPrefix: '',
771
772     // -- Protected Static Properties ------------------------------------------
773
774     /**
775      * Regular expression used to parse location hash/query strings.
776      *
777      * @property _REGEX_HASH
778      * @type RegExp
779      * @protected
780      * @static
781      * @final
782      */
783     _REGEX_HASH: /([^\?#&]+)=([^&]+)/g,
784
785     // -- Public Static Methods ------------------------------------------------
786
787     /**
788      * Creates a location hash string from the specified object of key/value
789      * pairs.
790      *
791      * @method createHash
792      * @param {Object} params object of key/value parameter pairs
793      * @return {String} location hash string
794      * @static
795      */
796     createHash: function (params) {
797         var encode = HistoryHash.encode,
798             hash   = [];
799
800         YObject.each(params, function (value, key) {
801             if (Lang.isValue(value)) {
802                 hash.push(encode(key) + '=' + encode(value));
803             }
804         });
805
806         return hash.join('&');
807     },
808
809     /**
810      * Wrapper around <code>decodeURIComponent()</code> that also converts +
811      * chars into spaces.
812      *
813      * @method decode
814      * @param {String} string string to decode
815      * @return {String} decoded string
816      * @static
817      */
818     decode: function (string) {
819         return decodeURIComponent(string.replace(/\+/g, ' '));
820     },
821
822     /**
823      * Wrapper around <code>encodeURIComponent()</code> that converts spaces to
824      * + chars.
825      *
826      * @method encode
827      * @param {String} string string to encode
828      * @return {String} encoded string
829      * @static
830      */
831     encode: function (string) {
832         return encodeURIComponent(string).replace(/%20/g, '+');
833     },
834
835     /**
836      * Gets the raw (not decoded) current location hash, minus the preceding '#'
837      * character and the hashPrefix (if one is set).
838      *
839      * @method getHash
840      * @return {String} current location hash
841      * @static
842      */
843     getHash: (Y.UA.gecko ? function () {
844         // Gecko's window.location.hash returns a decoded string and we want all
845         // encoding untouched, so we need to get the hash value from
846         // window.location.href instead. We have to use UA sniffing rather than
847         // feature detection, since the only way to detect this would be to
848         // actually change the hash.
849         var matches = /#(.*)$/.exec(location.href),
850             hash    = matches && matches[1] || '',
851             prefix  = HistoryHash.hashPrefix;
852
853         return prefix && hash.indexOf(prefix) === 0 ?
854                     hash.replace(prefix, '') : hash;
855     } : function () {
856         var hash   = location.hash.substr(1),
857             prefix = HistoryHash.hashPrefix;
858
859         // Slight code duplication here, but execution speed is of the essence
860         // since getHash() is called every 50ms to poll for changes in browsers
861         // that don't support native onhashchange. An additional function call
862         // would add unnecessary overhead.
863         return prefix && hash.indexOf(prefix) === 0 ?
864                     hash.replace(prefix, '') : hash;
865     }),
866
867     /**
868      * Gets the current bookmarkable URL.
869      *
870      * @method getUrl
871      * @return {String} current bookmarkable URL
872      * @static
873      */
874     getUrl: function () {
875         return location.href;
876     },
877
878     /**
879      * Parses a location hash string into an object of key/value parameter
880      * pairs. If <i>hash</i> is not specified, the current location hash will
881      * be used.
882      *
883      * @method parseHash
884      * @param {String} hash (optional) location hash string
885      * @return {Object} object of parsed key/value parameter pairs
886      * @static
887      */
888     parseHash: function (hash) {
889         var decode = HistoryHash.decode,
890             i,
891             len,
892             matches,
893             param,
894             params = {},
895             prefix = HistoryHash.hashPrefix,
896             prefixIndex;
897
898         hash = Lang.isValue(hash) ? hash : HistoryHash.getHash();
899
900         if (prefix) {
901             prefixIndex = hash.indexOf(prefix);
902
903             if (prefixIndex === 0 || (prefixIndex === 1 && hash.charAt(0) === '#')) {
904                 hash = hash.replace(prefix, '');
905             }
906         }
907
908         matches = hash.match(HistoryHash._REGEX_HASH) || [];
909
910         for (i = 0, len = matches.length; i < len; ++i) {
911             param = matches[i].split('=');
912             params[decode(param[0])] = decode(param[1]);
913         }
914
915         return params;
916     },
917
918     /**
919      * Replaces the browser's current location hash with the specified hash
920      * and removes all forward navigation states, without creating a new browser
921      * history entry. Automatically prepends the <code>hashPrefix</code> if one
922      * is set.
923      *
924      * @method replaceHash
925      * @param {String} hash new location hash
926      * @static
927      */
928     replaceHash: function (hash) {
929         if (hash.charAt(0) === '#') {
930             hash = hash.substr(1);
931         }
932
933         location.replace('#' + (HistoryHash.hashPrefix || '') + hash);
934     },
935
936     /**
937      * Sets the browser's location hash to the specified string. Automatically
938      * prepends the <code>hashPrefix</code> if one is set.
939      *
940      * @method setHash
941      * @param {String} hash new location hash
942      * @static
943      */
944     setHash: function (hash) {
945         if (hash.charAt(0) === '#') {
946             hash = hash.substr(1);
947         }
948
949         location.hash = (HistoryHash.hashPrefix || '') + hash;
950     }
951 });
952
953 // -- Synthetic hashchange Event -----------------------------------------------
954
955 // TODO: YUIDoc currently doesn't provide a good way to document synthetic DOM
956 // events. For now, we're just documenting the hashchange event on the YUI
957 // object, which is about the best we can do until enhancements are made to
958 // YUIDoc.
959
960 /**
961  * <p>
962  * Synthetic <code>window.onhashchange</code> event that normalizes differences
963  * across browsers and provides support for browsers that don't natively support
964  * <code>onhashchange</code>.
965  * </p>
966  *
967  * <p>
968  * This event is provided by the <code>history-hash</code> module.
969  * </p>
970  *
971  * <p>
972  * <strong>Usage example:</strong>
973  * </p>
974  *
975  * <code><pre>
976  * YUI().use('history-hash', function (Y) {
977  * &nbsp;&nbsp;Y.on('hashchange', function (e) {
978  * &nbsp;&nbsp;&nbsp;&nbsp;// Handle hashchange events on the current window.
979  * &nbsp;&nbsp;}, Y.config.win);
980  * });
981  * </pre></code>
982  *
983  * @event hashchange
984  * @param {EventFacade} e Event facade with the following additional
985  *   properties:
986  *
987  * <dl>
988  *   <dt>oldHash</dt>
989  *   <dd>
990  *     Previous hash fragment value before the change.
991  *   </dd>
992  *
993  *   <dt>oldUrl</dt>
994  *   <dd>
995  *     Previous URL (including the hash fragment) before the change.
996  *   </dd>
997  *
998  *   <dt>newHash</dt>
999  *   <dd>
1000  *     New hash fragment value after the change.
1001  *   </dd>
1002  *
1003  *   <dt>newUrl</dt>
1004  *   <dd>
1005  *     New URL (including the hash fragment) after the change.
1006  *   </dd>
1007  * </dl>
1008  * @for YUI
1009  * @since 3.2.0
1010  */
1011
1012 hashNotifiers = GlobalEnv._notifiers;
1013
1014 if (!hashNotifiers) {
1015     hashNotifiers = GlobalEnv._notifiers = [];
1016 }
1017
1018 Y.Event.define('hashchange', {
1019     on: function (node, subscriber, notifier) {
1020         // Ignore this subscription if the node is anything other than the
1021         // window or document body, since those are the only elements that
1022         // should support the hashchange event. Note that the body could also be
1023         // a frameset, but that's okay since framesets support hashchange too.
1024         if (node.compareTo(win) || node.compareTo(Y.config.doc.body)) {
1025             hashNotifiers.push(notifier);
1026         }
1027     },
1028
1029     detach: function (node, subscriber, notifier) {
1030         var index = YArray.indexOf(hashNotifiers, notifier);
1031
1032         if (index !== -1) {
1033             hashNotifiers.splice(index, 1);
1034         }
1035     }
1036 });
1037
1038 oldHash = HistoryHash.getHash();
1039 oldUrl  = HistoryHash.getUrl();
1040
1041 if (HistoryBase.nativeHashChange) {
1042     // Wrap the browser's native hashchange event.
1043     Y.Event.attach('hashchange', function (e) {
1044         var newHash = HistoryHash.getHash(),
1045             newUrl  = HistoryHash.getUrl();
1046
1047         // Iterate over a copy of the hashNotifiers array since a subscriber
1048         // could detach during iteration and cause the array to be re-indexed.
1049         YArray.each(hashNotifiers.concat(), function (notifier) {
1050             notifier.fire({
1051                 _event : e,
1052                 oldHash: oldHash,
1053                 oldUrl : oldUrl,
1054                 newHash: newHash,
1055                 newUrl : newUrl
1056             });
1057         });
1058
1059         oldHash = newHash;
1060         oldUrl  = newUrl;
1061     }, win);
1062 } else {
1063     // Begin polling for location hash changes if there's not already a global
1064     // poll running.
1065     if (!GlobalEnv._hashPoll) {
1066         if (Y.UA.webkit && !Y.UA.chrome &&
1067                 navigator.vendor.indexOf('Apple') !== -1) {
1068             // Attach a noop unload handler to disable Safari's back/forward
1069             // cache. This works around a nasty Safari bug when the back button
1070             // is used to return from a page on another domain, but results in
1071             // slightly worse performance. This bug is not present in Chrome.
1072             //
1073             // Unfortunately a UA sniff is unavoidable here, but the
1074             // consequences of a false positive are minor.
1075             //
1076             // Current as of Safari 5.0 (6533.16).
1077             // See: https://bugs.webkit.org/show_bug.cgi?id=34679
1078             Y.on('unload', function () {}, win);
1079         }
1080
1081         GlobalEnv._hashPoll = Y.later(50, null, function () {
1082             var newHash = HistoryHash.getHash(),
1083                 newUrl;
1084
1085             if (oldHash !== newHash) {
1086                 newUrl = HistoryHash.getUrl();
1087
1088                 YArray.each(hashNotifiers.concat(), function (notifier) {
1089                     notifier.fire({
1090                         oldHash: oldHash,
1091                         oldUrl : oldUrl,
1092                         newHash: newHash,
1093                         newUrl : newUrl
1094                     });
1095                 });
1096
1097                 oldHash = newHash;
1098                 oldUrl  = newUrl;
1099             }
1100         }, null, true);
1101     }
1102 }
1103
1104 Y.HistoryHash = HistoryHash;
1105
1106 // HistoryHash will never win over HistoryHTML5 unless useHistoryHTML5 is false.
1107 if (useHistoryHTML5 === false || (!Y.History && useHistoryHTML5 !== true &&
1108         (!HistoryBase.html5 || !Y.HistoryHTML5))) {
1109     Y.History = HistoryHash;
1110 }
1111
1112
1113 }, '3.3.0' ,{requires:['event-synthetic', 'history-base', 'yui-later']});
1114 YUI.add('history-hash-ie', function(Y) {
1115
1116 /**
1117  * Improves IE6/7 support in history-hash by using a hidden iframe to create
1118  * entries in IE's browser history. This module is only needed if IE6/7 support
1119  * is necessary; it's not needed for any other browser.
1120  *
1121  * @module history
1122  * @submodule history-hash-ie
1123  * @since 3.2.0
1124  */
1125
1126 // Combination of a UA sniff to ensure this is IE (or a browser that wants us to
1127 // treat it like IE) and feature detection for native hashchange support (false
1128 // for IE < 8 or IE8/9 in IE7 mode).
1129 if (Y.UA.ie && !Y.HistoryBase.nativeHashChange) {
1130     var Do          = Y.Do,
1131         GlobalEnv   = YUI.namespace('Env.HistoryHash'),
1132         HistoryHash = Y.HistoryHash,
1133
1134         iframe      = GlobalEnv._iframe,
1135         win         = Y.config.win,
1136         location    = win.location,
1137         lastUrlHash = '';
1138
1139     /**
1140      * Gets the raw (not decoded) current location hash from the IE iframe,
1141      * minus the preceding '#' character and the hashPrefix (if one is set).
1142      *
1143      * @method getIframeHash
1144      * @return {String} current iframe hash
1145      * @static
1146      */
1147     HistoryHash.getIframeHash = function () {
1148         if (!iframe || !iframe.contentWindow) {
1149             return '';
1150         }
1151
1152         var prefix = HistoryHash.hashPrefix,
1153             hash   = iframe.contentWindow.location.hash.substr(1);
1154
1155         return prefix && hash.indexOf(prefix) === 0 ?
1156                     hash.replace(prefix, '') : hash;
1157     };
1158
1159     /**
1160      * Updates the history iframe with the specified hash.
1161      *
1162      * @method _updateIframe
1163      * @param {String} hash location hash
1164      * @param {Boolean} replace (optional) if <code>true</code>, the current
1165      *   history state will be replaced without adding a new history entry
1166      * @protected
1167      * @static
1168      * @for HistoryHash
1169      */
1170     HistoryHash._updateIframe = function (hash, replace) {
1171         var iframeDoc      = iframe && iframe.contentWindow && iframe.contentWindow.document,
1172             iframeLocation = iframeDoc && iframeDoc.location;
1173
1174         if (!iframeDoc || !iframeLocation) {
1175             return;
1176         }
1177
1178
1179         iframeDoc.open().close();
1180
1181         if (replace) {
1182             iframeLocation.replace(hash.charAt(0) === '#' ? hash : '#' + hash);
1183         } else {
1184             iframeLocation.hash = hash;
1185         }
1186     };
1187
1188     Do.after(HistoryHash._updateIframe, HistoryHash, 'replaceHash', HistoryHash, true);
1189
1190     if (!iframe) {
1191         Y.on('domready', function () {
1192             // Create a hidden iframe to store history state, following the
1193             // iframe-hiding recommendations from
1194             // http://www.paciellogroup.com/blog/?p=604.
1195             //
1196             // This iframe will allow history navigation within the current page
1197             // context. After navigating to another page, all but the most
1198             // recent history state will be lost.
1199             //
1200             // Earlier versions of the YUI History Utility attempted to work
1201             // around this limitation by having the iframe load a static
1202             // resource. This workaround was extremely fragile and tended to
1203             // break frequently (and silently) since it was entirely dependent
1204             // on IE's inconsistent handling of iframe history.
1205             //
1206             // Since this workaround didn't work much of the time anyway and
1207             // added significant complexity, it has been removed, and IE6 and 7
1208             // now get slightly degraded history support.
1209
1210             iframe = GlobalEnv._iframe = Y.Node.getDOMNode(Y.Node.create(
1211                 '<iframe src="javascript:0" style="display:none" height="0" width="0" tabindex="-1" title="empty"/>'
1212             ));
1213
1214             // Append the iframe to the documentElement rather than the body.
1215             // Keeping it outside the body prevents scrolling on the initial
1216             // page load (hat tip to Ben Alman and jQuery BBQ for this
1217             // technique).
1218             Y.config.doc.documentElement.appendChild(iframe);
1219
1220             // Update the iframe with the initial location hash, if any. This
1221             // will create an initial history entry that the user can return to
1222             // after the state has changed.
1223             HistoryHash._updateIframe(HistoryHash.getHash() || '#');
1224
1225             // Listen for hashchange events and keep the iframe's hash in sync
1226             // with the parent frame's hash.
1227             Y.on('hashchange', function (e) {
1228                 lastUrlHash = e.newHash;
1229
1230                 if (HistoryHash.getIframeHash() !== lastUrlHash) {
1231                     HistoryHash._updateIframe(lastUrlHash);
1232                 }
1233             }, win);
1234
1235             // Watch the iframe hash in order to detect back/forward navigation.
1236             Y.later(50, null, function () {
1237                 var iframeHash = HistoryHash.getIframeHash();
1238
1239                 if (iframeHash !== lastUrlHash) {
1240                     HistoryHash.setHash(iframeHash);
1241                 }
1242             }, null, true);
1243         });
1244     }
1245 }
1246
1247
1248 }, '3.3.0' ,{requires:['history-hash', 'node-base']});
1249 YUI.add('history-html5', function(Y) {
1250
1251 /**
1252  * Provides browser history management using the HTML5 history API.
1253  *
1254  * @module history
1255  * @submodule history-html5
1256  * @since 3.2.0
1257  */
1258
1259 /**
1260  * <p>
1261  * Provides browser history management using the HTML5 history API.
1262  * </p>
1263  *
1264  * <p>
1265  * When calling the <code>add()</code>, <code>addValue()</code>,
1266  * <code>replace()</code>, or <code>replaceValue()</code> methods on
1267  * <code>HistoryHTML5</code>, the following additional options are supported:
1268  * </p>
1269  *
1270  * <dl>
1271  *   <dt><strong>title (String)</strong></dt>
1272  *   <dd>
1273  *     Title to use for the new history entry. Browsers will typically display
1274  *     this title to the user in the detailed history window or in a dropdown
1275  *     menu attached to the back/forward buttons. If not specified, the title
1276  *     of the current document will be used.
1277  *   </dd>
1278  *
1279  *   <dt><strong>url (String)</strong></dt>
1280  *   <dd>
1281  *     URL to display to the user for the new history entry. This URL will be
1282  *     visible in the browser's address bar and will be the bookmarked URL if
1283  *     the user bookmarks the page. It may be a relative path ("foo/bar"), an
1284  *     absolute path ("/foo/bar"), or a full URL ("http://example.com/foo/bar").
1285  *     If you specify a full URL, the origin <i>must</i> be the same as the 
1286  *     origin of the current page, or an error will occur. If no URL is
1287  *     specified, the current URL will not be changed.
1288  *   </dd>
1289  * </dl>
1290  *
1291  * @class HistoryHTML5
1292  * @extends HistoryBase
1293  * @constructor
1294  * @param {Object} config (optional) Configuration object. The following
1295  *   <code>HistoryHTML5</code>-specific properties are supported in addition to
1296  *   those supported by <code>HistoryBase</code>:
1297  *
1298  * <dl>
1299  *   <dt><strong>enableSessionFallback (Boolean)</strong></dt>
1300  *   <dd>
1301  *     <p>
1302  *     Set this to <code>true</code> to store the most recent history state in
1303  *     sessionStorage in order to seamlessly restore the previous state (if any)
1304  *     when <code>HistoryHTML5</code> is instantiated after a
1305  *     <code>window.onpopstate</code> event has already fired.
1306  *     </p>
1307  *
1308  *     <p>
1309  *     By default, this setting is <code>false</code>.
1310  *     </p>
1311  *   </dd>
1312  * </dl>
1313  */
1314
1315 var HistoryBase     = Y.HistoryBase,
1316     doc             = Y.config.doc,
1317     win             = Y.config.win,
1318     sessionStorage,
1319     useHistoryHTML5 = Y.config.useHistoryHTML5,
1320
1321     JSON = Y.JSON || win.JSON, // prefer YUI JSON, but fall back to native
1322
1323     ENABLE_FALLBACK = 'enableSessionFallback',
1324     SESSION_KEY     = 'YUI_HistoryHTML5_state',
1325     SRC_POPSTATE    = 'popstate',
1326     SRC_REPLACE     = HistoryBase.SRC_REPLACE;
1327
1328 function HistoryHTML5() {
1329     HistoryHTML5.superclass.constructor.apply(this, arguments);
1330 }
1331
1332 Y.extend(HistoryHTML5, HistoryBase, {
1333     // -- Initialization -------------------------------------------------------
1334     _init: function (config) {
1335         Y.on('popstate', this._onPopState, win, this);
1336
1337         HistoryHTML5.superclass._init.apply(this, arguments);
1338
1339         // If window.onload has already fired and the sessionStorage fallback is
1340         // enabled, try to restore the last state from sessionStorage. This
1341         // works around a shortcoming of the HTML5 history API: it's impossible
1342         // to get the current state if the popstate event fires before you've
1343         // subscribed to it. Since popstate fires immediately after onload,
1344         // the last state may be lost if you return to a page from another page.
1345         if (config && config[ENABLE_FALLBACK] && YUI.Env.windowLoaded) {
1346             // Gecko will throw an error if you attempt to reference
1347             // sessionStorage on a page served from a file:// URL, so we have to
1348             // be careful here.
1349             //
1350             // See http://yuilibrary.com/projects/yui3/ticket/2529165
1351             try {
1352                 sessionStorage = win.sessionStorage;
1353             } catch (ex) {}
1354
1355             this._loadSessionState();
1356         }
1357     },
1358
1359     // -- Protected Methods ----------------------------------------------------
1360
1361     /**
1362      * Returns a string unique to the current URL pathname that's suitable for
1363      * use as a session storage key.
1364      *
1365      * @method _getSessionKey
1366      * @return {String}
1367      * @protected
1368      */
1369     _getSessionKey: function () {
1370         return SESSION_KEY + '_' + win.location.pathname;
1371     },
1372
1373     /**
1374      * Attempts to load a state entry stored in session storage.
1375      *
1376      * @method _loadSessionState
1377      * @protected
1378      */
1379     _loadSessionState: function () {
1380         var lastState = JSON && sessionStorage &&
1381                 sessionStorage[this._getSessionKey()];
1382
1383         if (lastState) {
1384             try {
1385                 this._resolveChanges(SRC_POPSTATE, JSON.parse(lastState) || null);
1386             } catch (ex) {}
1387         }
1388     },
1389
1390     /**
1391      * Stores the specified state entry in session storage if the
1392      * <code>enableSessionFallback</code> config property is <code>true</code>
1393      * and either <code>Y.JSON</code> or native JSON support is available and
1394      * session storage is supported.
1395      *
1396      * @method _storeSessionState
1397      * @param {mixed} state State to store. May be any type serializable to
1398      *   JSON.
1399      * @protected
1400      */
1401     _storeSessionState: function (state) {
1402         if (this._config[ENABLE_FALLBACK] && JSON && sessionStorage) {
1403             sessionStorage[this._getSessionKey()] = JSON.stringify(state || null);
1404         }
1405     },
1406
1407     /**
1408      * Overrides HistoryBase's <code>_storeState()</code> and pushes or replaces
1409      * a history entry using the HTML5 history API when necessary.
1410      *
1411      * @method _storeState
1412      * @param {String} src Source of the changes.
1413      * @param {Object} newState New state to store.
1414      * @param {Object} options Zero or more options.
1415      * @protected
1416      */
1417     _storeState: function (src, newState, options) {
1418         if (src !== SRC_POPSTATE) {
1419             win.history[src === SRC_REPLACE ? 'replaceState' : 'pushState'](
1420                 newState, options.title || doc.title || '', options.url || null
1421             );
1422         }
1423
1424         this._storeSessionState(newState);
1425         HistoryHTML5.superclass._storeState.apply(this, arguments);
1426     },
1427
1428     // -- Protected Event Handlers ---------------------------------------------
1429
1430     /**
1431      * Handler for popstate events.
1432      *
1433      * @method _onPopState
1434      * @param {Event} e
1435      * @protected
1436      */
1437     _onPopState: function (e) {
1438         var state = e._event.state;
1439
1440         this._storeSessionState(state);
1441         this._resolveChanges(SRC_POPSTATE, state || null);
1442     }
1443 }, {
1444     // -- Public Static Properties ---------------------------------------------
1445     NAME: 'historyhtml5',
1446
1447     /**
1448      * Constant used to identify state changes originating from
1449      * <code>popstate</code> events.
1450      *
1451      * @property SRC_POPSTATE
1452      * @type String
1453      * @static
1454      * @final
1455      */
1456     SRC_POPSTATE: SRC_POPSTATE
1457 });
1458
1459 if (!Y.Node.DOM_EVENTS.popstate) {
1460     Y.Node.DOM_EVENTS.popstate = 1;
1461 }
1462
1463 Y.HistoryHTML5 = HistoryHTML5;
1464
1465 /**
1466  * <p>
1467  * If <code>true</code>, the <code>Y.History</code> alias will always point to
1468  * <code>Y.HistoryHTML5</code> when the history-html5 module is loaded, even if
1469  * the current browser doesn't support HTML5 history.
1470  * </p>
1471  *
1472  * <p>
1473  * If <code>false</code>, the <code>Y.History</code> alias will always point to
1474  * <code>Y.HistoryHash</code> when the history-hash module is loaded, even if
1475  * the current browser supports HTML5 history.
1476  * </p>
1477  *
1478  * <p>
1479  * If neither <code>true</code> nor <code>false</code>, the
1480  * <code>Y.History</code> alias will point to the best available history adapter
1481  * that the browser supports. This is the default behavior.
1482  * </p>
1483  *
1484  * @property useHistoryHTML5
1485  * @type boolean
1486  * @for config
1487  * @since 3.2.0
1488  */
1489
1490 // HistoryHTML5 will always win over HistoryHash unless useHistoryHTML5 is false
1491 // or HTML5 history is not supported.
1492 if (useHistoryHTML5 === true || (useHistoryHTML5 !== false &&
1493         HistoryBase.html5)) {
1494     Y.History = HistoryHTML5;
1495 }
1496
1497
1498 }, '3.3.0' ,{optional:['json'], requires:['event-base', 'history-base', 'node-base']});
1499
1500
1501 YUI.add('history', function(Y){}, '3.3.0' ,{use:['history-base', 'history-hash', 'history-hash-ie', 'history-html5']});
1502