Started coding reader
[ReadingsJQM.git] / js / jquery.mobile-1.1.1.js
1 /*
2 * jQuery Mobile Framework 1.1.1 1981b3f5ec22675ae47df8f0bdf9622e7780e90e
3 * http://jquerymobile.com
4 *
5 * Copyright 2012 jQuery Foundation and other contributors
6 * Dual licensed under the MIT or GPL Version 2 licenses.
7 * http://jquery.org/license
8 *
9 */
10 (function ( root, doc, factory ) {
11         if ( typeof define === "function" && define.amd ) {
12                 // AMD. Register as an anonymous module.
13                 define( [ "jquery" ], function ( $ ) {
14                         factory( $, root, doc );
15                         return $.mobile;
16                 });
17         } else {
18                 // Browser globals
19                 factory( root.jQuery, root, doc );
20         }
21 }( this, document, function ( jQuery, window, document, undefined ) {
22
23
24 // This plugin is an experiment for abstracting away the touch and mouse
25 // events so that developers don't have to worry about which method of input
26 // the device their document is loaded on supports.
27 //
28 // The idea here is to allow the developer to register listeners for the
29 // basic mouse events, such as mousedown, mousemove, mouseup, and click,
30 // and the plugin will take care of registering the correct listeners
31 // behind the scenes to invoke the listener at the fastest possible time
32 // for that device, while still retaining the order of event firing in
33 // the traditional mouse environment, should multiple handlers be registered
34 // on the same element for different events.
35 //
36 // The current version exposes the following virtual events to jQuery bind methods:
37 // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
38
39 (function( $, window, document, undefined ) {
40
41 var dataPropertyName = "virtualMouseBindings",
42         touchTargetPropertyName = "virtualTouchID",
43         virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
44         touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
45         mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
46         mouseEventProps = $.event.props.concat( mouseHookProps ),
47         activeDocHandlers = {},
48         resetTimerID = 0,
49         startX = 0,
50         startY = 0,
51         didScroll = false,
52         clickBlockList = [],
53         blockMouseTriggers = false,
54         blockTouchTriggers = false,
55         eventCaptureSupported = "addEventListener" in document,
56         $document = $( document ),
57         nextTouchID = 1,
58         lastTouchID = 0;
59
60 $.vmouse = {
61         moveDistanceThreshold: 10,
62         clickDistanceThreshold: 10,
63         resetTimerDuration: 1500
64 };
65
66 function getNativeEvent( event ) {
67
68         while ( event && typeof event.originalEvent !== "undefined" ) {
69                 event = event.originalEvent;
70         }
71         return event;
72 }
73
74 function createVirtualEvent( event, eventType ) {
75
76         var t = event.type,
77                 oe, props, ne, prop, ct, touch, i, j;
78
79         event = $.Event(event);
80         event.type = eventType;
81
82         oe = event.originalEvent;
83         props = $.event.props;
84
85         // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
86         // https://github.com/jquery/jquery-mobile/issues/3280
87         if ( t.search( /^(mouse|click)/ ) > -1 ) {
88                 props = mouseEventProps;
89         }
90
91         // copy original event properties over to the new event
92         // this would happen if we could call $.event.fix instead of $.Event
93         // but we don't have a way to force an event to be fixed multiple times
94         if ( oe ) {
95                 for ( i = props.length, prop; i; ) {
96                         prop = props[ --i ];
97                         event[ prop ] = oe[ prop ];
98                 }
99         }
100
101         // make sure that if the mouse and click virtual events are generated
102         // without a .which one is defined
103         if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ){
104                 event.which = 1;
105         }
106
107         if ( t.search(/^touch/) !== -1 ) {
108                 ne = getNativeEvent( oe );
109                 t = ne.touches;
110                 ct = ne.changedTouches;
111                 touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined );
112
113                 if ( touch ) {
114                         for ( j = 0, len = touchEventProps.length; j < len; j++){
115                                 prop = touchEventProps[ j ];
116                                 event[ prop ] = touch[ prop ];
117                         }
118                 }
119         }
120
121         return event;
122 }
123
124 function getVirtualBindingFlags( element ) {
125
126         var flags = {},
127                 b, k;
128
129         while ( element ) {
130
131                 b = $.data( element, dataPropertyName );
132
133                 for (  k in b ) {
134                         if ( b[ k ] ) {
135                                 flags[ k ] = flags.hasVirtualBinding = true;
136                         }
137                 }
138                 element = element.parentNode;
139         }
140         return flags;
141 }
142
143 function getClosestElementWithVirtualBinding( element, eventType ) {
144         var b;
145         while ( element ) {
146
147                 b = $.data( element, dataPropertyName );
148
149                 if ( b && ( !eventType || b[ eventType ] ) ) {
150                         return element;
151                 }
152                 element = element.parentNode;
153         }
154         return null;
155 }
156
157 function enableTouchBindings() {
158         blockTouchTriggers = false;
159 }
160
161 function disableTouchBindings() {
162         blockTouchTriggers = true;
163 }
164
165 function enableMouseBindings() {
166         lastTouchID = 0;
167         clickBlockList.length = 0;
168         blockMouseTriggers = false;
169
170         // When mouse bindings are enabled, our
171         // touch bindings are disabled.
172         disableTouchBindings();
173 }
174
175 function disableMouseBindings() {
176         // When mouse bindings are disabled, our
177         // touch bindings are enabled.
178         enableTouchBindings();
179 }
180
181 function startResetTimer() {
182         clearResetTimer();
183         resetTimerID = setTimeout(function(){
184                 resetTimerID = 0;
185                 enableMouseBindings();
186         }, $.vmouse.resetTimerDuration );
187 }
188
189 function clearResetTimer() {
190         if ( resetTimerID ){
191                 clearTimeout( resetTimerID );
192                 resetTimerID = 0;
193         }
194 }
195
196 function triggerVirtualEvent( eventType, event, flags ) {
197         var ve;
198
199         if ( ( flags && flags[ eventType ] ) ||
200                                 ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
201
202                 ve = createVirtualEvent( event, eventType );
203
204                 $( event.target).trigger( ve );
205         }
206
207         return ve;
208 }
209
210 function mouseEventCallback( event ) {
211         var touchID = $.data(event.target, touchTargetPropertyName);
212
213         if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){
214                 var ve = triggerVirtualEvent( "v" + event.type, event );
215                 if ( ve ) {
216                         if ( ve.isDefaultPrevented() ) {
217                                 event.preventDefault();
218                         }
219                         if ( ve.isPropagationStopped() ) {
220                                 event.stopPropagation();
221                         }
222                         if ( ve.isImmediatePropagationStopped() ) {
223                                 event.stopImmediatePropagation();
224                         }
225                 }
226         }
227 }
228
229 function handleTouchStart( event ) {
230
231         var touches = getNativeEvent( event ).touches,
232                 target, flags;
233
234         if ( touches && touches.length === 1 ) {
235
236                 target = event.target;
237                 flags = getVirtualBindingFlags( target );
238
239                 if ( flags.hasVirtualBinding ) {
240
241                         lastTouchID = nextTouchID++;
242                         $.data( target, touchTargetPropertyName, lastTouchID );
243
244                         clearResetTimer();
245
246                         disableMouseBindings();
247                         didScroll = false;
248
249                         var t = getNativeEvent( event ).touches[ 0 ];
250                         startX = t.pageX;
251                         startY = t.pageY;
252
253                         triggerVirtualEvent( "vmouseover", event, flags );
254                         triggerVirtualEvent( "vmousedown", event, flags );
255                 }
256         }
257 }
258
259 function handleScroll( event ) {
260         if ( blockTouchTriggers ) {
261                 return;
262         }
263
264         if ( !didScroll ) {
265                 triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
266         }
267
268         didScroll = true;
269         startResetTimer();
270 }
271
272 function handleTouchMove( event ) {
273         if ( blockTouchTriggers ) {
274                 return;
275         }
276
277         var t = getNativeEvent( event ).touches[ 0 ],
278                 didCancel = didScroll,
279                 moveThreshold = $.vmouse.moveDistanceThreshold;
280                 didScroll = didScroll ||
281                         ( Math.abs(t.pageX - startX) > moveThreshold ||
282                                 Math.abs(t.pageY - startY) > moveThreshold ),
283                 flags = getVirtualBindingFlags( event.target );
284
285         if ( didScroll && !didCancel ) {
286                 triggerVirtualEvent( "vmousecancel", event, flags );
287         }
288
289         triggerVirtualEvent( "vmousemove", event, flags );
290         startResetTimer();
291 }
292
293 function handleTouchEnd( event ) {
294         if ( blockTouchTriggers ) {
295                 return;
296         }
297
298         disableTouchBindings();
299
300         var flags = getVirtualBindingFlags( event.target ),
301                 t;
302         triggerVirtualEvent( "vmouseup", event, flags );
303
304         if ( !didScroll ) {
305                 var ve = triggerVirtualEvent( "vclick", event, flags );
306                 if ( ve && ve.isDefaultPrevented() ) {
307                         // The target of the mouse events that follow the touchend
308                         // event don't necessarily match the target used during the
309                         // touch. This means we need to rely on coordinates for blocking
310                         // any click that is generated.
311                         t = getNativeEvent( event ).changedTouches[ 0 ];
312                         clickBlockList.push({
313                                 touchID: lastTouchID,
314                                 x: t.clientX,
315                                 y: t.clientY
316                         });
317
318                         // Prevent any mouse events that follow from triggering
319                         // virtual event notifications.
320                         blockMouseTriggers = true;
321                 }
322         }
323         triggerVirtualEvent( "vmouseout", event, flags);
324         didScroll = false;
325
326         startResetTimer();
327 }
328
329 function hasVirtualBindings( ele ) {
330         var bindings = $.data( ele, dataPropertyName ),
331                 k;
332
333         if ( bindings ) {
334                 for ( k in bindings ) {
335                         if ( bindings[ k ] ) {
336                                 return true;
337                         }
338                 }
339         }
340         return false;
341 }
342
343 function dummyMouseHandler(){}
344
345 function getSpecialEventObject( eventType ) {
346         var realType = eventType.substr( 1 );
347
348         return {
349                 setup: function( data, namespace ) {
350                         // If this is the first virtual mouse binding for this element,
351                         // add a bindings object to its data.
352
353                         if ( !hasVirtualBindings( this ) ) {
354                                 $.data( this, dataPropertyName, {});
355                         }
356
357                         // If setup is called, we know it is the first binding for this
358                         // eventType, so initialize the count for the eventType to zero.
359                         var bindings = $.data( this, dataPropertyName );
360                         bindings[ eventType ] = true;
361
362                         // If this is the first virtual mouse event for this type,
363                         // register a global handler on the document.
364
365                         activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
366
367                         if ( activeDocHandlers[ eventType ] === 1 ) {
368                                 $document.bind( realType, mouseEventCallback );
369                         }
370
371                         // Some browsers, like Opera Mini, won't dispatch mouse/click events
372                         // for elements unless they actually have handlers registered on them.
373                         // To get around this, we register dummy handlers on the elements.
374
375                         $( this ).bind( realType, dummyMouseHandler );
376
377                         // For now, if event capture is not supported, we rely on mouse handlers.
378                         if ( eventCaptureSupported ) {
379                                 // If this is the first virtual mouse binding for the document,
380                                 // register our touchstart handler on the document.
381
382                                 activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
383
384                                 if (activeDocHandlers[ "touchstart" ] === 1) {
385                                         $document.bind( "touchstart", handleTouchStart )
386                                                 .bind( "touchend", handleTouchEnd )
387
388                                                 // On touch platforms, touching the screen and then dragging your finger
389                                                 // causes the window content to scroll after some distance threshold is
390                                                 // exceeded. On these platforms, a scroll prevents a click event from being
391                                                 // dispatched, and on some platforms, even the touchend is suppressed. To
392                                                 // mimic the suppression of the click event, we need to watch for a scroll
393                                                 // event. Unfortunately, some platforms like iOS don't dispatch scroll
394                                                 // events until *AFTER* the user lifts their finger (touchend). This means
395                                                 // we need to watch both scroll and touchmove events to figure out whether
396                                                 // or not a scroll happenens before the touchend event is fired.
397
398                                                 .bind( "touchmove", handleTouchMove )
399                                                 .bind( "scroll", handleScroll );
400                                 }
401                         }
402                 },
403
404                 teardown: function( data, namespace ) {
405                         // If this is the last virtual binding for this eventType,
406                         // remove its global handler from the document.
407
408                         --activeDocHandlers[ eventType ];
409
410                         if ( !activeDocHandlers[ eventType ] ) {
411                                 $document.unbind( realType, mouseEventCallback );
412                         }
413
414                         if ( eventCaptureSupported ) {
415                                 // If this is the last virtual mouse binding in existence,
416                                 // remove our document touchstart listener.
417
418                                 --activeDocHandlers[ "touchstart" ];
419
420                                 if ( !activeDocHandlers[ "touchstart" ] ) {
421                                         $document.unbind( "touchstart", handleTouchStart )
422                                                 .unbind( "touchmove", handleTouchMove )
423                                                 .unbind( "touchend", handleTouchEnd )
424                                                 .unbind( "scroll", handleScroll );
425                                 }
426                         }
427
428                         var $this = $( this ),
429                                 bindings = $.data( this, dataPropertyName );
430
431                         // teardown may be called when an element was
432                         // removed from the DOM. If this is the case,
433                         // jQuery core may have already stripped the element
434                         // of any data bindings so we need to check it before
435                         // using it.
436                         if ( bindings ) {
437                                 bindings[ eventType ] = false;
438                         }
439
440                         // Unregister the dummy event handler.
441
442                         $this.unbind( realType, dummyMouseHandler );
443
444                         // If this is the last virtual mouse binding on the
445                         // element, remove the binding data from the element.
446
447                         if ( !hasVirtualBindings( this ) ) {
448                                 $this.removeData( dataPropertyName );
449                         }
450                 }
451         };
452 }
453
454 // Expose our custom events to the jQuery bind/unbind mechanism.
455
456 for ( var i = 0; i < virtualEventNames.length; i++ ){
457         $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
458 }
459
460 // Add a capture click handler to block clicks.
461 // Note that we require event capture support for this so if the device
462 // doesn't support it, we punt for now and rely solely on mouse events.
463 if ( eventCaptureSupported ) {
464         document.addEventListener( "click", function( e ){
465                 var cnt = clickBlockList.length,
466                         target = e.target,
467                         x, y, ele, i, o, touchID;
468
469                 if ( cnt ) {
470                         x = e.clientX;
471                         y = e.clientY;
472                         threshold = $.vmouse.clickDistanceThreshold;
473
474                         // The idea here is to run through the clickBlockList to see if
475                         // the current click event is in the proximity of one of our
476                         // vclick events that had preventDefault() called on it. If we find
477                         // one, then we block the click.
478                         //
479                         // Why do we have to rely on proximity?
480                         //
481                         // Because the target of the touch event that triggered the vclick
482                         // can be different from the target of the click event synthesized
483                         // by the browser. The target of a mouse/click event that is syntehsized
484                         // from a touch event seems to be implementation specific. For example,
485                         // some browsers will fire mouse/click events for a link that is near
486                         // a touch event, even though the target of the touchstart/touchend event
487                         // says the user touched outside the link. Also, it seems that with most
488                         // browsers, the target of the mouse/click event is not calculated until the
489                         // time it is dispatched, so if you replace an element that you touched
490                         // with another element, the target of the mouse/click will be the new
491                         // element underneath that point.
492                         //
493                         // Aside from proximity, we also check to see if the target and any
494                         // of its ancestors were the ones that blocked a click. This is necessary
495                         // because of the strange mouse/click target calculation done in the
496                         // Android 2.1 browser, where if you click on an element, and there is a
497                         // mouse/click handler on one of its ancestors, the target will be the
498                         // innermost child of the touched element, even if that child is no where
499                         // near the point of touch.
500
501                         ele = target;
502
503                         while ( ele ) {
504                                 for ( i = 0; i < cnt; i++ ) {
505                                         o = clickBlockList[ i ];
506                                         touchID = 0;
507
508                                         if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
509                                                                 $.data( ele, touchTargetPropertyName ) === o.touchID ) {
510                                                 // XXX: We may want to consider removing matches from the block list
511                                                 //      instead of waiting for the reset timer to fire.
512                                                 e.preventDefault();
513                                                 e.stopPropagation();
514                                                 return;
515                                         }
516                                 }
517                                 ele = ele.parentNode;
518                         }
519                 }
520         }, true);
521 }
522 })( jQuery, window, document );
523
524
525
526 // Script: jQuery hashchange event
527 // 
528 // *Version: 1.3, Last updated: 7/21/2010*
529 // 
530 // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
531 // GitHub       - http://github.com/cowboy/jquery-hashchange/
532 // Source       - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
533 // (Minified)   - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
534 // 
535 // About: License
536 // 
537 // Copyright (c) 2010 "Cowboy" Ben Alman,
538 // Dual licensed under the MIT and GPL licenses.
539 // http://benalman.com/about/license/
540 // 
541 // About: Examples
542 // 
543 // These working examples, complete with fully commented code, illustrate a few
544 // ways in which this plugin can be used.
545 // 
546 // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
547 // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
548 // 
549 // About: Support and Testing
550 // 
551 // Information about what version or versions of jQuery this plugin has been
552 // tested with, what browsers it has been tested in, and where the unit tests
553 // reside (so you can test it yourself).
554 // 
555 // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
556 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
557 //                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
558 // Unit Tests      - http://benalman.com/code/projects/jquery-hashchange/unit/
559 // 
560 // About: Known issues
561 // 
562 // While this jQuery hashchange event implementation is quite stable and
563 // robust, there are a few unfortunate browser bugs surrounding expected
564 // hashchange event-based behaviors, independent of any JavaScript
565 // window.onhashchange abstraction. See the following examples for more
566 // information:
567 // 
568 // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
569 // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
570 // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
571 // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
572 // 
573 // Also note that should a browser natively support the window.onhashchange 
574 // event, but not report that it does, the fallback polling loop will be used.
575 // 
576 // About: Release History
577 // 
578 // 1.3   - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
579 //         "removable" for mobile-only development. Added IE6/7 document.title
580 //         support. Attempted to make Iframe as hidden as possible by using
581 //         techniques from http://www.paciellogroup.com/blog/?p=604. Added 
582 //         support for the "shortcut" format $(window).hashchange( fn ) and
583 //         $(window).hashchange() like jQuery provides for built-in events.
584 //         Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
585 //         lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
586 //         and <jQuery.fn.hashchange.src> properties plus document-domain.html
587 //         file to address access denied issues when setting document.domain in
588 //         IE6/7.
589 // 1.2   - (2/11/2010) Fixed a bug where coming back to a page using this plugin
590 //         from a page on another domain would cause an error in Safari 4. Also,
591 //         IE6/7 Iframe is now inserted after the body (this actually works),
592 //         which prevents the page from scrolling when the event is first bound.
593 //         Event can also now be bound before DOM ready, but it won't be usable
594 //         before then in IE6/7.
595 // 1.1   - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
596 //         where browser version is incorrectly reported as 8.0, despite
597 //         inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
598 // 1.0   - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
599 //         window.onhashchange functionality into a separate plugin for users
600 //         who want just the basic event & back button support, without all the
601 //         extra awesomeness that BBQ provides. This plugin will be included as
602 //         part of jQuery BBQ, but also be available separately.
603
604 (function($,window,undefined){
605   // Reused string.
606   var str_hashchange = 'hashchange',
607     
608     // Method / object references.
609     doc = document,
610     fake_onhashchange,
611     special = $.event.special,
612     
613     // Does the browser support window.onhashchange? Note that IE8 running in
614     // IE7 compatibility mode reports true for 'onhashchange' in window, even
615     // though the event isn't supported, so also test document.documentMode.
616     doc_mode = doc.documentMode,
617     supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
618   
619   // Get location.hash (or what you'd expect location.hash to be) sans any
620   // leading #. Thanks for making this necessary, Firefox!
621   function get_fragment( url ) {
622     url = url || location.href;
623     return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
624   };
625   
626   // Method: jQuery.fn.hashchange
627   // 
628   // Bind a handler to the window.onhashchange event or trigger all bound
629   // window.onhashchange event handlers. This behavior is consistent with
630   // jQuery's built-in event handlers.
631   // 
632   // Usage:
633   // 
634   // > jQuery(window).hashchange( [ handler ] );
635   // 
636   // Arguments:
637   // 
638   //  handler - (Function) Optional handler to be bound to the hashchange
639   //    event. This is a "shortcut" for the more verbose form:
640   //    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
641   //    all bound window.onhashchange event handlers will be triggered. This
642   //    is a shortcut for the more verbose
643   //    jQuery(window).trigger( 'hashchange' ). These forms are described in
644   //    the <hashchange event> section.
645   // 
646   // Returns:
647   // 
648   //  (jQuery) The initial jQuery collection of elements.
649   
650   // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
651   // $(elem).hashchange() for triggering, like jQuery does for built-in events.
652   $.fn[ str_hashchange ] = function( fn ) {
653     return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
654   };
655   
656   // Property: jQuery.fn.hashchange.delay
657   // 
658   // The numeric interval (in milliseconds) at which the <hashchange event>
659   // polling loop executes. Defaults to 50.
660   
661   // Property: jQuery.fn.hashchange.domain
662   // 
663   // If you're setting document.domain in your JavaScript, and you want hash
664   // history to work in IE6/7, not only must this property be set, but you must
665   // also set document.domain BEFORE jQuery is loaded into the page. This
666   // property is only applicable if you are supporting IE6/7 (or IE8 operating
667   // in "IE7 compatibility" mode).
668   // 
669   // In addition, the <jQuery.fn.hashchange.src> property must be set to the
670   // path of the included "document-domain.html" file, which can be renamed or
671   // modified if necessary (note that the document.domain specified must be the
672   // same in both your main JavaScript as well as in this file).
673   // 
674   // Usage:
675   // 
676   // jQuery.fn.hashchange.domain = document.domain;
677   
678   // Property: jQuery.fn.hashchange.src
679   // 
680   // If, for some reason, you need to specify an Iframe src file (for example,
681   // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
682   // do so using this property. Note that when using this property, history
683   // won't be recorded in IE6/7 until the Iframe src file loads. This property
684   // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
685   // compatibility" mode).
686   // 
687   // Usage:
688   // 
689   // jQuery.fn.hashchange.src = 'path/to/file.html';
690   
691   $.fn[ str_hashchange ].delay = 50;
692   /*
693   $.fn[ str_hashchange ].domain = null;
694   $.fn[ str_hashchange ].src = null;
695   */
696   
697   // Event: hashchange event
698   // 
699   // Fired when location.hash changes. In browsers that support it, the native
700   // HTML5 window.onhashchange event is used, otherwise a polling loop is
701   // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
702   // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
703   // compatibility" mode), a hidden Iframe is created to allow the back button
704   // and hash-based history to work.
705   // 
706   // Usage as described in <jQuery.fn.hashchange>:
707   // 
708   // > // Bind an event handler.
709   // > jQuery(window).hashchange( function(e) {
710   // >   var hash = location.hash;
711   // >   ...
712   // > });
713   // > 
714   // > // Manually trigger the event handler.
715   // > jQuery(window).hashchange();
716   // 
717   // A more verbose usage that allows for event namespacing:
718   // 
719   // > // Bind an event handler.
720   // > jQuery(window).bind( 'hashchange', function(e) {
721   // >   var hash = location.hash;
722   // >   ...
723   // > });
724   // > 
725   // > // Manually trigger the event handler.
726   // > jQuery(window).trigger( 'hashchange' );
727   // 
728   // Additional Notes:
729   // 
730   // * The polling loop and Iframe are not created until at least one handler
731   //   is actually bound to the 'hashchange' event.
732   // * If you need the bound handler(s) to execute immediately, in cases where
733   //   a location.hash exists on page load, via bookmark or page refresh for
734   //   example, use jQuery(window).hashchange() or the more verbose 
735   //   jQuery(window).trigger( 'hashchange' ).
736   // * The event can be bound before DOM ready, but since it won't be usable
737   //   before then in IE6/7 (due to the necessary Iframe), recommended usage is
738   //   to bind it inside a DOM ready handler.
739   
740   // Override existing $.event.special.hashchange methods (allowing this plugin
741   // to be defined after jQuery BBQ in BBQ's source code).
742   special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
743     
744     // Called only when the first 'hashchange' event is bound to window.
745     setup: function() {
746       // If window.onhashchange is supported natively, there's nothing to do..
747       if ( supports_onhashchange ) { return false; }
748       
749       // Otherwise, we need to create our own. And we don't want to call this
750       // until the user binds to the event, just in case they never do, since it
751       // will create a polling loop and possibly even a hidden Iframe.
752       $( fake_onhashchange.start );
753     },
754     
755     // Called only when the last 'hashchange' event is unbound from window.
756     teardown: function() {
757       // If window.onhashchange is supported natively, there's nothing to do..
758       if ( supports_onhashchange ) { return false; }
759       
760       // Otherwise, we need to stop ours (if possible).
761       $( fake_onhashchange.stop );
762     }
763     
764   });
765   
766   // fake_onhashchange does all the work of triggering the window.onhashchange
767   // event for browsers that don't natively support it, including creating a
768   // polling loop to watch for hash changes and in IE 6/7 creating a hidden
769   // Iframe to enable back and forward.
770   fake_onhashchange = (function(){
771     var self = {},
772       timeout_id,
773       
774       // Remember the initial hash so it doesn't get triggered immediately.
775       last_hash = get_fragment(),
776       
777       fn_retval = function(val){ return val; },
778       history_set = fn_retval,
779       history_get = fn_retval;
780     
781     // Start the polling loop.
782     self.start = function() {
783       timeout_id || poll();
784     };
785     
786     // Stop the polling loop.
787     self.stop = function() {
788       timeout_id && clearTimeout( timeout_id );
789       timeout_id = undefined;
790     };
791     
792     // This polling loop checks every $.fn.hashchange.delay milliseconds to see
793     // if location.hash has changed, and triggers the 'hashchange' event on
794     // window when necessary.
795     function poll() {
796       var hash = get_fragment(),
797         history_hash = history_get( last_hash );
798       
799       if ( hash !== last_hash ) {
800         history_set( last_hash = hash, history_hash );
801         
802         $(window).trigger( str_hashchange );
803         
804       } else if ( history_hash !== last_hash ) {
805         location.href = location.href.replace( /#.*/, '' ) + history_hash;
806       }
807       
808       timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
809     };
810     
811     // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
812     // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
813     // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
814     $.browser.msie && !supports_onhashchange && (function(){
815       // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
816       // when running in "IE7 compatibility" mode.
817       
818       var iframe,
819         iframe_src;
820       
821       // When the event is bound and polling starts in IE 6/7, create a hidden
822       // Iframe for history handling.
823       self.start = function(){
824         if ( !iframe ) {
825           iframe_src = $.fn[ str_hashchange ].src;
826           iframe_src = iframe_src && iframe_src + get_fragment();
827           
828           // Create hidden Iframe. Attempt to make Iframe as hidden as possible
829           // by using techniques from http://www.paciellogroup.com/blog/?p=604.
830           iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
831             
832             // When Iframe has completely loaded, initialize the history and
833             // start polling.
834             .one( 'load', function(){
835               iframe_src || history_set( get_fragment() );
836               poll();
837             })
838             
839             // Load Iframe src if specified, otherwise nothing.
840             .attr( 'src', iframe_src || 'javascript:0' )
841             
842             // Append Iframe after the end of the body to prevent unnecessary
843             // initial page scrolling (yes, this works).
844             .insertAfter( 'body' )[0].contentWindow;
845           
846           // Whenever `document.title` changes, update the Iframe's title to
847           // prettify the back/next history menu entries. Since IE sometimes
848           // errors with "Unspecified error" the very first time this is set
849           // (yes, very useful) wrap this with a try/catch block.
850           doc.onpropertychange = function(){
851             try {
852               if ( event.propertyName === 'title' ) {
853                 iframe.document.title = doc.title;
854               }
855             } catch(e) {}
856           };
857           
858         }
859       };
860       
861       // Override the "stop" method since an IE6/7 Iframe was created. Even
862       // if there are no longer any bound event handlers, the polling loop
863       // is still necessary for back/next to work at all!
864       self.stop = fn_retval;
865       
866       // Get history by looking at the hidden Iframe's location.hash.
867       history_get = function() {
868         return get_fragment( iframe.location.href );
869       };
870       
871       // Set a new history item by opening and then closing the Iframe
872       // document, *then* setting its location.hash. If document.domain has
873       // been set, update that as well.
874       history_set = function( hash, history_hash ) {
875         var iframe_doc = iframe.document,
876           domain = $.fn[ str_hashchange ].domain;
877         
878         if ( hash !== history_hash ) {
879           // Update Iframe with any initial `document.title` that might be set.
880           iframe_doc.title = doc.title;
881           
882           // Opening the Iframe's document after it has been closed is what
883           // actually adds a history entry.
884           iframe_doc.open();
885           
886           // Set document.domain for the Iframe document as well, if necessary.
887           domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
888           
889           iframe_doc.close();
890           
891           // Update the Iframe's hash, for great justice.
892           iframe.location.hash = hash;
893         }
894       };
895       
896     })();
897     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
898     // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
899     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
900     
901     return self;
902   })();
903   
904 })(jQuery,this);
905
906 /*!
907  * jQuery UI Widget @VERSION
908  *
909  * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
910  * Dual licensed under the MIT or GPL Version 2 licenses.
911  * http://jquery.org/license
912  *
913  * http://docs.jquery.com/UI/Widget
914  */
915
916 (function( $, undefined ) {
917
918 // jQuery 1.4+
919 if ( $.cleanData ) {
920         var _cleanData = $.cleanData;
921         $.cleanData = function( elems ) {
922                 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
923                         $( elem ).triggerHandler( "remove" );
924                 }
925                 _cleanData( elems );
926         };
927 } else {
928         var _remove = $.fn.remove;
929         $.fn.remove = function( selector, keepData ) {
930                 return this.each(function() {
931                         if ( !keepData ) {
932                                 if ( !selector || $.filter( selector, [ this ] ).length ) {
933                                         $( "*", this ).add( [ this ] ).each(function() {
934                                                 $( this ).triggerHandler( "remove" );
935                                         });
936                                 }
937                         }
938                         return _remove.call( $(this), selector, keepData );
939                 });
940         };
941 }
942
943 $.widget = function( name, base, prototype ) {
944         var namespace = name.split( "." )[ 0 ],
945                 fullName;
946         name = name.split( "." )[ 1 ];
947         fullName = namespace + "-" + name;
948
949         if ( !prototype ) {
950                 prototype = base;
951                 base = $.Widget;
952         }
953
954         // create selector for plugin
955         $.expr[ ":" ][ fullName ] = function( elem ) {
956                 return !!$.data( elem, name );
957         };
958
959         $[ namespace ] = $[ namespace ] || {};
960         $[ namespace ][ name ] = function( options, element ) {
961                 // allow instantiation without initializing for simple inheritance
962                 if ( arguments.length ) {
963                         this._createWidget( options, element );
964                 }
965         };
966
967         var basePrototype = new base();
968         // we need to make the options hash a property directly on the new instance
969         // otherwise we'll modify the options hash on the prototype that we're
970         // inheriting from
971 //      $.each( basePrototype, function( key, val ) {
972 //              if ( $.isPlainObject(val) ) {
973 //                      basePrototype[ key ] = $.extend( {}, val );
974 //              }
975 //      });
976         basePrototype.options = $.extend( true, {}, basePrototype.options );
977         $[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
978                 namespace: namespace,
979                 widgetName: name,
980                 widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
981                 widgetBaseClass: fullName
982         }, prototype );
983
984         $.widget.bridge( name, $[ namespace ][ name ] );
985 };
986
987 $.widget.bridge = function( name, object ) {
988         $.fn[ name ] = function( options ) {
989                 var isMethodCall = typeof options === "string",
990                         args = Array.prototype.slice.call( arguments, 1 ),
991                         returnValue = this;
992
993                 // allow multiple hashes to be passed on init
994                 options = !isMethodCall && args.length ?
995                         $.extend.apply( null, [ true, options ].concat(args) ) :
996                         options;
997
998                 // prevent calls to internal methods
999                 if ( isMethodCall && options.charAt( 0 ) === "_" ) {
1000                         return returnValue;
1001                 }
1002
1003                 if ( isMethodCall ) {
1004                         this.each(function() {
1005                                 var instance = $.data( this, name );
1006                                 if ( !instance ) {
1007                                         throw "cannot call methods on " + name + " prior to initialization; " +
1008                                                 "attempted to call method '" + options + "'";
1009                                 }
1010                                 if ( !$.isFunction( instance[options] ) ) {
1011                                         throw "no such method '" + options + "' for " + name + " widget instance";
1012                                 }
1013                                 var methodValue = instance[ options ].apply( instance, args );
1014                                 if ( methodValue !== instance && methodValue !== undefined ) {
1015                                         returnValue = methodValue;
1016                                         return false;
1017                                 }
1018                         });
1019                 } else {
1020                         this.each(function() {
1021                                 var instance = $.data( this, name );
1022                                 if ( instance ) {
1023                                         instance.option( options || {} )._init();
1024                                 } else {
1025                                         $.data( this, name, new object( options, this ) );
1026                                 }
1027                         });
1028                 }
1029
1030                 return returnValue;
1031         };
1032 };
1033
1034 $.Widget = function( options, element ) {
1035         // allow instantiation without initializing for simple inheritance
1036         if ( arguments.length ) {
1037                 this._createWidget( options, element );
1038         }
1039 };
1040
1041 $.Widget.prototype = {
1042         widgetName: "widget",
1043         widgetEventPrefix: "",
1044         options: {
1045                 disabled: false
1046         },
1047         _createWidget: function( options, element ) {
1048                 // $.widget.bridge stores the plugin instance, but we do it anyway
1049                 // so that it's stored even before the _create function runs
1050                 $.data( element, this.widgetName, this );
1051                 this.element = $( element );
1052                 this.options = $.extend( true, {},
1053                         this.options,
1054                         this._getCreateOptions(),
1055                         options );
1056
1057                 var self = this;
1058                 this.element.bind( "remove." + this.widgetName, function() {
1059                         self.destroy();
1060                 });
1061
1062                 this._create();
1063                 this._trigger( "create" );
1064                 this._init();
1065         },
1066         _getCreateOptions: function() {
1067                 var options = {};
1068                 if ( $.metadata ) {
1069                         options = $.metadata.get( element )[ this.widgetName ];
1070                 }
1071                 return options;
1072         },
1073         _create: function() {},
1074         _init: function() {},
1075
1076         destroy: function() {
1077                 this.element
1078                         .unbind( "." + this.widgetName )
1079                         .removeData( this.widgetName );
1080                 this.widget()
1081                         .unbind( "." + this.widgetName )
1082                         .removeAttr( "aria-disabled" )
1083                         .removeClass(
1084                                 this.widgetBaseClass + "-disabled " +
1085                                 "ui-state-disabled" );
1086         },
1087
1088         widget: function() {
1089                 return this.element;
1090         },
1091
1092         option: function( key, value ) {
1093                 var options = key;
1094
1095                 if ( arguments.length === 0 ) {
1096                         // don't return a reference to the internal hash
1097                         return $.extend( {}, this.options );
1098                 }
1099
1100                 if  (typeof key === "string" ) {
1101                         if ( value === undefined ) {
1102                                 return this.options[ key ];
1103                         }
1104                         options = {};
1105                         options[ key ] = value;
1106                 }
1107
1108                 this._setOptions( options );
1109
1110                 return this;
1111         },
1112         _setOptions: function( options ) {
1113                 var self = this;
1114                 $.each( options, function( key, value ) {
1115                         self._setOption( key, value );
1116                 });
1117
1118                 return this;
1119         },
1120         _setOption: function( key, value ) {
1121                 this.options[ key ] = value;
1122
1123                 if ( key === "disabled" ) {
1124                         this.widget()
1125                                 [ value ? "addClass" : "removeClass"](
1126                                         this.widgetBaseClass + "-disabled" + " " +
1127                                         "ui-state-disabled" )
1128                                 .attr( "aria-disabled", value );
1129                 }
1130
1131                 return this;
1132         },
1133
1134         enable: function() {
1135                 return this._setOption( "disabled", false );
1136         },
1137         disable: function() {
1138                 return this._setOption( "disabled", true );
1139         },
1140
1141         _trigger: function( type, event, data ) {
1142                 var callback = this.options[ type ];
1143
1144                 event = $.Event( event );
1145                 event.type = ( type === this.widgetEventPrefix ?
1146                         type :
1147                         this.widgetEventPrefix + type ).toLowerCase();
1148                 data = data || {};
1149
1150                 // copy original event properties over to the new event
1151                 // this would happen if we could call $.event.fix instead of $.Event
1152                 // but we don't have a way to force an event to be fixed multiple times
1153                 if ( event.originalEvent ) {
1154                         for ( var i = $.event.props.length, prop; i; ) {
1155                                 prop = $.event.props[ --i ];
1156                                 event[ prop ] = event.originalEvent[ prop ];
1157                         }
1158                 }
1159
1160                 this.element.trigger( event, data );
1161
1162                 return !( $.isFunction(callback) &&
1163                         callback.call( this.element[0], event, data ) === false ||
1164                         event.isDefaultPrevented() );
1165         }
1166 };
1167
1168 })( jQuery );
1169
1170 (function( $, undefined ) {
1171
1172 $.widget( "mobile.widget", {
1173         // decorate the parent _createWidget to trigger `widgetinit` for users
1174         // who wish to do post post `widgetcreate` alterations/additions
1175         //
1176         // TODO create a pull request for jquery ui to trigger this event
1177         // in the original _createWidget
1178         _createWidget: function() {
1179                 $.Widget.prototype._createWidget.apply( this, arguments );
1180                 this._trigger( 'init' );
1181         },
1182
1183         _getCreateOptions: function() {
1184
1185                 var elem = this.element,
1186                         options = {};
1187
1188                 $.each( this.options, function( option ) {
1189
1190                         var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
1191                                                         return "-" + c.toLowerCase();
1192                                                 })
1193                                         );
1194
1195                         if ( value !== undefined ) {
1196                                 options[ option ] = value;
1197                         }
1198                 });
1199
1200                 return options;
1201         },
1202
1203         enhanceWithin: function( target, useKeepNative ) {
1204                 this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
1205         },
1206
1207         enhance: function( targets, useKeepNative ) {
1208                 var page, keepNative, $widgetElements = $( targets ), self = this;
1209
1210                 // if ignoreContentEnabled is set to true the framework should
1211                 // only enhance the selected elements when they do NOT have a
1212                 // parent with the data-namespace-ignore attribute
1213                 $widgetElements = $.mobile.enhanceable( $widgetElements );
1214
1215                 if ( useKeepNative && $widgetElements.length ) {
1216                         // TODO remove dependency on the page widget for the keepNative.
1217                         // Currently the keepNative value is defined on the page prototype so
1218                         // the method is as well
1219                         page = $.mobile.closestPageData( $widgetElements );
1220                         keepNative = (page && page.keepNativeSelector()) || "";
1221
1222                         $widgetElements = $widgetElements.not( keepNative );
1223                 }
1224
1225                 $widgetElements[ this.widgetName ]();
1226         },
1227
1228         raise: function( msg ) {
1229                 throw "Widget [" + this.widgetName + "]: " + msg;
1230         }
1231 });
1232
1233 })( jQuery );
1234
1235 (function( $, window, undefined ) {
1236
1237         var nsNormalizeDict = {};
1238
1239         // jQuery.mobile configurable options
1240         $.mobile = $.extend( {}, {
1241
1242                 // Version of the jQuery Mobile Framework
1243                 version: "1.1.1",
1244
1245                 // Namespace used framework-wide for data-attrs. Default is no namespace
1246                 ns: "",
1247
1248                 // Define the url parameter used for referencing widget-generated sub-pages.
1249                 // Translates to to example.html&ui-page=subpageIdentifier
1250                 // hash segment before &ui-page= is used to make Ajax request
1251                 subPageUrlKey: "ui-page",
1252
1253                 // Class assigned to page currently in view, and during transitions
1254                 activePageClass: "ui-page-active",
1255
1256                 // Class used for "active" button state, from CSS framework
1257                 activeBtnClass: "ui-btn-active",
1258
1259                 // Class used for "focus" form element state, from CSS framework
1260                 focusClass: "ui-focus",
1261
1262                 // Automatically handle clicks and form submissions through Ajax, when same-domain
1263                 ajaxEnabled: true,
1264
1265                 // Automatically load and show pages based on location.hash
1266                 hashListeningEnabled: true,
1267
1268                 // disable to prevent jquery from bothering with links
1269                 linkBindingEnabled: true,
1270
1271                 // Set default page transition - 'none' for no transitions
1272                 defaultPageTransition: "fade",
1273
1274                 // Set maximum window width for transitions to apply - 'false' for no limit
1275                 maxTransitionWidth: false,
1276
1277                 // Minimum scroll distance that will be remembered when returning to a page
1278                 minScrollBack: 250,
1279
1280                 // DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
1281                 touchOverflowEnabled: false,
1282
1283                 // Set default dialog transition - 'none' for no transitions
1284                 defaultDialogTransition: "pop",
1285
1286                 // Show loading message during Ajax requests
1287                 // if false, message will not appear, but loading classes will still be toggled on html el
1288                 loadingMessage: "loading",
1289
1290                 // Error response message - appears when an Ajax page request fails
1291                 pageLoadErrorMessage: "Error Loading Page",
1292
1293                 // Should the text be visble in the loading message?
1294                 loadingMessageTextVisible: false,
1295
1296                 // When the text is visible, what theme does the loading box use?
1297                 loadingMessageTheme: "a",
1298
1299                 // For error messages, which theme does the box uses?
1300                 pageLoadErrorMessageTheme: "e",
1301
1302                 //automatically initialize the DOM when it's ready
1303                 autoInitializePage: true,
1304
1305                 pushStateEnabled: true,
1306
1307                 // allows users to opt in to ignoring content by marking a parent element as
1308                 // data-ignored
1309                 ignoreContentEnabled: false,
1310
1311                 // turn of binding to the native orientationchange due to android orientation behavior
1312                 orientationChangeEnabled: true,
1313
1314                 buttonMarkup: {
1315                         hoverDelay: 200
1316                 },
1317
1318                 // TODO might be useful upstream in jquery itself ?
1319                 keyCode: {
1320                         ALT: 18,
1321                         BACKSPACE: 8,
1322                         CAPS_LOCK: 20,
1323                         COMMA: 188,
1324                         COMMAND: 91,
1325                         COMMAND_LEFT: 91, // COMMAND
1326                         COMMAND_RIGHT: 93,
1327                         CONTROL: 17,
1328                         DELETE: 46,
1329                         DOWN: 40,
1330                         END: 35,
1331                         ENTER: 13,
1332                         ESCAPE: 27,
1333                         HOME: 36,
1334                         INSERT: 45,
1335                         LEFT: 37,
1336                         MENU: 93, // COMMAND_RIGHT
1337                         NUMPAD_ADD: 107,
1338                         NUMPAD_DECIMAL: 110,
1339                         NUMPAD_DIVIDE: 111,
1340                         NUMPAD_ENTER: 108,
1341                         NUMPAD_MULTIPLY: 106,
1342                         NUMPAD_SUBTRACT: 109,
1343                         PAGE_DOWN: 34,
1344                         PAGE_UP: 33,
1345                         PERIOD: 190,
1346                         RIGHT: 39,
1347                         SHIFT: 16,
1348                         SPACE: 32,
1349                         TAB: 9,
1350                         UP: 38,
1351                         WINDOWS: 91 // COMMAND
1352                 },
1353
1354                 // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
1355                 silentScroll: function( ypos ) {
1356                         if ( $.type( ypos ) !== "number" ) {
1357                                 ypos = $.mobile.defaultHomeScroll;
1358                         }
1359
1360                         // prevent scrollstart and scrollstop events
1361                         $.event.special.scrollstart.enabled = false;
1362
1363                         setTimeout(function() {
1364                                 window.scrollTo( 0, ypos );
1365                                 $( document ).trigger( "silentscroll", { x: 0, y: ypos });
1366                         }, 20 );
1367
1368                         setTimeout(function() {
1369                                 $.event.special.scrollstart.enabled = true;
1370                         }, 150 );
1371                 },
1372
1373                 // Expose our cache for testing purposes.
1374                 nsNormalizeDict: nsNormalizeDict,
1375
1376                 // Take a data attribute property, prepend the namespace
1377                 // and then camel case the attribute string. Add the result
1378                 // to our nsNormalizeDict so we don't have to do this again.
1379                 nsNormalize: function( prop ) {
1380                         if ( !prop ) {
1381                                 return;
1382                         }
1383
1384                         return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
1385                 },
1386
1387                 // Find the closest parent with a theme class on it. Note that
1388                 // we are not using $.fn.closest() on purpose here because this
1389                 // method gets called quite a bit and we need it to be as fast
1390                 // as possible.
1391                 getInheritedTheme: function( el, defaultTheme ) {
1392                         var e = el[ 0 ],
1393                                 ltr = "",
1394                                 re = /ui-(bar|body|overlay)-([a-z])\b/,
1395                                 c, m;
1396
1397                         while ( e ) {
1398                                 c = e.className || "";
1399                                 if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
1400                                         // We found a parent with a theme class
1401                                         // on it so bail from this loop.
1402                                         break;
1403                                 }
1404
1405                                 e = e.parentNode;
1406                         }
1407
1408                         // Return the theme letter we found, if none, return the
1409                         // specified default.
1410
1411                         return ltr || defaultTheme || "a";
1412                 },
1413
1414                 // TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
1415                 //
1416                 // Find the closest javascript page element to gather settings data jsperf test
1417                 // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
1418                 // possibly naive, but it shows that the parsing overhead for *just* the page selector vs
1419                 // the page and dialog selector is negligable. This could probably be speed up by
1420                 // doing a similar parent node traversal to the one found in the inherited theme code above
1421                 closestPageData: function( $target ) {
1422                         return $target
1423                                 .closest(':jqmData(role="page"), :jqmData(role="dialog")')
1424                                 .data("page");
1425                 },
1426
1427                 enhanceable: function( $set ) {
1428                         return this.haveParents( $set, "enhance" );
1429                 },
1430
1431                 hijackable: function( $set ) {
1432                         return this.haveParents( $set, "ajax" );
1433                 },
1434
1435                 haveParents: function( $set, attr ) {
1436                         if( !$.mobile.ignoreContentEnabled ){
1437                                 return $set;
1438                         }
1439
1440                         var count = $set.length,
1441                                 $newSet = $(),
1442                                 e, $element, excluded;
1443
1444                         for ( var i = 0; i < count; i++ ) {
1445                                 $element = $set.eq( i );
1446                                 excluded = false;
1447                                 e = $set[ i ];
1448
1449                                 while ( e ) {
1450                                         var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
1451
1452                                         if ( c === "false" ) {
1453                                                 excluded = true;
1454                                                 break;
1455                                         }
1456
1457                                         e = e.parentNode;
1458                                 }
1459
1460                                 if ( !excluded ) {
1461                                         $newSet = $newSet.add( $element );
1462                                 }
1463                         }
1464
1465                         return $newSet;
1466                 },
1467
1468                 getScreenHeight: function(){
1469                         // Native innerHeight returns more accurate value for this across platforms,
1470                         // jQuery version is here as a normalized fallback for platforms like Symbian
1471                         return window.innerHeight || $( window ).height();
1472                 }
1473         }, $.mobile );
1474
1475         // Mobile version of data and removeData and hasData methods
1476         // ensures all data is set and retrieved using jQuery Mobile's data namespace
1477         $.fn.jqmData = function( prop, value ) {
1478                 var result;
1479                 if ( typeof prop != "undefined" ) {
1480                         if ( prop ) {
1481                                 prop = $.mobile.nsNormalize( prop );
1482                         }
1483                         result = this.data.apply( this, arguments.length < 2 ? [ prop ] : [ prop, value ] );
1484                 }
1485                 return result;
1486         };
1487
1488         $.jqmData = function( elem, prop, value ) {
1489                 var result;
1490                 if ( typeof prop != "undefined" ) {
1491                         result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
1492                 }
1493                 return result;
1494         };
1495
1496         $.fn.jqmRemoveData = function( prop ) {
1497                 return this.removeData( $.mobile.nsNormalize( prop ) );
1498         };
1499
1500         $.jqmRemoveData = function( elem, prop ) {
1501                 return $.removeData( elem, $.mobile.nsNormalize( prop ) );
1502         };
1503
1504         $.fn.removeWithDependents = function() {
1505                 $.removeWithDependents( this );
1506         };
1507
1508         $.removeWithDependents = function( elem ) {
1509                 var $elem = $( elem );
1510
1511                 ( $elem.jqmData('dependents') || $() ).remove();
1512                 $elem.remove();
1513         };
1514
1515         $.fn.addDependents = function( newDependents ) {
1516                 $.addDependents( $(this), newDependents );
1517         };
1518
1519         $.addDependents = function( elem, newDependents ) {
1520                 var dependents = $(elem).jqmData( 'dependents' ) || $();
1521
1522                 $(elem).jqmData( 'dependents', $.merge(dependents, newDependents) );
1523         };
1524
1525         // note that this helper doesn't attempt to handle the callback
1526         // or setting of an html elements text, its only purpose is
1527         // to return the html encoded version of the text in all cases. (thus the name)
1528         $.fn.getEncodedText = function() {
1529                 return $( "<div/>" ).text( $(this).text() ).html();
1530         };
1531
1532         // fluent helper function for the mobile namespaced equivalent
1533         $.fn.jqmEnhanceable = function() {
1534                 return $.mobile.enhanceable( this );
1535         };
1536
1537         $.fn.jqmHijackable = function() {
1538                 return $.mobile.hijackable( this );
1539         };
1540
1541         // Monkey-patching Sizzle to filter the :jqmData selector
1542         var oldFind = $.find,
1543                 jqmDataRE = /:jqmData\(([^)]*)\)/g;
1544
1545         $.find = function( selector, context, ret, extra ) {
1546                 selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
1547
1548                 return oldFind.call( this, selector, context, ret, extra );
1549         };
1550
1551         $.extend( $.find, oldFind );
1552
1553         $.find.matches = function( expr, set ) {
1554                 return $.find( expr, null, null, set );
1555         };
1556
1557         $.find.matchesSelector = function( node, expr ) {
1558                 return $.find( expr, null, null, [ node ] ).length > 0;
1559         };
1560 })( jQuery, this );
1561
1562
1563 (function( $, undefined ) {
1564
1565 var $window = $( window ),
1566         $html = $( "html" );
1567
1568 /* $.mobile.media method: pass a CSS media type or query and get a bool return
1569         note: this feature relies on actual media query support for media queries, though types will work most anywhere
1570         examples:
1571                 $.mobile.media('screen') // tests for screen media type
1572                 $.mobile.media('screen and (min-width: 480px)') // tests for screen media type with window width > 480px
1573                 $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') // tests for webkit 2x pixel ratio (iPhone 4)
1574 */
1575 $.mobile.media = (function() {
1576         // TODO: use window.matchMedia once at least one UA implements it
1577         var cache = {},
1578                 testDiv = $( "<div id='jquery-mediatest'></div>" ),
1579                 fakeBody = $( "<body>" ).append( testDiv );
1580
1581         return function( query ) {
1582                 if ( !( query in cache ) ) {
1583                         var styleBlock = document.createElement( "style" ),
1584                                 cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }";
1585
1586                         //must set type for IE!
1587                         styleBlock.type = "text/css";
1588
1589                         if ( styleBlock.styleSheet  ){
1590                                 styleBlock.styleSheet.cssText = cssrule;
1591                         } else {
1592                                 styleBlock.appendChild( document.createTextNode(cssrule) );
1593                         }
1594
1595                         $html.prepend( fakeBody ).prepend( styleBlock );
1596                         cache[ query ] = testDiv.css( "position" ) === "absolute";
1597                         fakeBody.add( styleBlock ).remove();
1598                 }
1599                 return cache[ query ];
1600         };
1601 })();
1602
1603 })(jQuery);
1604
1605 (function( $, undefined ) {
1606
1607 var fakeBody = $( "<body>" ).prependTo( "html" ),
1608         fbCSS = fakeBody[ 0 ].style,
1609         vendors = [ "Webkit", "Moz", "O" ],
1610         webos = "palmGetResource" in window, //only used to rule out scrollTop
1611         opera = window.opera,
1612         operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
1613         bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB
1614
1615 // thx Modernizr
1616 function propExists( prop ) {
1617         var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
1618                 props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
1619
1620         for ( var v in props ){
1621                 if ( fbCSS[ props[ v ] ] !== undefined ) {
1622                         return true;
1623                 }
1624         }
1625 }
1626
1627 function validStyle( prop, value, check_vend ) {
1628         var div = document.createElement('div'),
1629                 uc = function( txt ) {
1630                         return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 )
1631                 },
1632                 vend_pref = function( vend ) {
1633                         return  "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
1634                 },
1635                 check_style = function( vend ) {
1636                         var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
1637                                 uc_vend = uc( vend ),
1638                                 propStyle = uc_vend + uc( prop );
1639                 
1640                         div.setAttribute( "style", vend_prop );
1641                 
1642                         if( !!div.style[ propStyle ] ) {
1643                                 ret = true;
1644                         }
1645                 },
1646                 check_vends = check_vend ? [ check_vend ] : vendors,
1647                 ret;
1648
1649         for( i = 0; i < check_vends.length; i++ ) {
1650                 check_style( check_vends[i] );
1651         }
1652         return !!ret;
1653 }
1654
1655 // Thanks to Modernizr src for this test idea. `perspective` check is limited to Moz to prevent a false positive for 3D transforms on Android.
1656 function transform3dTest() {
1657         var prop = "transform-3d";
1658         return validStyle( 'perspective', '10px', 'moz' ) || $.mobile.media( "(-" + vendors.join( "-" + prop + "),(-" ) + "-" + prop + "),(" + prop + ")" );
1659 }
1660
1661 // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
1662 function baseTagTest() {
1663         var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
1664                 base = $( "head base" ),
1665                 fauxEle = null,
1666                 href = "",
1667                 link, rebase;
1668
1669         if ( !base.length ) {
1670                 base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
1671         } else {
1672                 href = base.attr( "href" );
1673         }
1674
1675         link = $( "<a href='testurl' />" ).prependTo( fakeBody );
1676         rebase = link[ 0 ].href;
1677         base[ 0 ].href = href || location.pathname;
1678
1679         if ( fauxEle ) {
1680                 fauxEle.remove();
1681         }
1682         return rebase.indexOf( fauxBase ) === 0;
1683 }
1684
1685 // Thanks Modernizr
1686 function cssPointerEventsTest() {
1687         var element = document.createElement('x'),
1688                 documentElement = document.documentElement,
1689                 getComputedStyle = window.getComputedStyle,
1690                 supports;
1691
1692         if( !( 'pointerEvents' in element.style ) ){
1693                 return false;
1694         }
1695
1696         element.style.pointerEvents = 'auto';
1697         element.style.pointerEvents = 'x';
1698     documentElement.appendChild(element);
1699         supports = getComputedStyle &&
1700     getComputedStyle( element, '' ).pointerEvents === 'auto';
1701         documentElement.removeChild( element );
1702     return !!supports;
1703 }
1704
1705
1706 // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
1707 // allows for inclusion of IE 6+, including Windows Mobile 7
1708 $.extend( $.mobile, { browser: {} } );
1709 $.mobile.browser.ie = (function() {
1710         var v = 3,
1711         div = document.createElement( "div" ),
1712         a = div.all || [];
1713
1714         // added {} to silence closure compiler warnings. registering my dislike of all things
1715         // overly clever here for future reference
1716         while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ){};
1717
1718         return v > 4 ? v : !v;
1719 })();
1720
1721
1722 $.extend( $.support, {
1723         orientation: "orientation" in window && "onorientationchange" in window,
1724         touch: "ontouchend" in document,
1725         cssTransitions: "WebKitTransitionEvent" in window || validStyle( 'transition', 'height 100ms linear' ) && !opera,
1726         pushState: "pushState" in history && "replaceState" in history,
1727         mediaquery: $.mobile.media( "only all" ),
1728         cssPseudoElement: !!propExists( "content" ),
1729         touchOverflow: !!propExists( "overflowScrolling" ),
1730         cssTransform3d: transform3dTest(),
1731         boxShadow: !!propExists( "boxShadow" ) && !bb,
1732         scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos && !operamini,
1733         dynamicBaseTag: baseTagTest(),
1734         cssPointerEvents: cssPointerEventsTest()
1735 });
1736
1737 fakeBody.remove();
1738
1739
1740 // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
1741 // or that generally work better browsing in regular http for full page refreshes (Opera Mini)
1742 // Note: This detection below is used as a last resort.
1743 // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
1744 var nokiaLTE7_3 = (function(){
1745
1746         var ua = window.navigator.userAgent;
1747
1748         //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
1749         return ua.indexOf( "Nokia" ) > -1 &&
1750                         ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
1751                         ua.indexOf( "AppleWebKit" ) > -1 &&
1752                         ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
1753 })();
1754
1755 // Support conditions that must be met in order to proceed
1756 // default enhanced qualifications are media query support OR IE 7+
1757 $.mobile.gradeA = function(){
1758         return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7;
1759 };
1760
1761 $.mobile.ajaxBlacklist =
1762                         // BlackBerry browsers, pre-webkit
1763                         window.blackberry && !window.WebKitPoint ||
1764                         // Opera Mini
1765                         operamini ||
1766                         // Symbian webkits pre 7.3
1767                         nokiaLTE7_3;
1768
1769 // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
1770 // to render the stylesheets when they're referenced before this script, as we'd recommend doing.
1771 // This simply reappends the CSS in place, which for some reason makes it apply
1772 if ( nokiaLTE7_3 ) {
1773         $(function() {
1774                 $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
1775         });
1776 }
1777
1778 // For ruling out shadows via css
1779 if ( !$.support.boxShadow ) {
1780         $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
1781 }
1782
1783 })( jQuery );
1784
1785 (function( $, window, undefined ) {
1786
1787 // add new event shortcuts
1788 $.each( ( "touchstart touchmove touchend orientationchange throttledresize " +
1789                                         "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) {
1790
1791         $.fn[ name ] = function( fn ) {
1792                 return fn ? this.bind( name, fn ) : this.trigger( name );
1793         };
1794
1795         $.attrFn[ name ] = true;
1796 });
1797
1798 var supportTouch = $.support.touch,
1799         scrollEvent = "touchmove scroll",
1800         touchStartEvent = supportTouch ? "touchstart" : "mousedown",
1801         touchStopEvent = supportTouch ? "touchend" : "mouseup",
1802         touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
1803
1804 function triggerCustomEvent( obj, eventType, event ) {
1805         var originalType = event.type;
1806         event.type = eventType;
1807         $.event.handle.call( obj, event );
1808         event.type = originalType;
1809 }
1810
1811 // also handles scrollstop
1812 $.event.special.scrollstart = {
1813
1814         enabled: true,
1815
1816         setup: function() {
1817
1818                 var thisObject = this,
1819                         $this = $( thisObject ),
1820                         scrolling,
1821                         timer;
1822
1823                 function trigger( event, state ) {
1824                         scrolling = state;
1825                         triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
1826                 }
1827
1828                 // iPhone triggers scroll after a small delay; use touchmove instead
1829                 $this.bind( scrollEvent, function( event ) {
1830
1831                         if ( !$.event.special.scrollstart.enabled ) {
1832                                 return;
1833                         }
1834
1835                         if ( !scrolling ) {
1836                                 trigger( event, true );
1837                         }
1838
1839                         clearTimeout( timer );
1840                         timer = setTimeout(function() {
1841                                 trigger( event, false );
1842                         }, 50 );
1843                 });
1844         }
1845 };
1846
1847 // also handles taphold
1848 $.event.special.tap = {
1849         setup: function() {
1850                 var thisObject = this,
1851                         $this = $( thisObject );
1852
1853                 $this.bind( "vmousedown", function( event ) {
1854
1855                         if ( event.which && event.which !== 1 ) {
1856                                 return false;
1857                         }
1858
1859                         var origTarget = event.target,
1860                                 origEvent = event.originalEvent,
1861                                 timer;
1862
1863                         function clearTapTimer() {
1864                                 clearTimeout( timer );
1865                         }
1866
1867                         function clearTapHandlers() {
1868                                 clearTapTimer();
1869
1870                                 $this.unbind( "vclick", clickHandler )
1871                                         .unbind( "vmouseup", clearTapTimer );
1872                                 $( document ).unbind( "vmousecancel", clearTapHandlers );
1873                         }
1874
1875                         function clickHandler(event) {
1876                                 clearTapHandlers();
1877
1878                                 // ONLY trigger a 'tap' event if the start target is
1879                                 // the same as the stop target.
1880                                 if ( origTarget == event.target ) {
1881                                         triggerCustomEvent( thisObject, "tap", event );
1882                                 }
1883                         }
1884
1885                         $this.bind( "vmouseup", clearTapTimer )
1886                                 .bind( "vclick", clickHandler );
1887                         $( document ).bind( "vmousecancel", clearTapHandlers );
1888
1889                         timer = setTimeout(function() {
1890                                         triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
1891                         }, 750 );
1892                 });
1893         }
1894 };
1895
1896 // also handles swipeleft, swiperight
1897 $.event.special.swipe = {
1898         scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling.
1899
1900         durationThreshold: 1000, // More time than this, and it isn't a swipe.
1901
1902         horizontalDistanceThreshold: 30,  // Swipe horizontal displacement must be more than this.
1903
1904         verticalDistanceThreshold: 75,  // Swipe vertical displacement must be less than this.
1905
1906         setup: function() {
1907                 var thisObject = this,
1908                         $this = $( thisObject );
1909
1910                 $this.bind( touchStartEvent, function( event ) {
1911                         var data = event.originalEvent.touches ?
1912                                                                 event.originalEvent.touches[ 0 ] : event,
1913                                 start = {
1914                                         time: ( new Date() ).getTime(),
1915                                         coords: [ data.pageX, data.pageY ],
1916                                         origin: $( event.target )
1917                                 },
1918                                 stop;
1919
1920                         function moveHandler( event ) {
1921
1922                                 if ( !start ) {
1923                                         return;
1924                                 }
1925
1926                                 var data = event.originalEvent.touches ?
1927                                                 event.originalEvent.touches[ 0 ] : event;
1928
1929                                 stop = {
1930                                         time: ( new Date() ).getTime(),
1931                                         coords: [ data.pageX, data.pageY ]
1932                                 };
1933
1934                                 // prevent scrolling
1935                                 if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
1936                                         event.preventDefault();
1937                                 }
1938                         }
1939
1940                         $this.bind( touchMoveEvent, moveHandler )
1941                                 .one( touchStopEvent, function( event ) {
1942                                         $this.unbind( touchMoveEvent, moveHandler );
1943
1944                                         if ( start && stop ) {
1945                                                 if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
1946                                                                 Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
1947                                                                 Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
1948
1949                                                         start.origin.trigger( "swipe" )
1950                                                                 .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
1951                                                 }
1952                                         }
1953                                         start = stop = undefined;
1954                                 });
1955                 });
1956         }
1957 };
1958
1959 (function( $, window ) {
1960         // "Cowboy" Ben Alman
1961
1962         var win = $( window ),
1963                 special_event,
1964                 get_orientation,
1965                 last_orientation,
1966                 initial_orientation_is_landscape,
1967                 initial_orientation_is_default,
1968                 portrait_map = { "0": true, "180": true };
1969
1970         // It seems that some device/browser vendors use window.orientation values 0 and 180 to
1971         // denote the "default" orientation. For iOS devices, and most other smart-phones tested,
1972         // the default orientation is always "portrait", but in some Android and RIM based tablets,
1973         // the default orientation is "landscape". The following code attempts to use the window
1974         // dimensions to figure out what the current orientation is, and then makes adjustments
1975         // to the to the portrait_map if necessary, so that we can properly decode the
1976         // window.orientation value whenever get_orientation() is called.
1977         //
1978         // Note that we used to use a media query to figure out what the orientation the browser
1979         // thinks it is in:
1980         //
1981         //     initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
1982         //
1983         // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
1984         // where the browser *ALWAYS* applied the landscape media query. This bug does not
1985         // happen on iPad.
1986
1987         if ( $.support.orientation ) {
1988
1989                 // Check the window width and height to figure out what the current orientation
1990                 // of the device is at this moment. Note that we've initialized the portrait map
1991                 // values to 0 and 180, *AND* we purposely check for landscape so that if we guess
1992                 // wrong, , we default to the assumption that portrait is the default orientation.
1993                 // We use a threshold check below because on some platforms like iOS, the iPhone
1994                 // form-factor can report a larger width than height if the user turns on the
1995                 // developer console. The actual threshold value is somewhat arbitrary, we just
1996                 // need to make sure it is large enough to exclude the developer console case.
1997
1998                 var ww = window.innerWidth || $( window ).width(),
1999                         wh = window.innerHeight || $( window ).height(),
2000                         landscape_threshold = 50;
2001
2002                 initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
2003
2004
2005                 // Now check to see if the current window.orientation is 0 or 180.
2006                 initial_orientation_is_default = portrait_map[ window.orientation ];
2007
2008                 // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
2009                 // if the initial orientation is portrait, but window.orientation reports 90 or -90, we
2010                 // need to flip our portrait_map values because landscape is the default orientation for
2011                 // this device/browser.
2012                 if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
2013                         portrait_map = { "-90": true, "90": true };
2014                 }
2015         }
2016
2017         $.event.special.orientationchange = special_event = {
2018                 setup: function() {
2019                         // If the event is supported natively, return false so that jQuery
2020                         // will bind to the event using DOM methods.
2021                         if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
2022                                 return false;
2023                         }
2024
2025                         // Get the current orientation to avoid initial double-triggering.
2026                         last_orientation = get_orientation();
2027
2028                         // Because the orientationchange event doesn't exist, simulate the
2029                         // event by testing window dimensions on resize.
2030                         win.bind( "throttledresize", handler );
2031                 },
2032                 teardown: function(){
2033                         // If the event is supported natively, return false so that
2034                         // jQuery will unbind the event using DOM methods.
2035                         if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
2036                                 return false;
2037                         }
2038
2039                         // Because the orientationchange event doesn't exist, unbind the
2040                         // resize event handler.
2041                         win.unbind( "throttledresize", handler );
2042                 },
2043                 add: function( handleObj ) {
2044                         // Save a reference to the bound event handler.
2045                         var old_handler = handleObj.handler;
2046
2047
2048                         handleObj.handler = function( event ) {
2049                                 // Modify event object, adding the .orientation property.
2050                                 event.orientation = get_orientation();
2051
2052                                 // Call the originally-bound event handler and return its result.
2053                                 return old_handler.apply( this, arguments );
2054                         };
2055                 }
2056         };
2057
2058         // If the event is not supported natively, this handler will be bound to
2059         // the window resize event to simulate the orientationchange event.
2060         function handler() {
2061                 // Get the current orientation.
2062                 var orientation = get_orientation();
2063
2064                 if ( orientation !== last_orientation ) {
2065                         // The orientation has changed, so trigger the orientationchange event.
2066                         last_orientation = orientation;
2067                         win.trigger( "orientationchange" );
2068                 }
2069         }
2070
2071         // Get the current page orientation. This method is exposed publicly, should it
2072         // be needed, as jQuery.event.special.orientationchange.orientation()
2073         $.event.special.orientationchange.orientation = get_orientation = function() {
2074                 var isPortrait = true, elem = document.documentElement;
2075
2076                 // prefer window orientation to the calculation based on screensize as
2077                 // the actual screen resize takes place before or after the orientation change event
2078                 // has been fired depending on implementation (eg android 2.3 is before, iphone after).
2079                 // More testing is required to determine if a more reliable method of determining the new screensize
2080                 // is possible when orientationchange is fired. (eg, use media queries + element + opacity)
2081                 if ( $.support.orientation ) {
2082                         // if the window orientation registers as 0 or 180 degrees report
2083                         // portrait, otherwise landscape
2084                         isPortrait = portrait_map[ window.orientation ];
2085                 } else {
2086                         isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
2087                 }
2088
2089                 return isPortrait ? "portrait" : "landscape";
2090         };
2091
2092 })( jQuery, window );
2093
2094
2095 // throttled resize event
2096 (function() {
2097
2098         $.event.special.throttledresize = {
2099                 setup: function() {
2100                         $( this ).bind( "resize", handler );
2101                 },
2102                 teardown: function(){
2103                         $( this ).unbind( "resize", handler );
2104                 }
2105         };
2106
2107         var throttle = 250,
2108                 handler = function() {
2109                         curr = ( new Date() ).getTime();
2110                         diff = curr - lastCall;
2111
2112                         if ( diff >= throttle ) {
2113
2114                                 lastCall = curr;
2115                                 $( this ).trigger( "throttledresize" );
2116
2117                         } else {
2118
2119                                 if ( heldCall ) {
2120                                         clearTimeout( heldCall );
2121                                 }
2122
2123                                 // Promise a held call will still execute
2124                                 heldCall = setTimeout( handler, throttle - diff );
2125                         }
2126                 },
2127                 lastCall = 0,
2128                 heldCall,
2129                 curr,
2130                 diff;
2131 })();
2132
2133
2134 $.each({
2135         scrollstop: "scrollstart",
2136         taphold: "tap",
2137         swipeleft: "swipe",
2138         swiperight: "swipe"
2139 }, function( event, sourceEvent ) {
2140
2141         $.event.special[ event ] = {
2142                 setup: function() {
2143                         $( this ).bind( sourceEvent, $.noop );
2144                 }
2145         };
2146 });
2147
2148 })( jQuery, this );
2149
2150 (function( $, undefined ) {
2151
2152 $.widget( "mobile.page", $.mobile.widget, {
2153         options: {
2154                 theme: "c",
2155                 domCache: false,
2156                 keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
2157         },
2158
2159         _create: function() {
2160                 
2161                 var self = this;
2162                 
2163                 // if false is returned by the callbacks do not create the page
2164                 if( self._trigger( "beforecreate" ) === false ){
2165                         return false;
2166                 }
2167
2168                 self.element
2169                         .attr( "tabindex", "0" )
2170                         .addClass( "ui-page ui-body-" + self.options.theme )
2171                         .bind( "pagebeforehide", function(){
2172                                 self.removeContainerBackground();
2173                         } )
2174                         .bind( "pagebeforeshow", function(){
2175                                 self.setContainerBackground();
2176                         } );
2177
2178         },
2179         
2180         removeContainerBackground: function(){
2181                 $.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
2182         },
2183         
2184         // set the page container background to the page theme
2185         setContainerBackground: function( theme ){
2186                 if( this.options.theme ){
2187                         $.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
2188                 }
2189         },
2190
2191         keepNativeSelector: function() {
2192                 var options = this.options,
2193                         keepNativeDefined = options.keepNative && $.trim(options.keepNative);
2194
2195                 if( keepNativeDefined && options.keepNative !== options.keepNativeDefault ){
2196                         return [options.keepNative, options.keepNativeDefault].join(", ");
2197                 }
2198
2199                 return options.keepNativeDefault;
2200         }
2201 });
2202 })( jQuery );
2203
2204
2205 (function( $, window, undefined ) {
2206
2207 var createHandler = function( sequential ){
2208         
2209         // Default to sequential
2210         if( sequential === undefined ){
2211                 sequential = true;
2212         }
2213         
2214         return function( name, reverse, $to, $from ) {
2215
2216                 var deferred = new $.Deferred(),
2217                         reverseClass = reverse ? " reverse" : "",
2218                         active  = $.mobile.urlHistory.getActive(),
2219                         toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
2220                         screenHeight = $.mobile.getScreenHeight(),
2221                         maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth,
2222                         none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $( window ).scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
2223                         toPreClass = " ui-page-pre-in",
2224                         toggleViewportClass = function(){
2225                                 $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
2226                         },
2227                         scrollPage = function(){
2228                                 // By using scrollTo instead of silentScroll, we can keep things better in order
2229                                 // Just to be precautios, disable scrollstart listening like silentScroll would
2230                                 $.event.special.scrollstart.enabled = false;
2231                                 
2232                                 window.scrollTo( 0, toScroll );
2233                                 
2234                                 // reenable scrollstart listening like silentScroll would
2235                                 setTimeout(function() {
2236                                         $.event.special.scrollstart.enabled = true;
2237                                 }, 150 );
2238                         },
2239                         cleanFrom = function(){
2240                                 $from
2241                                         .removeClass( $.mobile.activePageClass + " out in reverse " + name )
2242                                         .height( "" );
2243                         },
2244                         startOut = function(){
2245                                 // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
2246                                 if( !sequential ){
2247                                         doneOut();
2248                                 }
2249                                 else {
2250                                         $from.animationComplete( doneOut );     
2251                                 }
2252                                 
2253                                 // Set the from page's height and start it transitioning out
2254                                 // Note: setting an explicit height helps eliminate tiling in the transitions
2255                                 $from
2256                                         .height( screenHeight + $(window ).scrollTop() )
2257                                         .addClass( name + " out" + reverseClass );
2258                         },
2259                         
2260                         doneOut = function() {
2261
2262                                 if ( $from && sequential ) {
2263                                         cleanFrom();
2264                                 }
2265                                 
2266                                 startIn();
2267                         },
2268                         
2269                         startIn = function(){   
2270                         
2271                                 $to.addClass( $.mobile.activePageClass );                               
2272                         
2273                                 // Send focus to page as it is now display: block
2274                                 $.mobile.focusPage( $to );
2275
2276                                 // Set to page height
2277                                 $to.height( screenHeight + toScroll );
2278                                 
2279                                 scrollPage();
2280                                 
2281                                 if( !none ){
2282                                         $to.animationComplete( doneIn );
2283                                 }
2284                                 
2285                                 $to.addClass( name + " in" + reverseClass );
2286                                 
2287                                 if( none ){
2288                                         doneIn();
2289                                 }
2290                                 
2291                         },
2292                 
2293                         doneIn = function() {
2294                         
2295                                 if ( !sequential ) {
2296                                         
2297                                         if( $from ){
2298                                                 cleanFrom();
2299                                         }
2300                                 }
2301                         
2302                                 $to
2303                                         .removeClass( "out in reverse " + name )
2304                                         .height( "" );
2305                                 
2306                                 toggleViewportClass();
2307                                 
2308                                 // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
2309                                 // This ensures we jump to that spot after the fact, if we aren't there already.
2310                                 if( $( window ).scrollTop() !== toScroll ){
2311                                         scrollPage();
2312                                 }
2313
2314                                 deferred.resolve( name, reverse, $to, $from, true );
2315                         };
2316
2317                 toggleViewportClass();
2318         
2319                 if ( $from && !none ) {
2320                         startOut();
2321                 }
2322                 else {
2323                         doneOut();
2324                 }
2325
2326                 return deferred.promise();
2327         };
2328 }
2329
2330 // generate the handlers from the above
2331 var sequentialHandler = createHandler(),
2332         simultaneousHandler = createHandler( false ),
2333         defaultGetMaxScrollForTransition = function() {
2334                 return $.mobile.getScreenHeight() * 3;
2335         };
2336
2337 // Make our transition handler the public default.
2338 $.mobile.defaultTransitionHandler = sequentialHandler;
2339
2340 //transition handler dictionary for 3rd party transitions
2341 $.mobile.transitionHandlers = {
2342         "default": $.mobile.defaultTransitionHandler,
2343         "sequential": sequentialHandler,
2344         "simultaneous": simultaneousHandler
2345 };
2346
2347 $.mobile.transitionFallbacks = {};
2348
2349 // Set the getMaxScrollForTransition to default if no implementation was set by user
2350 $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
2351 })( jQuery, this );
2352
2353 ( function( $, undefined ) {
2354
2355         //define vars for interal use
2356         var $window = $( window ),
2357                 $html = $( 'html' ),
2358                 $head = $( 'head' ),
2359
2360                 //url path helpers for use in relative url management
2361                 path = {
2362
2363                         // This scary looking regular expression parses an absolute URL or its relative
2364                         // variants (protocol, site, document, query, and hash), into the various
2365                         // components (protocol, host, path, query, fragment, etc that make up the
2366                         // URL as well as some other commonly used sub-parts. When used with RegExp.exec()
2367                         // or String.match, it parses the URL into a results array that looks like this:
2368                         //
2369                         //     [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content
2370                         //     [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread
2371                         //     [2]: http://jblas:password@mycompany.com:8080/mail/inbox
2372                         //     [3]: http://jblas:password@mycompany.com:8080
2373                         //     [4]: http:
2374                         //     [5]: //
2375                         //     [6]: jblas:password@mycompany.com:8080
2376                         //     [7]: jblas:password
2377                         //     [8]: jblas
2378                         //     [9]: password
2379                         //    [10]: mycompany.com:8080
2380                         //    [11]: mycompany.com
2381                         //    [12]: 8080
2382                         //    [13]: /mail/inbox
2383                         //    [14]: /mail/
2384                         //    [15]: inbox
2385                         //    [16]: ?msg=1234&type=unread
2386                         //    [17]: #msg-content
2387                         //
2388                         urlParseRE: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
2389
2390                         //Parse a URL into a structure that allows easy access to
2391                         //all of the URL components by name.
2392                         parseUrl: function( url ) {
2393                                 // If we're passed an object, we'll assume that it is
2394                                 // a parsed url object and just return it back to the caller.
2395                                 if ( $.type( url ) === "object" ) {
2396                                         return url;
2397                                 }
2398
2399                                 var matches = path.urlParseRE.exec( url || "" ) || [];
2400
2401                                         // Create an object that allows the caller to access the sub-matches
2402                                         // by name. Note that IE returns an empty string instead of undefined,
2403                                         // like all other browsers do, so we normalize everything so its consistent
2404                                         // no matter what browser we're running on.
2405                                         return {
2406                                                 href:         matches[  0 ] || "",
2407                                                 hrefNoHash:   matches[  1 ] || "",
2408                                                 hrefNoSearch: matches[  2 ] || "",
2409                                                 domain:       matches[  3 ] || "",
2410                                                 protocol:     matches[  4 ] || "",
2411                                                 doubleSlash:  matches[  5 ] || "",
2412                                                 authority:    matches[  6 ] || "",
2413                                                 username:     matches[  8 ] || "",
2414                                                 password:     matches[  9 ] || "",
2415                                                 host:         matches[ 10 ] || "",
2416                                                 hostname:     matches[ 11 ] || "",
2417                                                 port:         matches[ 12 ] || "",
2418                                                 pathname:     matches[ 13 ] || "",
2419                                                 directory:    matches[ 14 ] || "",
2420                                                 filename:     matches[ 15 ] || "",
2421                                                 search:       matches[ 16 ] || "",
2422                                                 hash:         matches[ 17 ] || ""
2423                                         };
2424                         },
2425
2426                         //Turn relPath into an asbolute path. absPath is
2427                         //an optional absolute path which describes what
2428                         //relPath is relative to.
2429                         makePathAbsolute: function( relPath, absPath ) {
2430                                 if ( relPath && relPath.charAt( 0 ) === "/" ) {
2431                                         return relPath;
2432                                 }
2433
2434                                 relPath = relPath || "";
2435                                 absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
2436
2437                                 var absStack = absPath ? absPath.split( "/" ) : [],
2438                                         relStack = relPath.split( "/" );
2439                                 for ( var i = 0; i < relStack.length; i++ ) {
2440                                         var d = relStack[ i ];
2441                                         switch ( d ) {
2442                                                 case ".":
2443                                                         break;
2444                                                 case "..":
2445                                                         if ( absStack.length ) {
2446                                                                 absStack.pop();
2447                                                         }
2448                                                         break;
2449                                                 default:
2450                                                         absStack.push( d );
2451                                                         break;
2452                                         }
2453                                 }
2454                                 return "/" + absStack.join( "/" );
2455                         },
2456
2457                         //Returns true if both urls have the same domain.
2458                         isSameDomain: function( absUrl1, absUrl2 ) {
2459                                 return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
2460                         },
2461
2462                         //Returns true for any relative variant.
2463                         isRelativeUrl: function( url ) {
2464                                 // All relative Url variants have one thing in common, no protocol.
2465                                 return path.parseUrl( url ).protocol === "";
2466                         },
2467
2468                         //Returns true for an absolute url.
2469                         isAbsoluteUrl: function( url ) {
2470                                 return path.parseUrl( url ).protocol !== "";
2471                         },
2472
2473                         //Turn the specified realtive URL into an absolute one. This function
2474                         //can handle all relative variants (protocol, site, document, query, fragment).
2475                         makeUrlAbsolute: function( relUrl, absUrl ) {
2476                                 if ( !path.isRelativeUrl( relUrl ) ) {
2477                                         return relUrl;
2478                                 }
2479
2480                                 var relObj = path.parseUrl( relUrl ),
2481                                         absObj = path.parseUrl( absUrl ),
2482                                         protocol = relObj.protocol || absObj.protocol,
2483                                         doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
2484                                         authority = relObj.authority || absObj.authority,
2485                                         hasPath = relObj.pathname !== "",
2486                                         pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
2487                                         search = relObj.search || ( !hasPath && absObj.search ) || "",
2488                                         hash = relObj.hash;
2489
2490                                 return protocol + doubleSlash + authority + pathname + search + hash;
2491                         },
2492
2493                         //Add search (aka query) params to the specified url.
2494                         addSearchParams: function( url, params ) {
2495                                 var u = path.parseUrl( url ),
2496                                         p = ( typeof params === "object" ) ? $.param( params ) : params,
2497                                         s = u.search || "?";
2498                                 return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
2499                         },
2500
2501                         convertUrlToDataUrl: function( absUrl ) {
2502                                 var u = path.parseUrl( absUrl );
2503                                 if ( path.isEmbeddedPage( u ) ) {
2504                                     // For embedded pages, remove the dialog hash key as in getFilePath(),
2505                                     // otherwise the Data Url won't match the id of the embedded Page.
2506                                         return u.hash.split( dialogHashKey )[0].replace( /^#/, "" );
2507                                 } else if ( path.isSameDomain( u, documentBase ) ) {
2508                                         return u.hrefNoHash.replace( documentBase.domain, "" ).split( dialogHashKey )[0];
2509                                 }
2510                                 return absUrl;
2511                         },
2512
2513                         //get path from current hash, or from a file path
2514                         get: function( newPath ) {
2515                                 if( newPath === undefined ) {
2516                                         newPath = location.hash;
2517                                 }
2518                                 return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
2519                         },
2520
2521                         //return the substring of a filepath before the sub-page key, for making a server request
2522                         getFilePath: function( path ) {
2523                                 var splitkey = '&' + $.mobile.subPageUrlKey;
2524                                 return path && path.split( splitkey )[0].split( dialogHashKey )[0];
2525                         },
2526
2527                         //set location hash to path
2528                         set: function( path ) {
2529                                 location.hash = path;
2530                         },
2531
2532                         //test if a given url (string) is a path
2533                         //NOTE might be exceptionally naive
2534                         isPath: function( url ) {
2535                                 return ( /\// ).test( url );
2536                         },
2537
2538                         //return a url path with the window's location protocol/hostname/pathname removed
2539                         clean: function( url ) {
2540                                 return url.replace( documentBase.domain, "" );
2541                         },
2542
2543                         //just return the url without an initial #
2544                         stripHash: function( url ) {
2545                                 return url.replace( /^#/, "" );
2546                         },
2547
2548                         //remove the preceding hash, any query params, and dialog notations
2549                         cleanHash: function( hash ) {
2550                                 return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
2551                         },
2552
2553                         isHashValid: function( hash ) {
2554                                 return /^#[^#]+$/.test(hash);
2555                         },
2556
2557                         //check whether a url is referencing the same domain, or an external domain or different protocol
2558                         //could be mailto, etc
2559                         isExternal: function( url ) {
2560                                 var u = path.parseUrl( url );
2561                                 return u.protocol && u.domain !== documentUrl.domain ? true : false;
2562                         },
2563
2564                         hasProtocol: function( url ) {
2565                                 return ( /^(:?\w+:)/ ).test( url );
2566                         },
2567
2568                         //check if the specified url refers to the first page in the main application document.
2569                         isFirstPageUrl: function( url ) {
2570                                 // We only deal with absolute paths.
2571                                 var u = path.parseUrl( path.makeUrlAbsolute( url, documentBase ) ),
2572
2573                                         // Does the url have the same path as the document?
2574                                         samePath = u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ),
2575
2576                                         // Get the first page element.
2577                                         fp = $.mobile.firstPage,
2578
2579                                         // Get the id of the first page element if it has one.
2580                                         fpId = fp && fp[0] ? fp[0].id : undefined;
2581
2582                                         // The url refers to the first page if the path matches the document and
2583                                         // it either has no hash value, or the hash is exactly equal to the id of the
2584                                         // first page element.
2585                                         return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
2586                         },
2587
2588                         isEmbeddedPage: function( url ) {
2589                                 var u = path.parseUrl( url );
2590
2591                                 //if the path is absolute, then we need to compare the url against
2592                                 //both the documentUrl and the documentBase. The main reason for this
2593                                 //is that links embedded within external documents will refer to the
2594                                 //application document, whereas links embedded within the application
2595                                 //document will be resolved against the document base.
2596                                 if ( u.protocol !== "" ) {
2597                                         return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) );
2598                                 }
2599                                 return (/^#/).test( u.href );
2600                         },
2601
2602
2603                         // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
2604                         // requests if the document doing the request was loaded via the file:// protocol.
2605                         // This is usually to allow the application to "phone home" and fetch app specific
2606                         // data. We normally let the browser handle external/cross-domain urls, but if the
2607                         // allowCrossDomainPages option is true, we will allow cross-domain http/https
2608                         // requests to go through our page loading logic.
2609                         isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
2610                                 return $.mobile.allowCrossDomainPages
2611                                         && docUrl.protocol === "file:"
2612                                         && reqUrl.search( /^https?:/ ) != -1;
2613                         }
2614                 },
2615
2616                 //will be defined when a link is clicked and given an active class
2617                 $activeClickedLink = null,
2618
2619                 //urlHistory is purely here to make guesses at whether the back or forward button was clicked
2620                 //and provide an appropriate transition
2621                 urlHistory = {
2622                         // Array of pages that are visited during a single page load.
2623                         // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs)
2624                         stack: [],
2625
2626                         //maintain an index number for the active page in the stack
2627                         activeIndex: 0,
2628
2629                         //get active
2630                         getActive: function() {
2631                                 return urlHistory.stack[ urlHistory.activeIndex ];
2632                         },
2633
2634                         getPrev: function() {
2635                                 return urlHistory.stack[ urlHistory.activeIndex - 1 ];
2636                         },
2637
2638                         getNext: function() {
2639                                 return urlHistory.stack[ urlHistory.activeIndex + 1 ];
2640                         },
2641
2642                         // addNew is used whenever a new page is added
2643                         addNew: function( url, transition, title, pageUrl, role ) {
2644                                 //if there's forward history, wipe it
2645                                 if( urlHistory.getNext() ) {
2646                                         urlHistory.clearForward();
2647                                 }
2648
2649                                 urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl, role: role } );
2650
2651                                 urlHistory.activeIndex = urlHistory.stack.length - 1;
2652                         },
2653
2654                         //wipe urls ahead of active index
2655                         clearForward: function() {
2656                                 urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
2657                         },
2658
2659                         directHashChange: function( opts ) {
2660                                 var back , forward, newActiveIndex, prev = this.getActive();
2661
2662                                 // check if url is in history and if it's ahead or behind current page
2663                                 $.each( urlHistory.stack, function( i, historyEntry ) {
2664
2665                                         //if the url is in the stack, it's a forward or a back
2666                                         if( opts.currentUrl === historyEntry.url ) {
2667                                                 //define back and forward by whether url is older or newer than current page
2668                                                 back = i < urlHistory.activeIndex;
2669                                                 forward = !back;
2670                                                 newActiveIndex = i;
2671                                         }
2672                                 });
2673
2674                                 // save new page index, null check to prevent falsey 0 result
2675                                 this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex;
2676
2677                                 if( back ) {
2678                                         ( opts.either || opts.isBack )( true );
2679                                 } else if( forward ) {
2680                                         ( opts.either || opts.isForward )( false );
2681                                 }
2682                         },
2683
2684                         //disable hashchange event listener internally to ignore one change
2685                         //toggled internally when location.hash is updated to match the url of a successful page load
2686                         ignoreNextHashChange: false
2687                 },
2688
2689                 //define first selector to receive focus when a page is shown
2690                 focusable = "[tabindex],a,button:visible,select:visible,input",
2691
2692                 //queue to hold simultanious page transitions
2693                 pageTransitionQueue = [],
2694
2695                 //indicates whether or not page is in process of transitioning
2696                 isPageTransitioning = false,
2697
2698                 //nonsense hash change key for dialogs, so they create a history entry
2699                 dialogHashKey = "&ui-state=dialog",
2700
2701                 //existing base tag?
2702                 $base = $head.children( "base" ),
2703
2704                 //tuck away the original document URL minus any fragment.
2705                 documentUrl = path.parseUrl( location.href ),
2706
2707                 //if the document has an embedded base tag, documentBase is set to its
2708                 //initial value. If a base tag does not exist, then we default to the documentUrl.
2709                 documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl,
2710
2711                 //cache the comparison once.
2712                 documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ),
2713
2714                 getScreenHeight = $.mobile.getScreenHeight;
2715
2716                 //base element management, defined depending on dynamic base tag support
2717                 var base = $.support.dynamicBaseTag ? {
2718
2719                         //define base element, for use in routing asset urls that are referenced in Ajax-requested markup
2720                         element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
2721
2722                         //set the generated BASE element's href attribute to a new page's base path
2723                         set: function( href ) {
2724                                 base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
2725                         },
2726
2727                         //set the generated BASE element's href attribute to a new page's base path
2728                         reset: function() {
2729                                 base.element.attr( "href", documentBase.hrefNoHash );
2730                         }
2731
2732                 } : undefined;
2733
2734 /*
2735         internal utility functions
2736 --------------------------------------*/
2737
2738
2739         //direct focus to the page title, or otherwise first focusable element
2740         $.mobile.focusPage = function ( page ) {
2741                 var autofocus = page.find("[autofocus]"),
2742                         pageTitle = page.find( ".ui-title:eq(0)" );
2743
2744                 if( autofocus.length ) {
2745                         autofocus.focus();
2746                         return;
2747                 }
2748
2749                 if( pageTitle.length ) {
2750                         pageTitle.focus();
2751                 }
2752                 else{
2753                         page.focus();
2754                 }
2755         }
2756
2757         //remove active classes after page transition or error
2758         function removeActiveLinkClass( forceRemoval ) {
2759                 if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) {
2760                         $activeClickedLink.removeClass( $.mobile.activeBtnClass );
2761                 }
2762                 $activeClickedLink = null;
2763         }
2764
2765         function releasePageTransitionLock() {
2766                 isPageTransitioning = false;
2767                 if( pageTransitionQueue.length > 0 ) {
2768                         $.mobile.changePage.apply( null, pageTransitionQueue.pop() );
2769                 }
2770         }
2771
2772         // Save the last scroll distance per page, before it is hidden
2773         var setLastScrollEnabled = true,
2774                 setLastScroll, delayedSetLastScroll;
2775
2776         setLastScroll = function() {
2777                 // this barrier prevents setting the scroll value based on the browser
2778                 // scrolling the window based on a hashchange
2779                 if( !setLastScrollEnabled ) {
2780                         return;
2781                 }
2782
2783                 var active = $.mobile.urlHistory.getActive();
2784
2785                 if( active ) {
2786                         var lastScroll = $window.scrollTop();
2787
2788                         // Set active page's lastScroll prop.
2789                         // If the location we're scrolling to is less than minScrollBack, let it go.
2790                         active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
2791                 }
2792         };
2793
2794         // bind to scrollstop to gather scroll position. The delay allows for the hashchange
2795         // event to fire and disable scroll recording in the case where the browser scrolls
2796         // to the hash targets location (sometimes the top of the page). once pagechange fires
2797         // getLastScroll is again permitted to operate
2798         delayedSetLastScroll = function() {
2799                 setTimeout( setLastScroll, 100 );
2800         };
2801
2802         // disable an scroll setting when a hashchange has been fired, this only works
2803         // because the recording of the scroll position is delayed for 100ms after
2804         // the browser might have changed the position because of the hashchange
2805         $window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
2806                 setLastScrollEnabled = false;
2807         });
2808
2809         // handle initial hashchange from chrome :(
2810         $window.one( $.support.pushState ? "popstate" : "hashchange", function() {
2811                 setLastScrollEnabled = true;
2812         });
2813
2814         // wait until the mobile page container has been determined to bind to pagechange
2815         $window.one( "pagecontainercreate", function(){
2816                 // once the page has changed, re-enable the scroll recording
2817                 $.mobile.pageContainer.bind( "pagechange", function() {
2818
2819                         setLastScrollEnabled = true;
2820
2821                         // remove any binding that previously existed on the get scroll
2822                         // which may or may not be different than the scroll element determined for
2823                         // this page previously
2824                         $window.unbind( "scrollstop", delayedSetLastScroll );
2825
2826                         // determine and bind to the current scoll element which may be the window
2827                         // or in the case of touch overflow the element with touch overflow
2828                         $window.bind( "scrollstop", delayedSetLastScroll );
2829                 });
2830         });
2831
2832         // bind to scrollstop for the first page as "pagechange" won't be fired in that case
2833         $window.bind( "scrollstop", delayedSetLastScroll );
2834
2835         //function for transitioning between two existing pages
2836         function transitionPages( toPage, fromPage, transition, reverse ) {
2837
2838                 if( fromPage ) {
2839                         //trigger before show/hide events
2840                         fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } );
2841                 }
2842
2843                 toPage.data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
2844
2845                 //clear page loader
2846                 $.mobile.hidePageLoadingMsg();
2847
2848                 // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
2849                 if( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ){
2850                         transition = $.mobile.transitionFallbacks[ transition ];
2851                 }
2852
2853                 //find the transition handler for the specified transition. If there
2854                 //isn't one in our transitionHandlers dictionary, use the default one.
2855                 //call the handler immediately to kick-off the transition.
2856                 var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
2857                         promise = th( transition, reverse, toPage, fromPage );
2858
2859                 promise.done(function() {
2860
2861                         //trigger show/hide events
2862                         if( fromPage ) {
2863                                 fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } );
2864                         }
2865
2866                         //trigger pageshow, define prevPage as either fromPage or empty jQuery obj
2867                         toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
2868                 });
2869
2870                 return promise;
2871         }
2872
2873         //simply set the active page's minimum height to screen height, depending on orientation
2874         function resetActivePageHeight(){
2875                 var aPage = $( "." + $.mobile.activePageClass ),
2876                         aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
2877                         aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
2878                         aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
2879                         aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
2880
2881                 aPage.css( "min-height", getScreenHeight() - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
2882         }
2883
2884         //shared page enhancements
2885         function enhancePage( $page, role ) {
2886                 // If a role was specified, make sure the data-role attribute
2887                 // on the page element is in sync.
2888                 if( role ) {
2889                         $page.attr( "data-" + $.mobile.ns + "role", role );
2890                 }
2891
2892                 //run page plugin
2893                 $page.page();
2894         }
2895
2896 /* exposed $.mobile methods      */
2897
2898         //animation complete callback
2899         $.fn.animationComplete = function( callback ) {
2900                 if( $.support.cssTransitions ) {
2901                         return $( this ).one( 'webkitAnimationEnd animationend', callback );
2902                 }
2903                 else{
2904                         // defer execution for consistency between webkit/non webkit
2905                         setTimeout( callback, 0 );
2906                         return $( this );
2907                 }
2908         };
2909
2910         //expose path object on $.mobile
2911         $.mobile.path = path;
2912
2913         //expose base object on $.mobile
2914         $.mobile.base = base;
2915
2916         //history stack
2917         $.mobile.urlHistory = urlHistory;
2918
2919         $.mobile.dialogHashKey = dialogHashKey;
2920
2921
2922
2923         //enable cross-domain page support
2924         $.mobile.allowCrossDomainPages = false;
2925
2926         //return the original document url
2927         $.mobile.getDocumentUrl = function(asParsedObject) {
2928                 return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href;
2929         };
2930
2931         //return the original document base url
2932         $.mobile.getDocumentBase = function(asParsedObject) {
2933                 return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href;
2934         };
2935
2936         $.mobile._bindPageRemove = function() {
2937                 var page = $(this);
2938
2939                 // when dom caching is not enabled or the page is embedded bind to remove the page on hide
2940                 if( !page.data("page").options.domCache
2941                                 && page.is(":jqmData(external-page='true')") ) {
2942
2943                         page.bind( 'pagehide.remove', function() {
2944                                 var $this = $( this ),
2945                                         prEvent = new $.Event( "pageremove" );
2946
2947                                 $this.trigger( prEvent );
2948
2949                                 if( !prEvent.isDefaultPrevented() ){
2950                                         $this.removeWithDependents();
2951                                 }
2952                         });
2953                 }
2954         };
2955
2956         // Load a page into the DOM.
2957         $.mobile.loadPage = function( url, options ) {
2958                 // This function uses deferred notifications to let callers
2959                 // know when the page is done loading, or if an error has occurred.
2960                 var deferred = $.Deferred(),
2961
2962                         // The default loadPage options with overrides specified by
2963                         // the caller.
2964                         settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
2965
2966                         // The DOM element for the page after it has been loaded.
2967                         page = null,
2968
2969                         // If the reloadPage option is true, and the page is already
2970                         // in the DOM, dupCachedPage will be set to the page element
2971                         // so that it can be removed after the new version of the
2972                         // page is loaded off the network.
2973                         dupCachedPage = null,
2974
2975                         // determine the current base url
2976                         findBaseWithDefault = function(){
2977                                 var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
2978                                 return closestBase || documentBase.hrefNoHash;
2979                         },
2980
2981                         // The absolute version of the URL passed into the function. This
2982                         // version of the URL may contain dialog/subpage params in it.
2983                         absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
2984
2985
2986                 // If the caller provided data, and we're using "get" request,
2987                 // append the data to the URL.
2988                 if ( settings.data && settings.type === "get" ) {
2989                         absUrl = path.addSearchParams( absUrl, settings.data );
2990                         settings.data = undefined;
2991                 }
2992
2993                 // If the caller is using a "post" request, reloadPage must be true
2994                 if(  settings.data && settings.type === "post" ){
2995                         settings.reloadPage = true;
2996                 }
2997
2998                         // The absolute version of the URL minus any dialog/subpage params.
2999                         // In otherwords the real URL of the page to be loaded.
3000                 var fileUrl = path.getFilePath( absUrl ),
3001
3002                         // The version of the Url actually stored in the data-url attribute of
3003                         // the page. For embedded pages, it is just the id of the page. For pages
3004                         // within the same domain as the document base, it is the site relative
3005                         // path. For cross-domain pages (Phone Gap only) the entire absolute Url
3006                         // used to load the page.
3007                         dataUrl = path.convertUrlToDataUrl( absUrl );
3008
3009                 // Make sure we have a pageContainer to work with.
3010                 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
3011
3012                 // Check to see if the page already exists in the DOM.
3013                 page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
3014
3015                 // If we failed to find the page, check to see if the url is a
3016                 // reference to an embedded page. If so, it may have been dynamically
3017                 // injected by a developer, in which case it would be lacking a data-url
3018                 // attribute and in need of enhancement.
3019                 if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
3020                         page = settings.pageContainer.children( "#" + dataUrl )
3021                                 .attr( "data-" + $.mobile.ns + "url", dataUrl );
3022                 }
3023
3024                 // If we failed to find a page in the DOM, check the URL to see if it
3025                 // refers to the first page in the application. If it isn't a reference
3026                 // to the first page and refers to non-existent embedded page, error out.
3027                 if ( page.length === 0 ) {
3028                         if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
3029                                 // Check to make sure our cached-first-page is actually
3030                                 // in the DOM. Some user deployed apps are pruning the first
3031                                 // page from the DOM for various reasons, we check for this
3032                                 // case here because we don't want a first-page with an id
3033                                 // falling through to the non-existent embedded page error
3034                                 // case. If the first-page is not in the DOM, then we let
3035                                 // things fall through to the ajax loading code below so
3036                                 // that it gets reloaded.
3037                                 if ( $.mobile.firstPage.parent().length ) {
3038                                         page = $( $.mobile.firstPage );
3039                                 }
3040                         } else if ( path.isEmbeddedPage( fileUrl )  ) {
3041                                 deferred.reject( absUrl, options );
3042                                 return deferred.promise();
3043                         }
3044                 }
3045
3046                 // Reset base to the default document base.
3047                 if ( base ) {
3048                         base.reset();
3049                 }
3050
3051                 // If the page we are interested in is already in the DOM,
3052                 // and the caller did not indicate that we should force a
3053                 // reload of the file, we are done. Otherwise, track the
3054                 // existing page as a duplicated.
3055                 if ( page.length ) {
3056                         if ( !settings.reloadPage ) {
3057                                 enhancePage( page, settings.role );
3058                                 deferred.resolve( absUrl, options, page );
3059                                 return deferred.promise();
3060                         }
3061                         dupCachedPage = page;
3062                 }
3063
3064                 var mpc = settings.pageContainer,
3065                         pblEvent = new $.Event( "pagebeforeload" ),
3066                         triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
3067
3068                 // Let listeners know we're about to load a page.
3069                 mpc.trigger( pblEvent, triggerData );
3070
3071                 // If the default behavior is prevented, stop here!
3072                 if( pblEvent.isDefaultPrevented() ){
3073                         return deferred.promise();
3074                 }
3075
3076                 if ( settings.showLoadMsg ) {
3077
3078                         // This configurable timeout allows cached pages a brief delay to load without showing a message
3079                         var loadMsgDelay = setTimeout(function(){
3080                                         $.mobile.showPageLoadingMsg();
3081                                 }, settings.loadMsgDelay ),
3082
3083                                 // Shared logic for clearing timeout and removing message.
3084                                 hideMsg = function(){
3085
3086                                         // Stop message show timer
3087                                         clearTimeout( loadMsgDelay );
3088
3089                                         // Hide loading message
3090                                         $.mobile.hidePageLoadingMsg();
3091                                 };
3092                 }
3093
3094                 if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
3095                         deferred.reject( absUrl, options );
3096                 } else {
3097                         // Load the new page.
3098                         $.ajax({
3099                                 url: fileUrl,
3100                                 type: settings.type,
3101                                 data: settings.data,
3102                                 dataType: "html",
3103                                 success: function( html, textStatus, xhr ) {
3104                                         //pre-parse html to check for a data-url,
3105                                         //use it as the new fileUrl, base path, etc
3106                                         var all = $( "<div></div>" ),
3107
3108                                                 //page title regexp
3109                                                 newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
3110
3111                                                 // TODO handle dialogs again
3112                                                 pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
3113                                                 dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
3114
3115
3116                                         // data-url must be provided for the base tag so resource requests can be directed to the
3117                                         // correct url. loading into a temprorary element makes these requests immediately
3118                                         if( pageElemRegex.test( html )
3119                                                         && RegExp.$1
3120                                                         && dataUrlRegex.test( RegExp.$1 )
3121                                                         && RegExp.$1 ) {
3122                                                 url = fileUrl = path.getFilePath( RegExp.$1 );
3123                                         }
3124
3125                                         if ( base ) {
3126                                                 base.set( fileUrl );
3127                                         }
3128
3129                                         //workaround to allow scripts to execute when included in page divs
3130                                         all.get( 0 ).innerHTML = html;
3131                                         page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
3132
3133                                         //if page elem couldn't be found, create one and insert the body element's contents
3134                                         if( !page.length ){
3135                                                 page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" );
3136                                         }
3137
3138                                         if ( newPageTitle && !page.jqmData( "title" ) ) {
3139                                                 if ( ~newPageTitle.indexOf( "&" ) ) {
3140                                                         newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
3141                                                 }
3142                                                 page.jqmData( "title", newPageTitle );
3143                                         }
3144
3145                                         //rewrite src and href attrs to use a base url
3146                                         if( !$.support.dynamicBaseTag ) {
3147                                                 var newPath = path.get( fileUrl );
3148                                                 page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
3149                                                         var thisAttr = $( this ).is( '[href]' ) ? 'href' :
3150                                                                         $(this).is('[src]') ? 'src' : 'action',
3151                                                                 thisUrl = $( this ).attr( thisAttr );
3152
3153                                                         // XXX_jblas: We need to fix this so that it removes the document
3154                                                         //            base URL, and then prepends with the new page URL.
3155                                                         //if full path exists and is same, chop it - helps IE out
3156                                                         thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
3157
3158                                                         if( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
3159                                                                 $( this ).attr( thisAttr, newPath + thisUrl );
3160                                                         }
3161                                                 });
3162                                         }
3163
3164                                         //append to page and enhance
3165                                         // TODO taging a page with external to make sure that embedded pages aren't removed
3166                                         //      by the various page handling code is bad. Having page handling code in many
3167                                         //      places is bad. Solutions post 1.0
3168                                         page
3169                                                 .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
3170                                                 .attr( "data-" + $.mobile.ns + "external-page", true )
3171                                                 .appendTo( settings.pageContainer );
3172
3173                                         // wait for page creation to leverage options defined on widget
3174                                         page.one( 'pagecreate', $.mobile._bindPageRemove );
3175
3176                                         enhancePage( page, settings.role );
3177
3178                                         // Enhancing the page may result in new dialogs/sub pages being inserted
3179                                         // into the DOM. If the original absUrl refers to a sub-page, that is the
3180                                         // real page we are interested in.
3181                                         if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
3182                                                 page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
3183                                         }
3184
3185                                         //bind pageHide to removePage after it's hidden, if the page options specify to do so
3186
3187                                         // Remove loading message.
3188                                         if ( settings.showLoadMsg ) {
3189                                                 hideMsg();
3190                                         }
3191
3192                                         // Add the page reference and xhr to our triggerData.
3193                                         triggerData.xhr = xhr;
3194                                         triggerData.textStatus = textStatus;
3195                                         triggerData.page = page;
3196
3197                                         // Let listeners know the page loaded successfully.
3198                                         settings.pageContainer.trigger( "pageload", triggerData );
3199
3200                                         deferred.resolve( absUrl, options, page, dupCachedPage );
3201                                 },
3202                                 error: function( xhr, textStatus, errorThrown ) {
3203                                         //set base back to current path
3204                                         if( base ) {
3205                                                 base.set( path.get() );
3206                                         }
3207
3208                                         // Add error info to our triggerData.
3209                                         triggerData.xhr = xhr;
3210                                         triggerData.textStatus = textStatus;
3211                                         triggerData.errorThrown = errorThrown;
3212
3213                                         var plfEvent = new $.Event( "pageloadfailed" );
3214
3215                                         // Let listeners know the page load failed.
3216                                         settings.pageContainer.trigger( plfEvent, triggerData );
3217
3218                                         // If the default behavior is prevented, stop here!
3219                                         // Note that it is the responsibility of the listener/handler
3220                                         // that called preventDefault(), to resolve/reject the
3221                                         // deferred object within the triggerData.
3222                                         if( plfEvent.isDefaultPrevented() ){
3223                                                 return;
3224                                         }
3225
3226                                         // Remove loading message.
3227                                         if ( settings.showLoadMsg ) {
3228
3229                                                 // Remove loading message.
3230                                                 hideMsg();
3231
3232                                                 // show error message
3233                                                 $.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
3234
3235                                                 // hide after delay
3236                                                 setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
3237                                         }
3238
3239                                         deferred.reject( absUrl, options );
3240                                 }
3241                         });
3242                 }
3243
3244                 return deferred.promise();
3245         };
3246
3247         $.mobile.loadPage.defaults = {
3248                 type: "get",
3249                 data: undefined,
3250                 reloadPage: false,
3251                 role: undefined, // By default we rely on the role defined by the @data-role attribute.
3252                 showLoadMsg: false,
3253                 pageContainer: undefined,
3254                 loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
3255         };
3256
3257         // Show a specific page in the page container.
3258         $.mobile.changePage = function( toPage, options ) {
3259                 // If we are in the midst of a transition, queue the current request.
3260                 // We'll call changePage() once we're done with the current transition to
3261                 // service the request.
3262                 if( isPageTransitioning ) {
3263                         pageTransitionQueue.unshift( arguments );
3264                         return;
3265                 }
3266
3267                 var settings = $.extend( {}, $.mobile.changePage.defaults, options );
3268
3269                 // Make sure we have a pageContainer to work with.
3270                 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
3271
3272                 // Make sure we have a fromPage.
3273                 settings.fromPage = settings.fromPage || $.mobile.activePage;
3274
3275                 var mpc = settings.pageContainer,
3276                         pbcEvent = new $.Event( "pagebeforechange" ),
3277                         triggerData = { toPage: toPage, options: settings };
3278
3279                 // Let listeners know we're about to change the current page.
3280                 mpc.trigger( pbcEvent, triggerData );
3281
3282                 // If the default behavior is prevented, stop here!
3283                 if( pbcEvent.isDefaultPrevented() ){
3284                         return;
3285                 }
3286
3287                 // We allow "pagebeforechange" observers to modify the toPage in the trigger
3288                 // data to allow for redirects. Make sure our toPage is updated.
3289
3290                 toPage = triggerData.toPage;
3291
3292                 // Set the isPageTransitioning flag to prevent any requests from
3293                 // entering this method while we are in the midst of loading a page
3294                 // or transitioning.
3295
3296                 isPageTransitioning = true;
3297
3298                 // If the caller passed us a url, call loadPage()
3299                 // to make sure it is loaded into the DOM. We'll listen
3300                 // to the promise object it returns so we know when
3301                 // it is done loading or if an error ocurred.
3302                 if ( typeof toPage == "string" ) {
3303                         $.mobile.loadPage( toPage, settings )
3304                                 .done(function( url, options, newPage, dupCachedPage ) {
3305                                         isPageTransitioning = false;
3306                                         options.duplicateCachedPage = dupCachedPage;
3307                                         $.mobile.changePage( newPage, options );
3308                                 })
3309                                 .fail(function( url, options ) {
3310                                         isPageTransitioning = false;
3311
3312                                         //clear out the active button state
3313                                         removeActiveLinkClass( true );
3314
3315                                         //release transition lock so navigation is free again
3316                                         releasePageTransitionLock();
3317                                         settings.pageContainer.trigger( "pagechangefailed", triggerData );
3318                                 });
3319                         return;
3320                 }
3321
3322                 // If we are going to the first-page of the application, we need to make
3323                 // sure settings.dataUrl is set to the application document url. This allows
3324                 // us to avoid generating a document url with an id hash in the case where the
3325                 // first-page of the document has an id attribute specified.
3326                 if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
3327                         settings.dataUrl = documentUrl.hrefNoHash;
3328                 }
3329
3330                 // The caller passed us a real page DOM element. Update our
3331                 // internal state and then trigger a transition to the page.
3332                 var fromPage = settings.fromPage,
3333                         url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
3334                         // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
3335                         pageUrl = url,
3336                         fileUrl = path.getFilePath( url ),
3337                         active = urlHistory.getActive(),
3338                         activeIsInitialPage = urlHistory.activeIndex === 0,
3339                         historyDir = 0,
3340                         pageTitle = document.title,
3341                         isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
3342
3343                 // By default, we prevent changePage requests when the fromPage and toPage
3344                 // are the same element, but folks that generate content manually/dynamically
3345                 // and reuse pages want to be able to transition to the same page. To allow
3346                 // this, they will need to change the default value of allowSamePageTransition
3347                 // to true, *OR*, pass it in as an option when they manually call changePage().
3348                 // It should be noted that our default transition animations assume that the
3349                 // formPage and toPage are different elements, so they may behave unexpectedly.
3350                 // It is up to the developer that turns on the allowSamePageTransitiona option
3351                 // to either turn off transition animations, or make sure that an appropriate
3352                 // animation transition is used.
3353                 if( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
3354                         isPageTransitioning = false;
3355                         mpc.trigger( "pagechange", triggerData );
3356
3357                         // Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
3358                         if( settings.fromHashChange ) {
3359                                 urlHistory.directHashChange({
3360                                         currentUrl:     url,
3361                                         isBack:         function() {},
3362                                         isForward:      function() {}
3363                                 });
3364                         }
3365
3366                         return;
3367                 }
3368
3369                 // We need to make sure the page we are given has already been enhanced.
3370                 enhancePage( toPage, settings.role );
3371
3372                 // If the changePage request was sent from a hashChange event, check to see if the
3373                 // page is already within the urlHistory stack. If so, we'll assume the user hit
3374                 // the forward/back button and will try to match the transition accordingly.
3375                 if( settings.fromHashChange ) {
3376                         urlHistory.directHashChange({
3377                                 currentUrl:     url,
3378                                 isBack:         function() { historyDir = -1; },
3379                                 isForward:      function() { historyDir = 1; }
3380                         });
3381                 }
3382
3383                 // Kill the keyboard.
3384                 // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
3385                 //            we should be tracking focus with a delegate() handler so we already have
3386                 //            the element in hand at this point.
3387                 // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
3388                 // is undefined when we are in an IFrame.
3389                 try {
3390                         if(document.activeElement && document.activeElement.nodeName.toLowerCase() != 'body') {
3391                                 $(document.activeElement).blur();
3392                         } else {
3393                                 $( "input:focus, textarea:focus, select:focus" ).blur();
3394                         }
3395                 } catch(e) {}
3396
3397                 // Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
3398                 var alreadyThere = false;
3399
3400                 // If we're displaying the page as a dialog, we don't want the url
3401                 // for the dialog content to be used in the hash. Instead, we want
3402                 // to append the dialogHashKey to the url of the current page.
3403                 if ( isDialog && active ) {
3404                         // on the initial page load active.url is undefined and in that case should
3405                         // be an empty string. Moving the undefined -> empty string back into
3406                         // urlHistory.addNew seemed imprudent given undefined better represents
3407                         // the url state
3408
3409                         // If we are at a place in history that once belonged to a dialog, reuse
3410                         // this state without adding to urlHistory and without modifying the hash.
3411                         // However, if a dialog is already displayed at this point, and we're
3412                         // about to display another dialog, then we must add another hash and
3413                         // history entry on top so that one may navigate back to the original dialog
3414                         if ( active.url.indexOf( dialogHashKey ) > -1 && !$.mobile.activePage.is( ".ui-dialog" ) ) {
3415                                 settings.changeHash = false;
3416                                 alreadyThere = true;
3417                         }
3418
3419                         url = ( active.url || "" ) + dialogHashKey;
3420
3421                         // tack on another dialogHashKey if this is the same as the initial hash
3422                         // this makes sure that a history entry is created for this dialog
3423                         if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
3424                                 url += dialogHashKey;
3425                         }
3426                 }
3427
3428                 // Set the location hash.
3429                 if( settings.changeHash !== false && url ) {
3430                         //disable hash listening temporarily
3431                         urlHistory.ignoreNextHashChange = true;
3432                         //update hash and history
3433                         path.set( url );
3434                 }
3435
3436                 // if title element wasn't found, try the page div data attr too
3437                 // If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
3438                 var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).getEncodedText();
3439                 if( !!newPageTitle && pageTitle == document.title ) {
3440                         pageTitle = newPageTitle;
3441                 }
3442                 if ( !toPage.jqmData( "title" ) ) {
3443                         toPage.jqmData( "title", pageTitle );
3444                 }
3445
3446                 // Make sure we have a transition defined.
3447                 settings.transition = settings.transition
3448                         || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined )
3449                         || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
3450
3451                 //add page to history stack if it's not back or forward
3452                 if( !historyDir && !alreadyThere ) {
3453                         urlHistory.addNew( url, settings.transition, pageTitle, pageUrl, settings.role );
3454                 }
3455
3456                 //set page title
3457                 document.title = urlHistory.getActive().title;
3458
3459                 //set "toPage" as activePage
3460                 $.mobile.activePage = toPage;
3461
3462                 // If we're navigating back in the URL history, set reverse accordingly.
3463                 settings.reverse = settings.reverse || historyDir < 0;
3464
3465                 transitionPages( toPage, fromPage, settings.transition, settings.reverse )
3466                         .done(function( name, reverse, $to, $from, alreadyFocused ) {
3467                                 removeActiveLinkClass();
3468
3469                                 //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
3470                                 if ( settings.duplicateCachedPage ) {
3471                                         settings.duplicateCachedPage.remove();
3472                                 }
3473
3474                                 // Send focus to the newly shown page. Moved from promise .done binding in transitionPages
3475                                 // itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
3476                                 // despite visibility: hidden addresses issue #2965
3477                                 // https://github.com/jquery/jquery-mobile/issues/2965
3478                                 if( !alreadyFocused ){
3479                                         $.mobile.focusPage( toPage );
3480                                 }
3481
3482                                 releasePageTransitionLock();
3483
3484                                 // Let listeners know we're all done changing the current page.
3485                                 mpc.trigger( "pagechange", triggerData );
3486                         });
3487         };
3488
3489         $.mobile.changePage.defaults = {
3490                 transition: undefined,
3491                 reverse: false,
3492                 changeHash: true,
3493                 fromHashChange: false,
3494                 role: undefined, // By default we rely on the role defined by the @data-role attribute.
3495                 duplicateCachedPage: undefined,
3496                 pageContainer: undefined,
3497                 showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
3498                 dataUrl: undefined,
3499                 fromPage: undefined,
3500                 allowSamePageTransition: false
3501         };
3502
3503 /* Event Bindings - hashchange, submit, and click */
3504         function findClosestLink( ele )
3505         {
3506                 while ( ele ) {
3507                         // Look for the closest element with a nodeName of "a".
3508                         // Note that we are checking if we have a valid nodeName
3509                         // before attempting to access it. This is because the
3510                         // node we get called with could have originated from within
3511                         // an embedded SVG document where some symbol instance elements
3512                         // don't have nodeName defined on them, or strings are of type
3513                         // SVGAnimatedString.
3514                         if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() == "a" ) {
3515                                 break;
3516                         }
3517                         ele = ele.parentNode;
3518                 }
3519                 return ele;
3520         }
3521
3522         // The base URL for any given element depends on the page it resides in.
3523         function getClosestBaseUrl( ele )
3524         {
3525                 // Find the closest page and extract out its url.
3526                 var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
3527                         base = documentBase.hrefNoHash;
3528
3529                 if ( !url || !path.isPath( url ) ) {
3530                         url = base;
3531                 }
3532
3533                 return path.makeUrlAbsolute( url, base);
3534         }
3535
3536         //The following event bindings should be bound after mobileinit has been triggered
3537         //the following deferred is resolved in the init file
3538         $.mobile.navreadyDeferred = $.Deferred();
3539         $.mobile.navreadyDeferred.done( function(){
3540                 //bind to form submit events, handle with Ajax
3541                 $( document ).delegate( "form", "submit", function( event ) {
3542                         var $this = $( this );
3543
3544                         if( !$.mobile.ajaxEnabled ||
3545                                         // test that the form is, itself, ajax false
3546                                         $this.is(":jqmData(ajax='false')") ||
3547                                         // test that $.mobile.ignoreContentEnabled is set and
3548                                         // the form or one of it's parents is ajax=false
3549                                         !$this.jqmHijackable().length ) {
3550                                 return;
3551                         }
3552
3553                         var type = $this.attr( "method" ),
3554                                 target = $this.attr( "target" ),
3555                                 url = $this.attr( "action" );
3556
3557                         // If no action is specified, browsers default to using the
3558                         // URL of the document containing the form. Since we dynamically
3559                         // pull in pages from external documents, the form should submit
3560                         // to the URL for the source document of the page containing
3561                         // the form.
3562                         if ( !url ) {
3563                                 // Get the @data-url for the page containing the form.
3564                                 url = getClosestBaseUrl( $this );
3565                                 if ( url === documentBase.hrefNoHash ) {
3566                                         // The url we got back matches the document base,
3567                                         // which means the page must be an internal/embedded page,
3568                                         // so default to using the actual document url as a browser
3569                                         // would.
3570                                         url = documentUrl.hrefNoSearch;
3571                                 }
3572                         }
3573
3574                         url = path.makeUrlAbsolute(  url, getClosestBaseUrl($this) );
3575
3576                         if(( path.isExternal( url ) && !path.isPermittedCrossDomainRequest(documentUrl, url)) || target ) {
3577                                 return;
3578                         }
3579
3580                         $.mobile.changePage(
3581                                 url,
3582                                 {
3583                                         type:           type && type.length && type.toLowerCase() || "get",
3584                                         data:           $this.serialize(),
3585                                         transition:     $this.jqmData( "transition" ),
3586                                         direction:      $this.jqmData( "direction" ),
3587                                         reloadPage:     true
3588                                 }
3589                         );
3590                         event.preventDefault();
3591                 });
3592
3593                 //add active state on vclick
3594                 $( document ).bind( "vclick", function( event ) {
3595                         // if this isn't a left click we don't care. Its important to note
3596                         // that when the virtual event is generated it will create the which attr
3597                         if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
3598                                 return;
3599                         }
3600
3601                         var link = findClosestLink( event.target );
3602
3603                         // split from the previous return logic to avoid find closest where possible
3604                         // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
3605                         // can be avoided
3606                         if ( !$(link).jqmHijackable().length ) {
3607                                 return;
3608                         }
3609
3610                         if ( link ) {
3611                                 if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) {
3612                                         removeActiveLinkClass( true );
3613                                         $activeClickedLink = $( link ).closest( ".ui-btn" ).not( ".ui-disabled" );
3614                                         $activeClickedLink.addClass( $.mobile.activeBtnClass );
3615                                 }
3616                         }
3617                 });
3618
3619                 // click routing - direct to HTTP or Ajax, accordingly
3620                 $( document ).bind( "click", function( event ) {
3621                         if( !$.mobile.linkBindingEnabled ){
3622                                 return;
3623                         }
3624
3625                         var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
3626
3627                         // If there is no link associated with the click or its not a left
3628                         // click we want to ignore the click
3629                         // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
3630                         // can be avoided
3631                         if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
3632                                 return;
3633                         }
3634
3635                         //remove active link class if external (then it won't be there if you come back)
3636                         httpCleanup = function(){
3637                                 window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 );
3638                         };
3639
3640                         //if there's a data-rel=back attr, go back in history
3641                         if( $link.is( ":jqmData(rel='back')" ) ) {
3642                                 window.history.back();
3643                                 return false;
3644                         }
3645
3646                         var baseUrl = getClosestBaseUrl( $link ),
3647
3648                                 //get href, if defined, otherwise default to empty hash
3649                                 href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
3650
3651                         //if ajax is disabled, exit early
3652                         if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){
3653                                 httpCleanup();
3654                                 //use default click handling
3655                                 return;
3656                         }
3657
3658                         // XXX_jblas: Ideally links to application pages should be specified as
3659                         //            an url to the application document with a hash that is either
3660                         //            the site relative path or id to the page. But some of the
3661                         //            internal code that dynamically generates sub-pages for nested
3662                         //            lists and select dialogs, just write a hash in the link they
3663                         //            create. This means the actual URL path is based on whatever
3664                         //            the current value of the base tag is at the time this code
3665                         //            is called. For now we are just assuming that any url with a
3666                         //            hash in it is an application page reference.
3667                         if ( href.search( "#" ) != -1 ) {
3668                                 href = href.replace( /[^#]*#/, "" );
3669                                 if ( !href ) {
3670                                         //link was an empty hash meant purely
3671                                         //for interaction, so we ignore it.
3672                                         event.preventDefault();
3673                                         return;
3674                                 } else if ( path.isPath( href ) ) {
3675                                         //we have apath so make it the href we want to load.
3676                                         href = path.makeUrlAbsolute( href, baseUrl );
3677                                 } else {
3678                                         //we have a simple id so use the documentUrl as its base.
3679                                         href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
3680                                 }
3681                         }
3682
3683                                 // Should we handle this link, or let the browser deal with it?
3684                         var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
3685
3686                                 // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
3687                                 // requests if the document doing the request was loaded via the file:// protocol.
3688                                 // This is usually to allow the application to "phone home" and fetch app specific
3689                                 // data. We normally let the browser handle external/cross-domain urls, but if the
3690                                 // allowCrossDomainPages option is true, we will allow cross-domain http/https
3691                                 // requests to go through our page loading logic.
3692
3693                                 //check for protocol or rel and its not an embedded page
3694                                 //TODO overlap in logic from isExternal, rel=external check should be
3695                                 //     moved into more comprehensive isExternalLink
3696                                 isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest(documentUrl, href) );
3697
3698                         if( isExternal ) {
3699                                 httpCleanup();
3700                                 //use default click handling
3701                                 return;
3702                         }
3703
3704                         //use ajax
3705                         var transition = $link.jqmData( "transition" ),
3706                                 direction = $link.jqmData( "direction" ),
3707                                 reverse = ( direction && direction === "reverse" ) ||
3708                                                         // deprecated - remove by 1.0
3709                                                         $link.jqmData( "back" ),
3710
3711                                 //this may need to be more specific as we use data-rel more
3712                                 role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
3713
3714                         $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } );
3715                         event.preventDefault();
3716                 });
3717
3718                 //prefetch pages when anchors with data-prefetch are encountered
3719                 $( document ).delegate( ".ui-page", "pageshow.prefetch", function() {
3720                         var urls = [];
3721                         $( this ).find( "a:jqmData(prefetch)" ).each(function(){
3722                                 var $link = $(this),
3723                                         url = $link.attr( "href" );
3724
3725                                 if ( url && $.inArray( url, urls ) === -1 ) {
3726                                         urls.push( url );
3727
3728                                         $.mobile.loadPage( url, {role: $link.attr("data-" + $.mobile.ns + "rel")} );
3729                                 }
3730                         });
3731                 });
3732
3733                 $.mobile._handleHashChange = function( hash ) {
3734                         //find first page via hash
3735                         var to = path.stripHash( hash ),
3736                                 //transition is false if it's the first page, undefined otherwise (and may be overridden by default)
3737                                 transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
3738
3739                                 // default options for the changPage calls made after examining the current state
3740                                 // of the page and the hash
3741                                 changePageOptions = {
3742                                         transition: transition,
3743                                         changeHash: false,
3744                                         fromHashChange: true
3745                                 };
3746
3747                         if ( 0 === urlHistory.stack.length ) {
3748                                 urlHistory.initialDst = to;
3749                         }
3750
3751                         //if listening is disabled (either globally or temporarily), or it's a dialog hash
3752                         if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) {
3753                                 urlHistory.ignoreNextHashChange = false;
3754                                 return;
3755                         }
3756
3757                         // special case for dialogs
3758                         if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
3759
3760                                 // If current active page is not a dialog skip the dialog and continue
3761                                 // in the same direction
3762                                 if(!$.mobile.activePage.is( ".ui-dialog" )) {
3763                                         //determine if we're heading forward or backward and continue accordingly past
3764                                         //the current dialog
3765                                         urlHistory.directHashChange({
3766                                                 currentUrl: to,
3767                                                 isBack: function() { window.history.back(); },
3768                                                 isForward: function() { window.history.forward(); }
3769                                         });
3770
3771                                         // prevent changePage()
3772                                         return;
3773                                 } else {
3774                                         // if the current active page is a dialog and we're navigating
3775                                         // to a dialog use the dialog objected saved in the stack
3776                                         urlHistory.directHashChange({
3777                                                 currentUrl: to,
3778
3779                                                 // regardless of the direction of the history change
3780                                                 // do the following
3781                                                 either: function( isBack ) {
3782                                                         var active = $.mobile.urlHistory.getActive();
3783
3784                                                         to = active.pageUrl;
3785
3786                                                         // make sure to set the role, transition and reversal
3787                                                         // as most of this is lost by the domCache cleaning
3788                                                         $.extend( changePageOptions, {
3789                                                                 role: active.role,
3790                                                                 transition:      active.transition,
3791                                                                 reverse: isBack
3792                                                         });
3793                                                 }
3794                                         });
3795                                 }
3796                         }
3797
3798                         //if to is defined, load it
3799                         if ( to ) {
3800                                 // At this point, 'to' can be one of 3 things, a cached page element from
3801                                 // a history stack entry, an id, or site-relative/absolute URL. If 'to' is
3802                                 // an id, we need to resolve it against the documentBase, not the location.href,
3803                                 // since the hashchange could've been the result of a forward/backward navigation
3804                                 // that crosses from an external page/dialog to an internal page/dialog.
3805                                 to = ( typeof to === "string" && !path.isPath( to ) ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
3806                                 $.mobile.changePage( to, changePageOptions );
3807                         }       else {
3808                                 //there's no hash, go to the first page in the dom
3809                                 $.mobile.changePage( $.mobile.firstPage, changePageOptions );
3810                         }
3811                 };
3812
3813                 //hashchange event handler
3814                 $window.bind( "hashchange", function( e, triggered ) {
3815                         $.mobile._handleHashChange( location.hash );
3816                 });
3817
3818                 //set page min-heights to be device specific
3819                 $( document ).bind( "pageshow", resetActivePageHeight );
3820                 $( window ).bind( "throttledresize", resetActivePageHeight );
3821
3822         });//navreadyDeferred done callback
3823
3824 })( jQuery );
3825
3826 ( function( $, window ) {
3827         // For now, let's Monkeypatch this onto the end of $.mobile._registerInternalEvents
3828         // Scope self to pushStateHandler so we can reference it sanely within the
3829         // methods handed off as event handlers
3830         var     pushStateHandler = {},
3831                 self = pushStateHandler,
3832                 $win = $( window ),
3833                 url = $.mobile.path.parseUrl( location.href ),
3834                 mobileinitDeferred = $.Deferred(),
3835                 domreadyDeferred = $.Deferred();
3836
3837         $( document ).ready( $.proxy( domreadyDeferred, "resolve" ) );
3838
3839         $( document ).one( "mobileinit", $.proxy( mobileinitDeferred, "resolve" ) );
3840
3841         $.extend( pushStateHandler, {
3842                 // TODO move to a path helper, this is rather common functionality
3843                 initialFilePath: (function() {
3844                         return url.pathname + url.search;
3845                 })(),
3846
3847                 hashChangeTimeout: 200,
3848
3849                 hashChangeEnableTimer: undefined,
3850
3851                 initialHref: url.hrefNoHash,
3852
3853                 state: function() {
3854                         return {
3855                                 hash: location.hash || "#" + self.initialFilePath,
3856                                 title: document.title,
3857
3858                                 // persist across refresh
3859                                 initialHref: self.initialHref
3860                         };
3861                 },
3862
3863                 resetUIKeys: function( url ) {
3864                         var dialog = $.mobile.dialogHashKey,
3865                                 subkey = "&" + $.mobile.subPageUrlKey,
3866                                 dialogIndex = url.indexOf( dialog );
3867
3868                         if( dialogIndex > -1 ) {
3869                                 url = url.slice( 0, dialogIndex ) + "#" + url.slice( dialogIndex );
3870                         } else if( url.indexOf( subkey ) > -1 ) {
3871                                 url = url.split( subkey ).join( "#" + subkey );
3872                         }
3873
3874                         return url;
3875                 },
3876
3877                 // TODO sort out a single barrier to hashchange functionality
3878                 nextHashChangePrevented: function( value ) {
3879                         $.mobile.urlHistory.ignoreNextHashChange = value;
3880                         self.onHashChangeDisabled = value;
3881                 },
3882
3883                 // on hash change we want to clean up the url
3884                 // NOTE this takes place *after* the vanilla navigation hash change
3885                 // handling has taken place and set the state of the DOM
3886                 onHashChange: function( e ) {
3887                         // disable this hash change
3888                         if( self.onHashChangeDisabled ){
3889                                 return;
3890                         }
3891
3892                         var href, state,
3893                                 hash = location.hash,
3894                                 isPath = $.mobile.path.isPath( hash ),
3895                                 resolutionUrl = isPath ? location.href : $.mobile.getDocumentUrl();
3896
3897                         hash = isPath ? hash.replace( "#", "" ) : hash;
3898
3899
3900                         // propulate the hash when its not available
3901                         state = self.state();
3902
3903                         // make the hash abolute with the current href
3904                         href = $.mobile.path.makeUrlAbsolute( hash, resolutionUrl );
3905
3906                         if ( isPath ) {
3907                                 href = self.resetUIKeys( href );
3908                         }
3909
3910                         // replace the current url with the new href and store the state
3911                         // Note that in some cases we might be replacing an url with the
3912                         // same url. We do this anyways because we need to make sure that
3913                         // all of our history entries have a state object associated with
3914                         // them. This allows us to work around the case where window.history.back()
3915                         // is called to transition from an external page to an embedded page.
3916                         // In that particular case, a hashchange event is *NOT* generated by the browser.
3917                         // Ensuring each history entry has a state object means that onPopState()
3918                         // will always trigger our hashchange callback even when a hashchange event
3919                         // is not fired.
3920                         history.replaceState( state, document.title, href );
3921                 },
3922
3923                 // on popstate (ie back or forward) we need to replace the hash that was there previously
3924                 // cleaned up by the additional hash handling
3925                 onPopState: function( e ) {
3926                         var poppedState = e.originalEvent.state,
3927                                 fromHash, toHash, hashChanged;
3928
3929                         // if there's no state its not a popstate we care about, eg chrome's initial popstate
3930                         if( poppedState ) {
3931                                 // if we get two pop states in under this.hashChangeTimeout
3932                                 // make sure to clear any timer set for the previous change
3933                                 clearTimeout( self.hashChangeEnableTimer );
3934
3935                                 // make sure to enable hash handling for the the _handleHashChange call
3936                                 self.nextHashChangePrevented( false );
3937
3938                                 // change the page based on the hash in the popped state
3939                                 $.mobile._handleHashChange( poppedState.hash );
3940
3941                                 // prevent any hashchange in the next self.hashChangeTimeout
3942                                 self.nextHashChangePrevented( true );
3943
3944                                 // re-enable hash change handling after swallowing a possible hash
3945                                 // change event that comes on all popstates courtesy of browsers like Android
3946                                 self.hashChangeEnableTimer = setTimeout( function() {
3947                                         self.nextHashChangePrevented( false );
3948                                 }, self.hashChangeTimeout);
3949                         }
3950                 },
3951
3952                 init: function() {
3953                         $win.bind( "hashchange", self.onHashChange );
3954
3955                         // Handle popstate events the occur through history changes
3956                         $win.bind( "popstate", self.onPopState );
3957
3958                         // if there's no hash, we need to replacestate for returning to home
3959                         if ( location.hash === "" ) {
3960                                 history.replaceState( self.state(), document.title, location.href );
3961                         }
3962                 }
3963         });
3964
3965         // We need to init when "mobileinit", "domready", and "navready" have all happened
3966         $.when( domreadyDeferred, mobileinitDeferred, $.mobile.navreadyDeferred ).done( function() {
3967                 if( $.mobile.pushStateEnabled && $.support.pushState ){
3968                         pushStateHandler.init();
3969                 }
3970         });
3971 })( jQuery, this );
3972
3973 /*
3974 * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
3975 */
3976
3977 (function( $, window, undefined ) {
3978
3979 $.mobile.transitionFallbacks.pop = "fade";
3980
3981 })( jQuery, this );
3982
3983 /*
3984 * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
3985 */
3986
3987 (function( $, window, undefined ) {
3988
3989 // Use the simultaneous transition handler for slide transitions
3990 $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
3991
3992 // Set the slide transition's fallback to "fade"
3993 $.mobile.transitionFallbacks.slide = "fade";
3994
3995 })( jQuery, this );
3996
3997 /*
3998 * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
3999 */
4000
4001 (function( $, window, undefined ) {
4002
4003 $.mobile.transitionFallbacks.slidedown = "fade";
4004
4005 })( jQuery, this );
4006
4007 /*
4008 * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4009 */
4010
4011 (function( $, window, undefined ) {
4012
4013 $.mobile.transitionFallbacks.slideup = "fade";
4014
4015 })( jQuery, this );
4016
4017 /*
4018 * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4019 */
4020
4021 (function( $, window, undefined ) {
4022
4023 $.mobile.transitionFallbacks.flip = "fade";
4024
4025 })( jQuery, this );
4026
4027 /*
4028 * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4029 */
4030
4031 (function( $, window, undefined ) {
4032
4033 $.mobile.transitionFallbacks.flow = "fade";
4034
4035 })( jQuery, this );
4036
4037 /*
4038 * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4039 */
4040
4041 (function( $, window, undefined ) {
4042
4043 $.mobile.transitionFallbacks.turn = "fade";
4044
4045 })( jQuery, this );
4046
4047 (function( $, undefined ) {
4048
4049 $.mobile.page.prototype.options.degradeInputs = {
4050         color: false,
4051         date: false,
4052         datetime: false,
4053         "datetime-local": false,
4054         email: false,
4055         month: false,
4056         number: false,
4057         range: "number",
4058         search: "text",
4059         tel: false,
4060         time: false,
4061         url: false,
4062         week: false
4063 };
4064
4065
4066 //auto self-init widgets
4067 $( document ).bind( "pagecreate create", function( e ){
4068
4069         var page = $.mobile.closestPageData($(e.target)), options;
4070
4071         if( !page ) {
4072                 return;
4073         }
4074
4075         options = page.options;
4076
4077         // degrade inputs to avoid poorly implemented native functionality
4078         $( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
4079                 var $this = $( this ),
4080                         type = this.getAttribute( "type" ),
4081                         optType = options.degradeInputs[ type ] || "text";
4082
4083                 if ( options.degradeInputs[ type ] ) {
4084                         var html = $( "<div>" ).html( $this.clone() ).html(),
4085                                 // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
4086                                 hasType = html.indexOf( " type=" ) > -1,
4087                                 findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
4088                                 repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
4089
4090                         $this.replaceWith( html.replace( findstr, repstr ) );
4091                 }
4092         });
4093
4094 });
4095
4096 })( jQuery );
4097
4098 (function( $, window, undefined ) {
4099
4100 $.widget( "mobile.dialog", $.mobile.widget, {
4101         options: {
4102                 closeBtnText    : "Close",
4103                 overlayTheme    : "a",
4104                 initSelector    : ":jqmData(role='dialog')"
4105         },
4106         _create: function() {
4107                 var self = this,
4108                         $el = this.element,
4109                         headerCloseButton = $( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ),
4110                         dialogWrap = $("<div/>", {
4111                                         "role" : "dialog",
4112                                         "class" : "ui-dialog-contain ui-corner-all ui-overlay-shadow"
4113                                 });
4114
4115                 $el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
4116                 
4117                 // Class the markup for dialog styling
4118                 // Set aria role
4119                 $el
4120                         .wrapInner( dialogWrap )
4121                         .children()
4122                                 .find( ":jqmData(role='header')" )
4123                                         .prepend( headerCloseButton )
4124                                 .end()
4125                                 .children( ':first-child')
4126                                         .addClass( "ui-corner-top" )
4127                                 .end()
4128                                 .children( ":last-child" )
4129                                         .addClass( "ui-corner-bottom" );
4130
4131                 // this must be an anonymous function so that select menu dialogs can replace
4132                 // the close method. This is a change from previously just defining data-rel=back
4133                 // on the button and letting nav handle it
4134                 //
4135                 // Use click rather than vclick in order to prevent the possibility of unintentionally
4136                 // reopening the dialog if the dialog opening item was directly under the close button.
4137                 headerCloseButton.bind( "click", function() {
4138                         self.close();
4139                 });
4140
4141                 /* bind events
4142                         - clicks and submits should use the closing transition that the dialog opened with
4143                           unless a data-transition is specified on the link/form
4144                         - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
4145                 */
4146                 $el.bind( "vclick submit", function( event ) {
4147                         var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
4148                                 active;
4149
4150                         if ( $target.length && !$target.jqmData( "transition" ) ) {
4151
4152                                 active = $.mobile.urlHistory.getActive() || {};
4153
4154                                 $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
4155                                         .attr( "data-" + $.mobile.ns + "direction", "reverse" );
4156                         }
4157                 })
4158                 .bind( "pagehide", function( e, ui ) {
4159                         self._isClosed = false;
4160                         $( this ).find( "." + $.mobile.activeBtnClass ).not( ".ui-slider-bg" ).removeClass( $.mobile.activeBtnClass );
4161                 })
4162                 // Override the theme set by the page plugin on pageshow
4163                 .bind( "pagebeforeshow", function(){
4164                         if( self.options.overlayTheme ){
4165                                 self.element
4166                                         .page( "removeContainerBackground" )
4167                                         .page( "setContainerBackground", self.options.overlayTheme );
4168                         }
4169                 });
4170         },
4171
4172         // Close method goes back in history
4173         close: function() {
4174                 if ( !this._isClosed ) {
4175                         this._isClosed = true;
4176                         if ( $.mobile.hashListeningEnabled ) {
4177                                 window.history.back();
4178                         }
4179                         else {
4180                                 $.mobile.changePage( $.mobile.urlHistory.getPrev().url );
4181                         }
4182                 }
4183         }
4184 });
4185
4186 //auto self-init widgets
4187 $( document ).delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function(){
4188         $.mobile.dialog.prototype.enhance( this );
4189 });
4190
4191 })( jQuery, this );
4192
4193 (function( $, undefined ) {
4194
4195 $.mobile.page.prototype.options.backBtnText  = "Back";
4196 $.mobile.page.prototype.options.addBackBtn   = false;
4197 $.mobile.page.prototype.options.backBtnTheme = null;
4198 $.mobile.page.prototype.options.headerTheme  = "a";
4199 $.mobile.page.prototype.options.footerTheme  = "a";
4200 $.mobile.page.prototype.options.contentTheme = null;
4201
4202 // NOTE bind used to force this binding to run before the buttonMarkup binding
4203 //      which expects .ui-footer top be applied in its gigantic selector 
4204 // TODO remove the buttonMarkup giant selector and move it to the various modules
4205 //      on which it depends
4206 $( document ).bind( "pagecreate", function( e ) {
4207         var $page = $( e.target ),
4208                 o = $page.data( "page" ).options,
4209                 pageRole = $page.jqmData( "role" ),
4210                 pageTheme = o.theme;
4211
4212         $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
4213                 .jqmEnhanceable()
4214                 .each(function() {
4215
4216                 var $this = $( this ),
4217                         role = $this.jqmData( "role" ),
4218                         theme = $this.jqmData( "theme" ),
4219                         contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
4220                         $headeranchors,
4221                         leftbtn,
4222                         rightbtn,
4223                         backBtn;
4224
4225                 $this.addClass( "ui-" + role );
4226
4227                 //apply theming and markup modifications to page,header,content,footer
4228                 if ( role === "header" || role === "footer" ) {
4229
4230                         var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
4231
4232                         $this
4233                                 //add theme class
4234                                 .addClass( "ui-bar-" + thisTheme )
4235                                 // Add ARIA role
4236                                 .attr( "role", role === "header" ? "banner" : "contentinfo" );
4237
4238                         if( role === "header") {
4239                                 // Right,left buttons
4240                                 $headeranchors  = $this.children( "a" );
4241                                 leftbtn = $headeranchors.hasClass( "ui-btn-left" );
4242                                 rightbtn = $headeranchors.hasClass( "ui-btn-right" );
4243
4244                                 leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
4245
4246                                 rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
4247                         }
4248
4249                         // Auto-add back btn on pages beyond first view
4250                         if ( o.addBackBtn &&
4251                                 role === "header" &&
4252                                 $( ".ui-page" ).length > 1 &&
4253                                 $page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
4254                                 !leftbtn ) {
4255
4256                                 backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
4257                                         // If theme is provided, override default inheritance
4258                                         .attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
4259                                         .prependTo( $this );
4260                         }
4261
4262                         // Page title
4263                         $this.children( "h1, h2, h3, h4, h5, h6" )
4264                                 .addClass( "ui-title" )
4265                                 // Regardless of h element number in src, it becomes h1 for the enhanced page
4266                                 .attr({
4267                                         "role": "heading",
4268                                         "aria-level": "1"
4269                                 });
4270
4271                 } else if ( role === "content" ) {
4272                         if ( contentTheme ) {
4273                             $this.addClass( "ui-body-" + ( contentTheme ) );
4274                         }
4275
4276                         // Add ARIA role
4277                         $this.attr( "role", "main" );
4278                 }
4279         });
4280 });
4281
4282 })( jQuery );
4283
4284 (function( $, undefined ) {
4285
4286 // filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
4287 $.fn.fieldcontain = function( options ) {
4288         return this
4289                 .addClass( "ui-field-contain ui-body ui-br" )
4290                 .contents().filter( function() {
4291                         return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
4292                 }).remove();
4293 };
4294
4295 //auto self-init widgets
4296 $( document ).bind( "pagecreate create", function( e ){
4297         $( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
4298 });
4299
4300 })( jQuery );
4301
4302 (function( $, undefined ) {
4303
4304 $.fn.grid = function( options ) {
4305         return this.each(function() {
4306
4307                 var $this = $( this ),
4308                         o = $.extend({
4309                                 grid: null
4310                         },options),
4311                         $kids = $this.children(),
4312                         gridCols = {solo:1, a:2, b:3, c:4, d:5},
4313                         grid = o.grid,
4314                         iterator;
4315
4316                         if ( !grid ) {
4317                                 if ( $kids.length <= 5 ) {
4318                                         for ( var letter in gridCols ) {
4319                                                 if ( gridCols[ letter ] === $kids.length ) {
4320                                                         grid = letter;
4321                                                 }
4322                                         }
4323                                 } else {
4324                                         grid = "a";
4325                                         $this.addClass( "ui-grid-duo" );
4326                                 }
4327                         }
4328                         iterator = gridCols[grid];
4329
4330                 $this.addClass( "ui-grid-" + grid );
4331
4332                 $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
4333
4334                 if ( iterator > 1 ) {
4335                         $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
4336                 }
4337                 if ( iterator > 2 ) {
4338                         $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" );
4339                 }
4340                 if ( iterator > 3 ) {
4341                         $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" );
4342                 }
4343                 if ( iterator > 4 ) {
4344                         $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" );
4345                 }
4346         });
4347 };
4348 })( jQuery );
4349
4350 (function( $, undefined ) {
4351
4352 $( document ).bind( "pagecreate create", function( e ){
4353         $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
4354         
4355 });
4356
4357 })( jQuery );
4358
4359 ( function( $, undefined ) {
4360
4361 $.fn.buttonMarkup = function( options ) {
4362         var $workingSet = this;
4363
4364         // Enforce options to be of type string
4365         options = ( options && ( $.type( options ) == "object" ) )? options : {};
4366         for ( var i = 0; i < $workingSet.length; i++ ) {
4367                 var el = $workingSet.eq( i ),
4368                         e = el[ 0 ],
4369                         o = $.extend( {}, $.fn.buttonMarkup.defaults, {
4370                                 icon:       options.icon       !== undefined ? options.icon       : el.jqmData( "icon" ),
4371                                 iconpos:    options.iconpos    !== undefined ? options.iconpos    : el.jqmData( "iconpos" ),
4372                                 theme:      options.theme      !== undefined ? options.theme      : el.jqmData( "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
4373                                 inline:     options.inline     !== undefined ? options.inline     : el.jqmData( "inline" ),
4374                                 shadow:     options.shadow     !== undefined ? options.shadow     : el.jqmData( "shadow" ),
4375                                 corners:    options.corners    !== undefined ? options.corners    : el.jqmData( "corners" ),
4376                                 iconshadow: options.iconshadow !== undefined ? options.iconshadow : el.jqmData( "iconshadow" ),
4377                                 mini:       options.mini       !== undefined ? options.mini       : el.jqmData( "mini" )
4378                         }, options ),
4379
4380                         // Classes Defined
4381                         innerClass = "ui-btn-inner",
4382                         textClass = "ui-btn-text",
4383                         buttonClass, iconClass,
4384                         // Button inner markup
4385                         buttonInner,
4386                         buttonText,
4387                         buttonIcon,
4388                         buttonElements;
4389
4390                 $.each(o, function(key, value) {
4391                         e.setAttribute( "data-" + $.mobile.ns + key, value );
4392                         el.jqmData(key, value);
4393                 });
4394
4395                 // Check if this element is already enhanced
4396                 buttonElements = $.data(((e.tagName === "INPUT" || e.tagName === "BUTTON") ? e.parentNode : e), "buttonElements");
4397
4398                 if (buttonElements) {
4399                         e = buttonElements.outer;
4400                         el = $(e);
4401                         buttonInner = buttonElements.inner;
4402                         buttonText = buttonElements.text;
4403                         // We will recreate this icon below
4404                         $(buttonElements.icon).remove();
4405                         buttonElements.icon = null;
4406                 }
4407                 else {
4408                         buttonInner = document.createElement( o.wrapperEls );
4409                         buttonText = document.createElement( o.wrapperEls );
4410                 }
4411                 buttonIcon = o.icon ? document.createElement( "span" ) : null;
4412
4413                 if ( attachEvents && !buttonElements) {
4414                         attachEvents();
4415                 }
4416                 
4417                 // if not, try to find closest theme container  
4418                 if ( !o.theme ) {
4419                         o.theme = $.mobile.getInheritedTheme( el, "c" );        
4420                 }               
4421
4422                 buttonClass = "ui-btn ui-btn-up-" + o.theme;
4423                 buttonClass += o.inline ? " ui-btn-inline" : "";
4424                 buttonClass += o.shadow ? " ui-shadow" : "";
4425                 buttonClass += o.corners ? " ui-btn-corner-all" : "";
4426
4427                 if ( o.mini !== undefined ) {
4428                         // Used to control styling in headers/footers, where buttons default to `mini` style.
4429                         buttonClass += o.mini ? " ui-mini" : " ui-fullsize";
4430                 }
4431                 
4432                 if ( o.inline !== undefined ) {                 
4433                         // Used to control styling in headers/footers, where buttons default to `mini` style.
4434                         buttonClass += o.inline === false ? " ui-btn-block" : " ui-btn-inline";
4435                 }
4436                 
4437                 
4438                 if ( o.icon ) {
4439                         o.icon = "ui-icon-" + o.icon;
4440                         o.iconpos = o.iconpos || "left";
4441
4442                         iconClass = "ui-icon " + o.icon;
4443
4444                         if ( o.iconshadow ) {
4445                                 iconClass += " ui-icon-shadow";
4446                         }
4447                 }
4448
4449                 if ( o.iconpos ) {
4450                         buttonClass += " ui-btn-icon-" + o.iconpos;
4451
4452                         if ( o.iconpos == "notext" && !el.attr( "title" ) ) {
4453                                 el.attr( "title", el.getEncodedText() );
4454                         }
4455                 }
4456     
4457                 innerClass += o.corners ? " ui-btn-corner-all" : "";
4458
4459                 if ( o.iconpos && o.iconpos === "notext" && !el.attr( "title" ) ) {
4460                         el.attr( "title", el.getEncodedText() );
4461                 }
4462
4463                 if ( buttonElements ) {
4464                         el.removeClass( buttonElements.bcls || "" );
4465                 }
4466                 el.removeClass( "ui-link" ).addClass( buttonClass );
4467
4468                 buttonInner.className = innerClass;
4469
4470                 buttonText.className = textClass;
4471                 if ( !buttonElements ) {
4472                         buttonInner.appendChild( buttonText );
4473                 }
4474                 if ( buttonIcon ) {
4475                         buttonIcon.className = iconClass;
4476                         if ( !(buttonElements && buttonElements.icon) ) {
4477                                 buttonIcon.appendChild( document.createTextNode("\u00a0") );
4478                                 buttonInner.appendChild( buttonIcon );
4479                         }
4480                 }
4481
4482                 while ( e.firstChild && !buttonElements) {
4483                         buttonText.appendChild( e.firstChild );
4484                 }
4485
4486                 if ( !buttonElements ) {
4487                         e.appendChild( buttonInner );
4488                 }
4489
4490                 // Assign a structure containing the elements of this button to the elements of this button. This
4491                 // will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
4492                 buttonElements = {
4493                         bcls  : buttonClass,
4494                         outer : e,
4495                         inner : buttonInner,
4496                         text  : buttonText,
4497                         icon  : buttonIcon
4498                 };
4499
4500                 $.data(e,           'buttonElements', buttonElements);
4501                 $.data(buttonInner, 'buttonElements', buttonElements);
4502                 $.data(buttonText,  'buttonElements', buttonElements);
4503                 if (buttonIcon) {
4504                         $.data(buttonIcon, 'buttonElements', buttonElements);
4505                 }
4506         }
4507
4508         return this;
4509 };
4510
4511 $.fn.buttonMarkup.defaults = {
4512         corners: true,
4513         shadow: true,
4514         iconshadow: true,
4515         wrapperEls: "span"
4516 };
4517
4518 function closestEnabledButton( element ) {
4519     var cname;
4520
4521     while ( element ) {
4522                 // Note that we check for typeof className below because the element we
4523                 // handed could be in an SVG DOM where className on SVG elements is defined to
4524                 // be of a different type (SVGAnimatedString). We only operate on HTML DOM
4525                 // elements, so we look for plain "string".
4526         cname = ( typeof element.className === 'string' ) && (element.className + ' ');
4527         if ( cname && cname.indexOf("ui-btn ") > -1 && cname.indexOf("ui-disabled ") < 0 ) {
4528             break;
4529         }
4530
4531         element = element.parentNode;
4532     }
4533
4534     return element;
4535 }
4536
4537 var attachEvents = function() {
4538         var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
4539
4540         $( document ).bind( {
4541                 "vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
4542                         var theme,
4543                                 $btn = $( closestEnabledButton( event.target ) ),
4544                                 evt = event.type;
4545                 
4546                         if ( $btn.length ) {
4547                                 theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
4548                 
4549                                 if ( evt === "vmousedown" ) {
4550                                         if ( $.support.touch ) {
4551                                                 hov = setTimeout(function() {
4552                                                         $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
4553                                                 }, hoverDelay );
4554                                         } else {
4555                                                 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
4556                                         }
4557                                 } else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
4558                                         $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
4559                                 } else if ( evt === "vmouseover" || evt === "focus" ) {
4560                                         if ( $.support.touch ) {
4561                                                 foc = setTimeout(function() {
4562                                                         $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
4563                                                 }, hoverDelay );
4564                                         } else {
4565                                                 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
4566                                         }
4567                                 } else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
4568                                         $btn.removeClass( "ui-btn-hover-" + theme  + " ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
4569                                         if ( hov ) {
4570                                                 clearTimeout( hov );
4571                                         }
4572                                         if ( foc ) {
4573                                                 clearTimeout( foc );
4574                                         }
4575                                 }
4576                         }
4577                 },
4578                 "focusin focus": function( event ){
4579                         $( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
4580                 },
4581                 "focusout blur": function( event ){
4582                         $( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
4583                 }
4584         });
4585
4586         attachEvents = null;
4587 };
4588
4589 //links in bars, or those with  data-role become buttons
4590 //auto self-init widgets
4591 $( document ).bind( "pagecreate create", function( e ){
4592
4593         $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
4594                 .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
4595                 .buttonMarkup();
4596 });
4597
4598 })( jQuery );
4599
4600
4601 (function( $, undefined ) {
4602
4603 $.widget( "mobile.collapsible", $.mobile.widget, {
4604         options: {
4605                 expandCueText: " click to expand contents",
4606                 collapseCueText: " click to collapse contents",
4607                 collapsed: true,
4608                 heading: "h1,h2,h3,h4,h5,h6,legend",
4609                 theme: null,
4610                 contentTheme: null,
4611                 iconTheme: "d",
4612                 mini: false,
4613                 initSelector: ":jqmData(role='collapsible')"
4614         },
4615         _create: function() {
4616
4617                 var $el = this.element,
4618                         o = this.options,
4619                         collapsible = $el.addClass( "ui-collapsible" ),
4620                         collapsibleHeading = $el.children( o.heading ).first(),
4621                         collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ),
4622                         collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" );
4623
4624                 // Replace collapsibleHeading if it's a legend
4625                 if ( collapsibleHeading.is( "legend" ) ) {
4626                         collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
4627                         collapsibleHeading.next().remove();
4628                 }
4629
4630                 // If we are in a collapsible set
4631                 if ( collapsibleSet.length ) {
4632                         // Inherit the theme from collapsible-set
4633                         if ( !o.theme ) {
4634                                 o.theme = collapsibleSet.jqmData("theme") || $.mobile.getInheritedTheme( collapsibleSet, "c" );
4635                         }
4636                         // Inherit the content-theme from collapsible-set
4637                         if ( !o.contentTheme ) {
4638                                 o.contentTheme = collapsibleSet.jqmData( "content-theme" );
4639                         }
4640
4641                         // Gets the preference icon position in the set
4642                         if ( !o.iconPos ) {
4643                                 o.iconPos = collapsibleSet.jqmData( "iconpos" );
4644                         }
4645
4646                         if( !o.mini ) {
4647                                 o.mini = collapsibleSet.jqmData( "mini" );
4648                         }
4649                 }
4650                 collapsibleContent.addClass( ( o.contentTheme ) ? ( "ui-body-" + o.contentTheme ) : "");
4651
4652                 collapsibleHeading
4653                         //drop heading in before content
4654                         .insertBefore( collapsibleContent )
4655                         //modify markup & attributes
4656                         .addClass( "ui-collapsible-heading" )
4657                         .append( "<span class='ui-collapsible-heading-status'></span>" )
4658                         .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
4659                         .find( "a" )
4660                                 .first()
4661                                 .buttonMarkup({
4662                                         shadow: false,
4663                                         corners: false,
4664                                         iconpos: $el.jqmData( "iconpos" ) || o.iconPos || "left",
4665                                         icon: "plus",
4666                                         mini: o.mini,
4667                                         theme: o.theme
4668                                 })
4669                         .add( ".ui-btn-inner", $el )
4670                                 .addClass( "ui-corner-top ui-corner-bottom" );
4671
4672                 //events
4673                 collapsible
4674                         .bind( "expand collapse", function( event ) {
4675                                 if ( !event.isDefaultPrevented() ) {
4676
4677                                         event.preventDefault();
4678
4679                                         var $this = $( this ),
4680                                                 isCollapse = ( event.type === "collapse" ),
4681                                             contentTheme = o.contentTheme;
4682
4683                                         collapsibleHeading
4684                                                 .toggleClass( "ui-collapsible-heading-collapsed", isCollapse)
4685                                                 .find( ".ui-collapsible-heading-status" )
4686                                                         .text( isCollapse ? o.expandCueText : o.collapseCueText )
4687                                                 .end()
4688                                                 .find( ".ui-icon" )
4689                                                         .toggleClass( "ui-icon-minus", !isCollapse )
4690                                                         .toggleClass( "ui-icon-plus", isCollapse )
4691                                                 .end()
4692                                                 .find( "a" ).first().removeClass( $.mobile.activeBtnClass );
4693
4694                                         $this.toggleClass( "ui-collapsible-collapsed", isCollapse );
4695                                         collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
4696
4697                                         if ( contentTheme && ( !collapsibleSet.length || collapsible.jqmData( "collapsible-last" ) ) ) {
4698                                                 collapsibleHeading
4699                                                         .find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) )
4700                                                         .toggleClass( "ui-corner-bottom", isCollapse );
4701                                                 collapsibleContent.toggleClass( "ui-corner-bottom", !isCollapse );
4702                                         }
4703                                         collapsibleContent.trigger( "updatelayout" );
4704                                 }
4705                         })
4706                         .trigger( o.collapsed ? "collapse" : "expand" );
4707
4708                 collapsibleHeading
4709                         .bind( "tap", function( event ) {
4710                                 collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
4711                         })
4712                         .bind( "click", function( event ) {
4713
4714                                 var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ?
4715                                                                                 "expand" : "collapse";
4716
4717                                 collapsible.trigger( type );
4718
4719                                 event.preventDefault();
4720                                 event.stopPropagation();
4721                         });
4722         }
4723 });
4724
4725 //auto self-init widgets
4726 $( document ).bind( "pagecreate create", function( e ){
4727         $.mobile.collapsible.prototype.enhanceWithin( e.target );
4728 });
4729
4730 })( jQuery );
4731
4732 (function( $, undefined ) {
4733
4734 $.widget( "mobile.collapsibleset", $.mobile.widget, {
4735         options: {
4736                 initSelector: ":jqmData(role='collapsible-set')"
4737         },
4738         _create: function() {
4739                 var $el = this.element.addClass( "ui-collapsible-set" ),
4740                         o = this.options;
4741
4742                 // Inherit the theme from collapsible-set
4743                 if ( !o.theme ) {
4744                         o.theme = $.mobile.getInheritedTheme( $el, "c" );
4745                 }
4746                 // Inherit the content-theme from collapsible-set
4747                 if ( !o.contentTheme ) {
4748                         o.contentTheme = $el.jqmData( "content-theme" );
4749                 }
4750
4751                 if ( !o.corners ) {
4752                         o.corners = $el.jqmData( "corners" ) === undefined ? true : false;
4753                 }
4754
4755                 // Initialize the collapsible set if it's not already initialized
4756                 if ( !$el.jqmData( "collapsiblebound" ) ) {
4757                         $el
4758                                 .jqmData( "collapsiblebound", true )
4759                                 .bind( "expand collapse", function( event ) {
4760                                         var isCollapse = ( event.type === "collapse" ),
4761                                                 collapsible = $( event.target ).closest( ".ui-collapsible" ),
4762                                                 widget = collapsible.data( "collapsible" ),
4763                                             contentTheme = widget.options.contentTheme;
4764                                         if ( contentTheme && collapsible.jqmData( "collapsible-last" ) ) {
4765                                                 collapsible.find( widget.options.heading ).first()
4766                                                         .find( "a" ).first()
4767                                                         .toggleClass( "ui-corner-bottom", isCollapse )
4768                                                         .find( ".ui-btn-inner" )
4769                                                         .toggleClass( "ui-corner-bottom", isCollapse );
4770                                                 collapsible.find( ".ui-collapsible-content" ).toggleClass( "ui-corner-bottom", !isCollapse );
4771                                         }
4772                                 })
4773                                 .bind( "expand", function( event ) {
4774                                         $( event.target )
4775                                                 .closest( ".ui-collapsible" )
4776                                                 .siblings( ".ui-collapsible" )
4777                                                 .trigger( "collapse" );
4778                                 });
4779                 }
4780         },
4781
4782         _init: function() {
4783                 this.refresh();
4784         },
4785
4786         refresh: function() {
4787                 var $el = this.element,
4788                         o = this.options,
4789                         collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" );
4790
4791                 $.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
4792
4793                 // clean up borders
4794                 collapsiblesInSet.each( function() {
4795                         $( this ).find( $.mobile.collapsible.prototype.options.heading )
4796                                 .find( "a" ).first()
4797                                 .removeClass( "ui-corner-top ui-corner-bottom" )
4798                                 .find( ".ui-btn-inner" )
4799                                 .removeClass( "ui-corner-top ui-corner-bottom" );
4800                 });
4801
4802                 collapsiblesInSet.first()
4803                         .find( "a" )
4804                                 .first()
4805                                 .addClass( o.corners ? "ui-corner-top" : "" )
4806                                 .find( ".ui-btn-inner" )
4807                                         .addClass( "ui-corner-top" );
4808
4809                 collapsiblesInSet.last()
4810                         .jqmData( "collapsible-last", true )
4811                         .find( "a" )
4812                                 .first()
4813                                 .addClass( o.corners ? "ui-corner-bottom" : "" )
4814                                 .find( ".ui-btn-inner" )
4815                                         .addClass( "ui-corner-bottom" );
4816         }
4817 });
4818
4819 //auto self-init widgets
4820 $( document ).bind( "pagecreate create", function( e ){
4821         $.mobile.collapsibleset.prototype.enhanceWithin( e.target );
4822 });
4823
4824 })( jQuery );
4825
4826 (function( $, undefined ) {
4827
4828 $.widget( "mobile.navbar", $.mobile.widget, {
4829         options: {
4830                 iconpos: "top",
4831                 grid: null,
4832                 initSelector: ":jqmData(role='navbar')"
4833         },
4834
4835         _create: function(){
4836
4837                 var $navbar = this.element,
4838                         $navbtns = $navbar.find( "a" ),
4839                         iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
4840                                                                         this.options.iconpos : undefined;
4841
4842                 $navbar.addClass( "ui-navbar ui-mini" )
4843                         .attr( "role","navigation" )
4844                         .find( "ul" )
4845                         .jqmEnhanceable()
4846                         .grid({ grid: this.options.grid });
4847
4848                 $navbtns.buttonMarkup({
4849                         corners:        false,
4850                         shadow:         false,
4851                         inline:     true,
4852                         iconpos:        iconpos
4853                 });
4854
4855                 $navbar.delegate( "a", "vclick", function( event ) {
4856                         if( !$(event.target).hasClass("ui-disabled") ) {
4857                                 $navbtns.removeClass( $.mobile.activeBtnClass );
4858                                 $( this ).addClass( $.mobile.activeBtnClass );
4859                         }
4860                 });
4861
4862                 // Buttons in the navbar with ui-state-persist class should regain their active state before page show
4863                 $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
4864                         $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
4865                 });
4866         }
4867 });
4868
4869 //auto self-init widgets
4870 $( document ).bind( "pagecreate create", function( e ){
4871         $.mobile.navbar.prototype.enhanceWithin( e.target );
4872 });
4873
4874 })( jQuery );
4875
4876 (function( $, undefined ) {
4877
4878 //Keeps track of the number of lists per page UID
4879 //This allows support for multiple nested list in the same page
4880 //https://github.com/jquery/jquery-mobile/issues/1617
4881 var listCountPerPage = {};
4882
4883 $.widget( "mobile.listview", $.mobile.widget, {
4884
4885         options: {
4886                 theme: null,
4887                 countTheme: "c",
4888                 headerTheme: "b",
4889                 dividerTheme: "b",
4890                 splitIcon: "arrow-r",
4891                 splitTheme: "b",
4892                 inset: false,
4893                 initSelector: ":jqmData(role='listview')"
4894         },
4895
4896         _create: function() {
4897                 var t = this,
4898                         listviewClasses = "";
4899                         
4900                 listviewClasses += t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "";
4901
4902                 // create listview markup
4903                 t.element.addClass(function( i, orig ) {
4904                         return orig + " ui-listview " + listviewClasses;
4905                 });
4906
4907                 t.refresh( true );
4908         },
4909
4910         _removeCorners: function( li, which ) {
4911                 var top = "ui-corner-top ui-corner-tr ui-corner-tl",
4912                         bot = "ui-corner-bottom ui-corner-br ui-corner-bl";
4913
4914                 li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) );
4915
4916                 if ( which === "top" ) {
4917                         li.removeClass( top );
4918                 } else if ( which === "bottom" ) {
4919                         li.removeClass( bot );
4920                 } else {
4921                         li.removeClass( top + " " + bot );
4922                 }
4923         },
4924
4925         _refreshCorners: function( create ) {
4926                 var $li,
4927                         $visibleli,
4928                         $topli,
4929                         $bottomli;
4930
4931                 if ( this.options.inset ) {
4932                         $li = this.element.children( "li" );
4933                         // at create time the li are not visible yet so we need to rely on .ui-screen-hidden
4934                         $visibleli = create?$li.not( ".ui-screen-hidden" ):$li.filter( ":visible" );
4935
4936                         this._removeCorners( $li );
4937
4938                         // Select the first visible li element
4939                         $topli = $visibleli.first()
4940                                 .addClass( "ui-corner-top" );
4941
4942                         $topli.add( $topli.find( ".ui-btn-inner" )
4943                                         .not( ".ui-li-link-alt span:first-child" ) )
4944                                 .addClass( "ui-corner-top" )
4945                                 .end()
4946                                 .find( ".ui-li-link-alt, .ui-li-link-alt span:first-child" )
4947                                         .addClass( "ui-corner-tr" )
4948                                 .end()
4949                                 .find( ".ui-li-thumb" )
4950                                         .not(".ui-li-icon")
4951                                         .addClass( "ui-corner-tl" );
4952
4953                         // Select the last visible li element
4954                         $bottomli = $visibleli.last()
4955                                 .addClass( "ui-corner-bottom" );
4956
4957                         $bottomli.add( $bottomli.find( ".ui-btn-inner" ) )
4958                                 .find( ".ui-li-link-alt" )
4959                                         .addClass( "ui-corner-br" )
4960                                 .end()
4961                                 .find( ".ui-li-thumb" )
4962                                         .not(".ui-li-icon")
4963                                         .addClass( "ui-corner-bl" );
4964                 }
4965                 if ( !create ) {
4966                         this.element.trigger( "updatelayout" );
4967                 }
4968         },
4969
4970         // This is a generic utility method for finding the first
4971         // node with a given nodeName. It uses basic DOM traversal
4972         // to be fast and is meant to be a substitute for simple
4973         // $.fn.closest() and $.fn.children() calls on a single
4974         // element. Note that callers must pass both the lowerCase
4975         // and upperCase version of the nodeName they are looking for.
4976         // The main reason for this is that this function will be
4977         // called many times and we want to avoid having to lowercase
4978         // the nodeName from the element every time to ensure we have
4979         // a match. Note that this function lives here for now, but may
4980         // be moved into $.mobile if other components need a similar method.
4981         _findFirstElementByTagName: function( ele, nextProp, lcName, ucName )
4982         {
4983                 var dict = {};
4984                 dict[ lcName ] = dict[ ucName ] = true;
4985                 while ( ele ) {
4986                         if ( dict[ ele.nodeName ] ) {
4987                                 return ele;
4988                         }
4989                         ele = ele[ nextProp ];
4990                 }
4991                 return null;
4992         },
4993         _getChildrenByTagName: function( ele, lcName, ucName )
4994         {
4995                 var results = [],
4996                         dict = {};
4997                 dict[ lcName ] = dict[ ucName ] = true;
4998                 ele = ele.firstChild;
4999                 while ( ele ) {
5000                         if ( dict[ ele.nodeName ] ) {
5001                                 results.push( ele );
5002                         }
5003                         ele = ele.nextSibling;
5004                 }
5005                 return $( results );
5006         },
5007
5008         _addThumbClasses: function( containers )
5009         {
5010                 var i, img, len = containers.length;
5011                 for ( i = 0; i < len; i++ ) {
5012                         img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
5013                         if ( img.length ) {
5014                                 img.addClass( "ui-li-thumb" );
5015                                 $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
5016                         }
5017                 }
5018         },
5019
5020         refresh: function( create ) {
5021                 this.parentPage = this.element.closest( ".ui-page" );
5022                 this._createSubPages();
5023
5024                 var o = this.options,
5025                         $list = this.element,
5026                         self = this,
5027                         dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
5028                         listsplittheme = $list.jqmData( "splittheme" ),
5029                         listspliticon = $list.jqmData( "spliticon" ),
5030                         li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
5031                         counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1,
5032                         itemClassDict = {},
5033                         item, itemClass, itemTheme,
5034                         a, last, splittheme, countParent, icon, imgParents, img, linkIcon;
5035
5036                 if ( counter ) {
5037                         $list.find( ".ui-li-dec" ).remove();
5038                 }
5039
5040                 if ( !o.theme ) {
5041                         o.theme = $.mobile.getInheritedTheme( this.element, "c" );
5042                 }
5043
5044                 for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
5045                         item = li.eq( pos );
5046                         itemClass = "ui-li";
5047
5048                         // If we're creating the element, we update it regardless
5049                         if ( create || !item.hasClass( "ui-li" ) ) {
5050                                 itemTheme = item.jqmData("theme") || o.theme;
5051                                 a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
5052                                 var isDivider = ( item.jqmData( "role" ) === "list-divider" );
5053
5054                                 if ( a.length && !isDivider ) {
5055                                         icon = item.jqmData("icon");
5056
5057                                         item.buttonMarkup({
5058                                                 wrapperEls: "div",
5059                                                 shadow: false,
5060                                                 corners: false,
5061                                                 iconpos: "right",
5062                                                 icon: a.length > 1 || icon === false ? false : icon || "arrow-r",
5063                                                 theme: itemTheme
5064                                         });
5065
5066                                         if ( ( icon != false ) && ( a.length == 1 ) ) {
5067                                                 item.addClass( "ui-li-has-arrow" );
5068                                         }
5069
5070                                         a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
5071
5072                                         if ( a.length > 1 ) {
5073                                                 itemClass += " ui-li-has-alt";
5074
5075                                                 last = a.last();
5076                                                 splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
5077                                                 linkIcon = last.jqmData("icon");
5078
5079                                                 last.appendTo(item)
5080                                                         .attr( "title", last.getEncodedText() )
5081                                                         .addClass( "ui-li-link-alt" )
5082                                                         .empty()
5083                                                         .buttonMarkup({
5084                                                                 shadow: false,
5085                                                                 corners: false,
5086                                                                 theme: itemTheme,
5087                                                                 icon: false,
5088                                                                 iconpos: "notext"
5089                                                         })
5090                                                         .find( ".ui-btn-inner" )
5091                                                                 .append(
5092                                                                         $( document.createElement( "span" ) ).buttonMarkup({
5093                                                                                 shadow: true,
5094                                                                                 corners: true,
5095                                                                                 theme: splittheme,
5096                                                                                 iconpos: "notext",
5097                                                                                 // link icon overrides list item icon overrides ul element overrides options
5098                                                                                 icon: linkIcon || icon || listspliticon || o.splitIcon
5099                                                                         })
5100                                                                 );
5101                                         }
5102                                 } else if ( isDivider ) {
5103
5104                                         itemClass += " ui-li-divider ui-bar-" + dividertheme;
5105                                         item.attr( "role", "heading" );
5106
5107                                         //reset counter when a divider heading is encountered
5108                                         if ( counter ) {
5109                                                 counter = 1;
5110                                         }
5111
5112                                 } else {
5113                                         itemClass += " ui-li-static ui-body-" + itemTheme;
5114                                 }
5115                         }
5116
5117                         if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
5118                                 countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" );
5119
5120                                 countParent.addClass( "ui-li-jsnumbering" )
5121                                         .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" );
5122                         }
5123
5124                         // Instead of setting item class directly on the list item and its
5125                         // btn-inner at this point in time, push the item into a dictionary
5126                         // that tells us what class to set on it so we can do this after this
5127                         // processing loop is finished.
5128
5129                         if ( !itemClassDict[ itemClass ] ) {
5130                                 itemClassDict[ itemClass ] = [];
5131                         }
5132
5133                         itemClassDict[ itemClass ].push( item[ 0 ] );
5134                 }
5135
5136                 // Set the appropriate listview item classes on each list item
5137                 // and their btn-inner elements. The main reason we didn't do this
5138                 // in the for-loop above is because we can eliminate per-item function overhead
5139                 // by calling addClass() and children() once or twice afterwards. This
5140                 // can give us a significant boost on platforms like WP7.5.
5141
5142                 for ( itemClass in itemClassDict ) {
5143                         $( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
5144                 }
5145
5146                 $list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
5147                         .end()
5148
5149                         .find( "p, dl" ).addClass( "ui-li-desc" )
5150                         .end()
5151
5152                         .find( ".ui-li-aside" ).each(function() {
5153                                         var $this = $(this);
5154                                         $this.prependTo( $this.parent() ); //shift aside to front for css float
5155                                 })
5156                         .end()
5157
5158                         .find( ".ui-li-count" ).each( function() {
5159                                         $( this ).closest( "li" ).addClass( "ui-li-has-count" );
5160                                 }).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
5161
5162                 // The idea here is to look at the first image in the list item
5163                 // itself, and any .ui-link-inherit element it may contain, so we
5164                 // can place the appropriate classes on the image and list item.
5165                 // Note that we used to use something like:
5166                 //
5167                 //    li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
5168                 //
5169                 // But executing a find() like that on Windows Phone 7.5 took a
5170                 // really long time. Walking things manually with the code below
5171                 // allows the 400 listview item page to load in about 3 seconds as
5172                 // opposed to 30 seconds.
5173
5174                 this._addThumbClasses( li );
5175                 this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
5176
5177                 this._refreshCorners( create );
5178         },
5179
5180         //create a string for ID/subpage url creation
5181         _idStringEscape: function( str ) {
5182                 return str.replace(/[^a-zA-Z0-9]/g, '-');
5183         },
5184
5185         _createSubPages: function() {
5186                 var parentList = this.element,
5187                         parentPage = parentList.closest( ".ui-page" ),
5188                         parentUrl = parentPage.jqmData( "url" ),
5189                         parentId = parentUrl || parentPage[ 0 ][ $.expando ],
5190                         parentListId = parentList.attr( "id" ),
5191                         o = this.options,
5192                         dns = "data-" + $.mobile.ns,
5193                         self = this,
5194                         persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
5195                         hasSubPages;
5196
5197                 if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
5198                         listCountPerPage[ parentId ] = -1;
5199                 }
5200
5201                 parentListId = parentListId || ++listCountPerPage[ parentId ];
5202
5203                 $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
5204                         var self = this,
5205                                 list = $( this ),
5206                                 listId = list.attr( "id" ) || parentListId + "-" + i,
5207                                 parent = list.parent(),
5208                                 nodeEls = $( list.prevAll().toArray().reverse() ),
5209                                 nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
5210                                 title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
5211                                 id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
5212                                 theme = list.jqmData( "theme" ) || o.theme,
5213                                 countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
5214                                 newPage, anchor;
5215
5216                         //define hasSubPages for use in later removal
5217                         hasSubPages = true;
5218
5219                         newPage = list.detach()
5220                                                 .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
5221                                                 .parent()
5222                                                         .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
5223                                                         .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" )
5224                                                         .parent()
5225                                                                 .appendTo( $.mobile.pageContainer );
5226
5227                         newPage.page();
5228
5229                         anchor = parent.find('a:first');
5230
5231                         if ( !anchor.length ) {
5232                                 anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
5233                         }
5234
5235                         anchor.attr( "href", "#" + id );
5236
5237                 }).listview();
5238
5239                 // on pagehide, remove any nested pages along with the parent page, as long as they aren't active
5240                 // and aren't embedded
5241                 if( hasSubPages &&
5242                         parentPage.is( ":jqmData(external-page='true')" ) &&
5243                         parentPage.data("page").options.domCache === false ) {
5244
5245                         var newRemove = function( e, ui ){
5246                                 var nextPage = ui.nextPage, npURL,
5247                                         prEvent = new $.Event( "pageremove" );
5248
5249                                 if( ui.nextPage ){
5250                                         npURL = nextPage.jqmData( "url" );
5251                                         if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){
5252                                                 self.childPages().remove();
5253                                                 parentPage.trigger( prEvent );
5254                                                 if( !prEvent.isDefaultPrevented() ){
5255                                                         parentPage.removeWithDependents();
5256                                                 }
5257                                         }
5258                                 }
5259                         };
5260
5261                         // unbind the original page remove and replace with our specialized version
5262                         parentPage
5263                                 .unbind( "pagehide.remove" )
5264                                 .bind( "pagehide.remove", newRemove);
5265                 }
5266         },
5267
5268         // TODO sort out a better way to track sub pages of the listview this is brittle
5269         childPages: function(){
5270                 var parentUrl = this.parentPage.jqmData( "url" );
5271
5272                 return $( ":jqmData(url^='"+  parentUrl + "&" + $.mobile.subPageUrlKey +"')");
5273         }
5274 });
5275
5276 //auto self-init widgets
5277 $( document ).bind( "pagecreate create", function( e ){
5278         $.mobile.listview.prototype.enhanceWithin( e.target );
5279 });
5280
5281 })( jQuery );
5282
5283 /*
5284 * "checkboxradio" plugin
5285 */
5286
5287 (function( $, undefined ) {
5288
5289 $.widget( "mobile.checkboxradio", $.mobile.widget, {
5290         options: {
5291                 theme: null,
5292                 initSelector: "input[type='checkbox'],input[type='radio']"
5293         },
5294         _create: function() {
5295                 var self = this,
5296                         input = this.element,
5297                         inheritAttr = function( input, dataAttr ) {
5298                                 return input.jqmData( dataAttr ) || input.closest( "form,fieldset" ).jqmData( dataAttr )
5299                         },
5300                         // NOTE: Windows Phone could not find the label through a selector
5301                         // filter works though.
5302                         parentLabel = $( input ).closest( "label" ),
5303                         label = parentLabel.length ? parentLabel : $( input ).closest( "form,fieldset,:jqmData(role='page'),:jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ),
5304                         inputtype = input[0].type,
5305                         mini = inheritAttr( input, "mini" ),
5306                         checkedState = inputtype + "-on",
5307                         uncheckedState = inputtype + "-off",
5308                         icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState,
5309                         iconpos = inheritAttr( input, "iconpos" ),
5310                         activeBtn = icon ? "" : " " + $.mobile.activeBtnClass,
5311                         checkedClass = "ui-" + checkedState + activeBtn,
5312                         uncheckedClass = "ui-" + uncheckedState,
5313                         checkedicon = "ui-icon-" + checkedState,
5314                         uncheckedicon = "ui-icon-" + uncheckedState;
5315
5316                 if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
5317                         return;
5318                 }
5319
5320                 // Expose for other methods
5321                 $.extend( this, {
5322                         label: label,
5323                         inputtype: inputtype,
5324                         checkedClass: checkedClass,
5325                         uncheckedClass: uncheckedClass,
5326                         checkedicon: checkedicon,
5327                         uncheckedicon: uncheckedicon
5328                 });
5329
5330                 // If there's no selected theme check the data attr
5331                 if( !this.options.theme ) {
5332                         this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
5333                 }
5334
5335                 label.buttonMarkup({
5336                         theme: this.options.theme,
5337                         icon: icon,
5338                         shadow: false,
5339                         mini: mini,
5340                         iconpos: iconpos
5341                 });
5342
5343                 // Wrap the input + label in a div
5344                 var wrapper = document.createElement('div');
5345                 wrapper.className = 'ui-' + inputtype;
5346
5347                 input.add( label ).wrapAll( wrapper );
5348
5349                 label.bind({
5350                         vmouseover: function( event ) {
5351                                 if ( $( this ).parent().is( ".ui-disabled" ) ) {
5352                                         event.stopPropagation();
5353                                 }
5354                         },
5355
5356                         vclick: function( event ) {
5357                                 if ( input.is( ":disabled" ) ) {
5358                                         event.preventDefault();
5359                                         return;
5360                                 }
5361
5362                                 self._cacheVals();
5363
5364                                 input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
5365
5366                                 // trigger click handler's bound directly to the input as a substitute for
5367                                 // how label clicks behave normally in the browsers
5368                                 // TODO: it would be nice to let the browser's handle the clicks and pass them
5369                                 //       through to the associate input. we can swallow that click at the parent
5370                                 //       wrapper element level
5371                                 input.triggerHandler( 'click' );
5372
5373                                 // Input set for common radio buttons will contain all the radio
5374                                 // buttons, but will not for checkboxes. clearing the checked status
5375                                 // of other radios ensures the active button state is applied properly
5376                                 self._getInputSet().not( input ).prop( "checked", false );
5377
5378                                 self._updateAll();
5379                                 return false;
5380                         }
5381                 });
5382
5383                 input
5384                         .bind({
5385                                 vmousedown: function() {
5386                                         self._cacheVals();
5387                                 },
5388
5389                                 vclick: function() {
5390                                         var $this = $(this);
5391
5392                                         // Adds checked attribute to checked input when keyboard is used
5393                                         if ( $this.is( ":checked" ) ) {
5394
5395                                                 $this.prop( "checked", true);
5396                                                 self._getInputSet().not($this).prop( "checked", false );
5397                                         } else {
5398
5399                                                 $this.prop( "checked", false );
5400                                         }
5401
5402                                         self._updateAll();
5403                                 },
5404
5405                                 focus: function() {
5406                                         label.addClass( $.mobile.focusClass );
5407                                 },
5408
5409                                 blur: function() {
5410                                         label.removeClass( $.mobile.focusClass );
5411                                 }
5412                         });
5413
5414                 this.refresh();
5415         },
5416
5417         _cacheVals: function() {
5418                 this._getInputSet().each(function() {
5419                         $(this).jqmData( "cacheVal", this.checked );
5420                 });
5421         },
5422
5423         //returns either a set of radios with the same name attribute, or a single checkbox
5424         _getInputSet: function(){
5425                 if(this.inputtype === "checkbox") {
5426                         return this.element;
5427                 }
5428
5429                 return this.element.closest( "form,fieldset,:jqmData(role='page')" )
5430                         .find( "input[name='"+ this.element[0].name +"'][type='"+ this.inputtype +"']" );
5431         },
5432
5433         _updateAll: function() {
5434                 var self = this;
5435
5436                 this._getInputSet().each(function() {
5437                         var $this = $(this);
5438
5439                         if ( this.checked || self.inputtype === "checkbox" ) {
5440                                 $this.trigger( "change" );
5441                         }
5442                 })
5443                 .checkboxradio( "refresh" );
5444         },
5445
5446         refresh: function() {
5447                 var input = this.element[0],
5448                         label = this.label,
5449                         icon = label.find( ".ui-icon" );
5450
5451                 if ( input.checked ) {
5452                         label.addClass( this.checkedClass ).removeClass( this.uncheckedClass );
5453                         icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon );
5454                 } else {
5455                         label.removeClass( this.checkedClass ).addClass( this.uncheckedClass );
5456                         icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon );
5457                 }
5458
5459                 if ( input.disabled ) {
5460                         this.disable();
5461                 } else {
5462                         this.enable();
5463                 }
5464         },
5465
5466         disable: function() {
5467                 this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
5468         },
5469
5470         enable: function() {
5471                 this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
5472         }
5473 });
5474
5475 //auto self-init widgets
5476 $( document ).bind( "pagecreate create", function( e ){
5477         $.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
5478 });
5479
5480 })( jQuery );
5481
5482 (function( $, undefined ) {
5483
5484 $.widget( "mobile.button", $.mobile.widget, {
5485         options: {
5486                 theme: null,
5487                 icon: null,
5488                 iconpos: null,
5489                 inline: false,
5490                 corners: true,
5491                 shadow: true,
5492                 iconshadow: true,
5493                 initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']",
5494                 mini: false
5495         },
5496         _create: function() {
5497                 var $el = this.element,
5498                         $button,
5499                         o = this.options,
5500                         type,
5501                         name,
5502                         classes = "",
5503                         $buttonPlaceholder;
5504
5505                 // if this is a link, check if it's been enhanced and, if not, use the right function
5506                 if( $el[ 0 ].tagName === "A" ) {
5507                         !$el.hasClass( "ui-btn" ) && $el.buttonMarkup();
5508                         return;
5509                 }
5510
5511                 // get the inherited theme
5512                 // TODO centralize for all widgets
5513                 if ( !this.options.theme ) {
5514                         this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
5515                 }
5516
5517                 // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
5518                 /* if( $el[0].className.length ) {
5519                         classes = $el[0].className;
5520                 } */
5521                 if( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
5522                         classes = "ui-btn-left";
5523                 }
5524
5525                 if(  !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
5526                         classes = "ui-btn-right";
5527                 }
5528
5529                 if(  $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
5530                         classes ? classes += " ui-submit" :  classes = "ui-submit";
5531                 }
5532                 
5533                 $( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
5534
5535                 // Add ARIA role
5536                 this.button = $( "<div></div>" )
5537                         .text( $el.text() || $el.val() )
5538                         .insertBefore( $el )
5539                         .buttonMarkup({
5540                                 theme: o.theme,
5541                                 icon: o.icon,
5542                                 iconpos: o.iconpos,
5543                                 inline: o.inline,
5544                                 corners: o.corners,
5545                                 shadow: o.shadow,
5546                                 iconshadow: o.iconshadow,
5547                                 mini: o.mini
5548                         })
5549                         .addClass( classes )
5550                         .append( $el.addClass( "ui-btn-hidden" ) );
5551
5552         $button = this.button;
5553                 type = $el.attr( "type" );
5554                 name = $el.attr( "name" );
5555
5556                 // Add hidden input during submit if input type="submit" has a name.
5557                 if ( type !== "button" && type !== "reset" && name ) {
5558                                 $el.bind( "vclick", function() {
5559                                         // Add hidden input if it doesn't already exist.
5560                                         if( $buttonPlaceholder === undefined ) {
5561                                                 $buttonPlaceholder = $( "<input>", {
5562                                                         type: "hidden",
5563                                                         name: $el.attr( "name" ),
5564                                                         value: $el.attr( "value" )
5565                                                 }).insertBefore( $el );
5566
5567                                                 // Bind to doc to remove after submit handling
5568                                                 $( document ).one("submit", function(){
5569                                                         $buttonPlaceholder.remove();
5570
5571                                                         // reset the local var so that the hidden input
5572                                                         // will be re-added on subsequent clicks
5573                                                         $buttonPlaceholder = undefined;
5574                                                 });
5575                                         }
5576                                 });
5577                 }
5578
5579         $el.bind({
5580             focus: function() {
5581                 $button.addClass( $.mobile.focusClass );
5582             },
5583
5584             blur: function() {
5585                 $button.removeClass( $.mobile.focusClass );
5586             }
5587         });
5588
5589                 this.refresh();
5590         },
5591
5592         enable: function() {
5593                 this.element.attr( "disabled", false );
5594                 this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
5595                 return this._setOption( "disabled", false );
5596         },
5597
5598         disable: function() {
5599                 this.element.attr( "disabled", true );
5600                 this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
5601                 return this._setOption( "disabled", true );
5602         },
5603
5604         refresh: function() {
5605                 var $el = this.element;
5606
5607                 if ( $el.prop("disabled") ) {
5608                         this.disable();
5609                 } else {
5610                         this.enable();
5611                 }
5612
5613                 // Grab the button's text element from its implementation-independent data item
5614                 $( this.button.data( 'buttonElements' ).text ).text( $el.text() || $el.val() );
5615         }
5616 });
5617
5618 //auto self-init widgets
5619 $( document ).bind( "pagecreate create", function( e ){
5620         $.mobile.button.prototype.enhanceWithin( e.target, true );
5621 });
5622
5623 })( jQuery );
5624
5625 (function( $, undefined ) {
5626
5627 $.fn.controlgroup = function( options ) {
5628         function flipClasses( els, flCorners  ) {
5629                 els.removeClass( "ui-btn-corner-all ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-controlgroup-last ui-shadow" )
5630                         .eq( 0 ).addClass( flCorners[ 0 ] )
5631                         .end()
5632                         .last().addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" );
5633         }
5634
5635         return this.each(function() {
5636                 var $el = $( this ),
5637                         o = $.extend({
5638                                                 direction: $el.jqmData( "type" ) || "vertical",
5639                                                 shadow: false,
5640                                                 excludeInvisible: true,
5641                                                 mini: $el.jqmData( "mini" )
5642                                         }, options ),
5643                         groupheading = $el.children( "legend" ),
5644                         flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ],
5645                         type = $el.find( "input" ).first().attr( "type" );
5646                         
5647                 $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" );
5648
5649                 // Replace legend with more stylable replacement div
5650                 if ( groupheading.length ) {
5651                         $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) );
5652                         groupheading.remove();
5653                 }
5654
5655                 $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction );
5656
5657                 flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ).not('.ui-slider-handle'), flCorners );
5658                 flipClasses( $el.find( ".ui-btn-inner" ), flCorners );
5659
5660                 if ( o.shadow ) {
5661                         $el.addClass( "ui-shadow" );
5662                 }
5663
5664                 if ( o.mini ) {
5665                         $el.addClass( "ui-mini" );
5666                 }
5667
5668         });
5669 };
5670
5671 // The pagecreate handler for controlgroup is in jquery.mobile.init because of the soft-dependency on the wrapped widgets
5672
5673 })(jQuery);
5674
5675 (function( $, undefined ) {
5676
5677 $( document ).bind( "pagecreate create", function( e ){
5678
5679         //links within content areas, tests included with page
5680         $( e.target )
5681                 .find( "a" )
5682                 .jqmEnhanceable()
5683                 .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
5684                 .addClass( "ui-link" );
5685
5686 });
5687
5688 })( jQuery );
5689
5690
5691 ( function( $ ) {
5692         var     meta = $( "meta[name=viewport]" ),
5693         initialContent = meta.attr( "content" ),
5694         disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
5695         enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
5696                 disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
5697         
5698         $.mobile.zoom = $.extend( {}, {
5699                 enabled: !disabledInitially,
5700                 locked: false,
5701                 disable: function( lock ) {
5702                         if( !disabledInitially && !$.mobile.zoom.locked ){
5703                         meta.attr( "content", disabledZoom );
5704                         $.mobile.zoom.enabled = false;
5705                                 $.mobile.zoom.locked = lock || false;
5706                         }
5707                 },
5708                 enable: function( unlock ) {
5709                         if( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ){
5710                         meta.attr( "content", enabledZoom );
5711                         $.mobile.zoom.enabled = true;
5712                                 $.mobile.zoom.locked = false;
5713                         }
5714                 },
5715                 restore: function() {
5716                         if( !disabledInitially ){
5717                         meta.attr( "content", initialContent );
5718                         $.mobile.zoom.enabled = true;
5719                         }
5720                 }
5721         });
5722
5723 }( jQuery ));
5724
5725 (function( $, undefined ) {
5726
5727 $.widget( "mobile.textinput", $.mobile.widget, {
5728         options: {
5729                 theme: null,
5730                 // This option defaults to true on iOS devices.
5731                 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
5732                 initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type])",
5733                 clearSearchButtonText: "clear text"
5734         },
5735
5736         _create: function() {
5737
5738                 var input = this.element,
5739                         o = this.options,
5740                         theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
5741                         themeclass  = " ui-body-" + theme,
5742                         mini = input.jqmData("mini") == true,
5743                         miniclass = mini ? " ui-mini" : "",
5744                         focusedEl, clearbtn;
5745
5746                 $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
5747
5748                 focusedEl = input.addClass("ui-input-text ui-body-"+ theme );
5749
5750                 // XXX: Temporary workaround for issue 785 (Apple bug 8910589).
5751                 //      Turn off autocorrect and autocomplete on non-iOS 5 devices
5752                 //      since the popup they use can't be dismissed by the user. Note
5753                 //      that we test for the presence of the feature by looking for
5754                 //      the autocorrect property on the input element. We currently
5755                 //      have no test for iOS 5 or newer so we're temporarily using
5756                 //      the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
5757                 if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
5758                         // Set the attribute instead of the property just in case there
5759                         // is code that attempts to make modifications via HTML.
5760                         input[0].setAttribute( "autocorrect", "off" );
5761                         input[0].setAttribute( "autocomplete", "off" );
5762                 }
5763
5764
5765                 //"search" input widget
5766                 if ( input.is( "[type='search'],:jqmData(type='search')" ) ) {
5767
5768                         focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
5769                         clearbtn = $( "<a href='#' class='ui-input-clear' title='" + o.clearSearchButtonText + "'>" + o.clearSearchButtonText + "</a>" )
5770                                 .bind('click', function( event ) {
5771                                         input
5772                                                 .val( "" )
5773                                                 .focus()
5774                                                 .trigger( "change" );
5775                                         clearbtn.addClass( "ui-input-clear-hidden" );
5776                                         event.preventDefault();
5777                                 })
5778                                 .appendTo( focusedEl )
5779                                 .buttonMarkup({
5780                                         icon: "delete",
5781                                         iconpos: "notext",
5782                                         corners: true,
5783                                         shadow: true,
5784                                         mini: mini
5785                                 });
5786
5787                         function toggleClear() {
5788                                 setTimeout(function() {
5789                                         clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
5790                                 }, 0);
5791                         }
5792
5793                         toggleClear();
5794
5795                         input.bind('paste cut keyup focus change blur', toggleClear);
5796
5797                 } else {
5798                         input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
5799                 }
5800
5801                 input.focus(function() {
5802                                 focusedEl.addClass( $.mobile.focusClass );
5803                         })
5804                         .blur(function(){
5805                                 focusedEl.removeClass( $.mobile.focusClass );
5806                         })
5807                         // In many situations, iOS will zoom into the select upon tap, this prevents that from happening
5808                         .bind( "focus", function() {
5809                                 if( o.preventFocusZoom ){
5810                                         $.mobile.zoom.disable( true );
5811                                 }
5812                         })
5813                         .bind( "blur", function() {
5814                                 if( o.preventFocusZoom ){
5815                                         $.mobile.zoom.enable( true );
5816                                 }
5817                         });
5818
5819                 // Autogrow
5820                 if ( input.is( "textarea" ) ) {
5821                         var extraLineHeight = 15,
5822                                 keyupTimeoutBuffer = 100,
5823                                 keyup = function() {
5824                                         var scrollHeight = input[ 0 ].scrollHeight,
5825                                                 clientHeight = input[ 0 ].clientHeight;
5826
5827                                         if ( clientHeight < scrollHeight ) {
5828                                                 input.height(scrollHeight + extraLineHeight);
5829                                         }
5830                                 },
5831                                 keyupTimeout;
5832
5833                         input.keyup(function() {
5834                                 clearTimeout( keyupTimeout );
5835                                 keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer );
5836                         });
5837
5838                         // binding to pagechange here ensures that for pages loaded via
5839                         // ajax the height is recalculated without user input
5840                         $( document ).one( "pagechange", keyup );
5841
5842                         // Issue 509: the browser is not providing scrollHeight properly until the styles load
5843                         if ( $.trim( input.val() ) ) {
5844                                 // bind to the window load to make sure the height is calculated based on BOTH
5845                                 // the DOM and CSS
5846                                 $( window ).load( keyup );
5847                         }
5848                 }
5849         },
5850
5851         disable: function(){
5852                 ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ?
5853                         this.element.parent() : this.element ).addClass( "ui-disabled" );
5854         },
5855
5856         enable: function(){
5857                 ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ?
5858                         this.element.parent() : this.element ).removeClass( "ui-disabled" );
5859         }
5860 });
5861
5862 //auto self-init widgets
5863 $( document ).bind( "pagecreate create", function( e ){
5864         $.mobile.textinput.prototype.enhanceWithin( e.target, true );
5865 });
5866
5867 })( jQuery );
5868
5869 (function( $, undefined ) {
5870
5871 $.mobile.listview.prototype.options.filter = false;
5872 $.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
5873 $.mobile.listview.prototype.options.filterTheme = "c";
5874 $.mobile.listview.prototype.options.filterCallback = function( text, searchValue ){
5875         return text.toLowerCase().indexOf( searchValue ) === -1;
5876 };
5877
5878 $( document ).delegate( ":jqmData(role='listview')", "listviewcreate", function() {
5879
5880         var list = $( this ),
5881                 listview = list.data( "listview" );
5882
5883         if ( !listview.options.filter ) {
5884                 return;
5885         }
5886
5887         var wrapper = $( "<form>", {
5888                         "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
5889                         "role": "search"
5890                 }),
5891                 search = $( "<input>", {
5892                         placeholder: listview.options.filterPlaceholder
5893                 })
5894                 .attr( "data-" + $.mobile.ns + "type", "search" )
5895                 .jqmData( "lastval", "" )
5896                 .bind( "keyup change", function() {
5897
5898                         var $this = $(this),
5899                                 val = this.value.toLowerCase(),
5900                                 listItems = null,
5901                                 lastval = $this.jqmData( "lastval" ) + "",
5902                                 childItems = false,
5903                                 itemtext = "",
5904                                 item;
5905
5906                         // Change val as lastval for next execution
5907                         $this.jqmData( "lastval" , val );
5908                         if ( val.length < lastval.length || val.indexOf(lastval) !== 0 ) {
5909
5910                                 // Removed chars or pasted something totally different, check all items
5911                                 listItems = list.children();
5912                         } else {
5913
5914                                 // Only chars added, not removed, only use visible subset
5915                                 listItems = list.children( ":not(.ui-screen-hidden)" );
5916                         }
5917
5918                         if ( val ) {
5919
5920                                 // This handles hiding regular rows without the text we search for
5921                                 // and any list dividers without regular rows shown under it
5922
5923                                 for ( var i = listItems.length - 1; i >= 0; i-- ) {
5924                                         item = $( listItems[ i ] );
5925                                         itemtext = item.jqmData( "filtertext" ) || item.text();
5926
5927                                         if ( item.is( "li:jqmData(role=list-divider)" ) ) {
5928
5929                                                 item.toggleClass( "ui-filter-hidequeue" , !childItems );
5930
5931                                                 // New bucket!
5932                                                 childItems = false;
5933
5934                                         } else if ( listview.options.filterCallback( itemtext, val ) ) {
5935
5936                                                 //mark to be hidden
5937                                                 item.toggleClass( "ui-filter-hidequeue" , true );
5938                                         } else {
5939
5940                                                 // There's a shown item in the bucket
5941                                                 childItems = true;
5942                                         }
5943                                 }
5944
5945                                 // Show items, not marked to be hidden
5946                                 listItems
5947                                         .filter( ":not(.ui-filter-hidequeue)" )
5948                                         .toggleClass( "ui-screen-hidden", false );
5949
5950                                 // Hide items, marked to be hidden
5951                                 listItems
5952                                         .filter( ".ui-filter-hidequeue" )
5953                                         .toggleClass( "ui-screen-hidden", true )
5954                                         .toggleClass( "ui-filter-hidequeue", false );
5955
5956                         } else {
5957
5958                                 //filtervalue is empty => show all
5959                                 listItems.toggleClass( "ui-screen-hidden", false );
5960                         }
5961                         listview._refreshCorners();
5962                 })
5963                 .appendTo( wrapper )
5964                 .textinput();
5965
5966         if ( listview.options.inset ) {
5967                 wrapper.addClass( "ui-listview-filter-inset" );
5968         }
5969
5970         wrapper.bind( "submit", function() {
5971                 return false;
5972         })
5973         .insertBefore( list );
5974 });
5975
5976 })( jQuery );
5977
5978 ( function( $, undefined ) {
5979
5980 $.widget( "mobile.slider", $.mobile.widget, {
5981         options: {
5982                 theme: null,
5983                 trackTheme: null,
5984                 disabled: false,
5985                 initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
5986                 mini: false
5987         },
5988
5989         _create: function() {
5990
5991                 // TODO: Each of these should have comments explain what they're for
5992                 var self = this,
5993
5994                         control = this.element,
5995
5996                         parentTheme = $.mobile.getInheritedTheme( control, "c" ),
5997
5998                         theme = this.options.theme || parentTheme,
5999
6000                         trackTheme = this.options.trackTheme || parentTheme,
6001
6002                         cType = control[ 0 ].nodeName.toLowerCase(),
6003
6004                         selectClass = ( cType == "select" ) ? "ui-slider-switch" : "",
6005
6006                         controlID = control.attr( "id" ),
6007
6008                         $label = $( "[for='" + controlID + "']" ),
6009
6010                         labelID = $label.attr( "id" ) || controlID + "-label",
6011
6012                         label = $label.attr( "id", labelID ),
6013
6014                         val = function() {
6015                                 return  cType == "input"  ? parseFloat( control.val() ) : control[0].selectedIndex;
6016                         },
6017
6018                         min =  cType == "input" ? parseFloat( control.attr( "min" ) ) : 0,
6019
6020                         max =  cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
6021
6022                         step = window.parseFloat( control.attr( "step" ) || 1 ),
6023
6024                         inlineClass = ( this.options.inline || control.jqmData("inline") == true ) ? " ui-slider-inline" : "",
6025
6026                         miniClass = ( this.options.mini || control.jqmData("mini") ) ? " ui-slider-mini" : "",
6027
6028
6029                         domHandle = document.createElement('a'),
6030                         handle = $( domHandle ),
6031                         domSlider = document.createElement('div'),
6032                         slider = $( domSlider ),
6033
6034                         valuebg = control.jqmData("highlight") && cType != "select" ? (function() {
6035                                 var bg = document.createElement('div');
6036                                 bg.className = 'ui-slider-bg ' + $.mobile.activeBtnClass + ' ui-btn-corner-all';
6037                                 return $( bg ).prependTo( slider );
6038                         })() : false,
6039
6040                         options;
6041
6042         domHandle.setAttribute( 'href', "#" );
6043                 domSlider.setAttribute('role','application');
6044                 domSlider.className = ['ui-slider ',selectClass," ui-btn-down-",trackTheme,' ui-btn-corner-all', inlineClass, miniClass].join("");
6045                 domHandle.className = 'ui-slider-handle';
6046                 domSlider.appendChild(domHandle);
6047
6048                 handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
6049                                 .attr({
6050                                         "role": "slider",
6051                                         "aria-valuemin": min,
6052                                         "aria-valuemax": max,
6053                                         "aria-valuenow": val(),
6054                                         "aria-valuetext": val(),
6055                                         "title": val(),
6056                                         "aria-labelledby": labelID
6057                                 });
6058
6059                 $.extend( this, {
6060                         slider: slider,
6061                         handle: handle,
6062                         valuebg: valuebg,
6063                         dragging: false,
6064                         beforeStart: null,
6065                         userModified: false,
6066                         mouseMoved: false
6067                 });
6068
6069                 if ( cType == "select" ) {
6070                         var wrapper = document.createElement('div');
6071                         wrapper.className = 'ui-slider-inneroffset';
6072
6073                         for(var j = 0,length = domSlider.childNodes.length;j < length;j++){
6074                                 wrapper.appendChild(domSlider.childNodes[j]);
6075                         }
6076
6077                         domSlider.appendChild(wrapper);
6078
6079                         // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
6080
6081                         // make the handle move with a smooth transition
6082                         handle.addClass( "ui-slider-handle-snapping" );
6083
6084                         options = control.find( "option" );
6085
6086                         for(var i = 0, optionsCount = options.length; i < optionsCount; i++){
6087                                 var side = !i ? "b":"a",
6088                                         sliderTheme = !i ? " ui-btn-down-" + trackTheme :( " " + $.mobile.activeBtnClass ),
6089                                         sliderLabel = document.createElement('div'),
6090                                         sliderImg = document.createElement('span');
6091
6092                                 sliderImg.className = ['ui-slider-label ui-slider-label-',side,sliderTheme," ui-btn-corner-all"].join("");
6093                                 sliderImg.setAttribute('role','img');
6094                                 sliderImg.appendChild(document.createTextNode(options[i].innerHTML));
6095                                 $(sliderImg).prependTo( slider );
6096                         }
6097
6098                         self._labels = $( ".ui-slider-label", slider );
6099
6100                 }
6101
6102                 label.addClass( "ui-slider" );
6103
6104                 // monitor the input for updated values
6105                 control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" )
6106                         .change( function() {
6107                                 // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
6108                                 if (!self.mouseMoved) {
6109                                         self.refresh( val(), true );
6110                                 }
6111                         })
6112                         .keyup( function() { // necessary?
6113                                 self.refresh( val(), true, true );
6114                         })
6115                         .blur( function() {
6116                                 self.refresh( val(), true );
6117                         });
6118
6119                 // prevent screen drag when slider activated
6120                 $( document ).bind( "vmousemove", function( event ) {
6121                         if ( self.dragging ) {
6122                                 // self.mouseMoved must be updated before refresh() because it will be used in the control "change" event
6123                                 self.mouseMoved = true;
6124
6125                                 if ( cType === "select" ) {
6126                                         // make the handle move in sync with the mouse
6127                                         handle.removeClass( "ui-slider-handle-snapping" );
6128                                 }
6129
6130                                 self.refresh( event );
6131
6132                                 // only after refresh() you can calculate self.userModified
6133                                 self.userModified = self.beforeStart !== control[0].selectedIndex;
6134                                 return false;
6135                         }
6136                 });
6137
6138                 slider.bind( "vmousedown", function( event ) {
6139                         self.dragging = true;
6140                         self.userModified = false;
6141                         self.mouseMoved = false;
6142
6143                         if ( cType === "select" ) {
6144                                 self.beforeStart = control[0].selectedIndex;
6145                         }
6146
6147                         self.refresh( event );
6148                         return false;
6149                 })
6150                 .bind( "vclick", false );
6151
6152                 slider.add( document )
6153                         .bind( "vmouseup", function() {
6154                                 if ( self.dragging ) {
6155
6156                                         self.dragging = false;
6157
6158                                         if ( cType === "select") {
6159
6160                                                 // make the handle move with a smooth transition
6161                                                 handle.addClass( "ui-slider-handle-snapping" );
6162
6163                                                 if ( self.mouseMoved ) {
6164
6165                                                         // this is a drag, change the value only if user dragged enough
6166                                                         if ( self.userModified ) {
6167                                                                 self.refresh( self.beforeStart == 0 ? 1 : 0 );
6168                                                         }
6169                                                         else {
6170                                                                 self.refresh( self.beforeStart );
6171                                                         }
6172
6173                                                 }
6174                                                 else {
6175                                                         // this is just a click, change the value
6176                                                         self.refresh( self.beforeStart == 0 ? 1 : 0 );
6177                                                 }
6178
6179                                         }
6180
6181                                         self.mouseMoved = false;
6182
6183                                         return false;
6184                                 }
6185                         });
6186
6187                 slider.insertAfter( control );
6188
6189                 // Only add focus class to toggle switch, sliders get it automatically from ui-btn
6190                 if( cType == 'select' ) {
6191                         this.handle.bind({
6192                                 focus: function() {
6193                                         slider.addClass( $.mobile.focusClass );
6194                                 },
6195
6196                                 blur: function() {
6197                                         slider.removeClass( $.mobile.focusClass );
6198                                 }
6199                         });
6200                 }
6201
6202                 this.handle.bind({
6203                         // NOTE force focus on handle
6204                         vmousedown: function() {
6205                                 $( this ).focus();
6206                         },
6207
6208                         vclick: false,
6209
6210                         keydown: function( event ) {
6211                                 var index = val();
6212
6213                                 if ( self.options.disabled ) {
6214                                         return;
6215                                 }
6216
6217                                 // In all cases prevent the default and mark the handle as active
6218                                 switch ( event.keyCode ) {
6219                                         case $.mobile.keyCode.HOME:
6220                                         case $.mobile.keyCode.END:
6221                                         case $.mobile.keyCode.PAGE_UP:
6222                                         case $.mobile.keyCode.PAGE_DOWN:
6223                                         case $.mobile.keyCode.UP:
6224                                         case $.mobile.keyCode.RIGHT:
6225                                         case $.mobile.keyCode.DOWN:
6226                                         case $.mobile.keyCode.LEFT:
6227                                                 event.preventDefault();
6228
6229                                                 if ( !self._keySliding ) {
6230                                                         self._keySliding = true;
6231                                                         $( this ).addClass( "ui-state-active" );
6232                                                 }
6233                                                 break;
6234                                 }
6235
6236                                 // move the slider according to the keypress
6237                                 switch ( event.keyCode ) {
6238                                         case $.mobile.keyCode.HOME:
6239                                                 self.refresh( min );
6240                                                 break;
6241                                         case $.mobile.keyCode.END:
6242                                                 self.refresh( max );
6243                                                 break;
6244                                         case $.mobile.keyCode.PAGE_UP:
6245                                         case $.mobile.keyCode.UP:
6246                                         case $.mobile.keyCode.RIGHT:
6247                                                 self.refresh( index + step );
6248                                                 break;
6249                                         case $.mobile.keyCode.PAGE_DOWN:
6250                                         case $.mobile.keyCode.DOWN:
6251                                         case $.mobile.keyCode.LEFT:
6252                                                 self.refresh( index - step );
6253                                                 break;
6254                                 }
6255                         }, // remove active mark
6256
6257                         keyup: function( event ) {
6258                                 if ( self._keySliding ) {
6259                                         self._keySliding = false;
6260                                         $( this ).removeClass( "ui-state-active" );
6261                                 }
6262                         }
6263                         });
6264
6265                 this.refresh(undefined, undefined, true);
6266         },
6267
6268         refresh: function( val, isfromControl, preventInputUpdate ) {
6269
6270                 if ( this.options.disabled || this.element.attr('disabled')) {
6271                         this.disable();
6272                 }
6273
6274                 var control = this.element, percent,
6275                         cType = control[0].nodeName.toLowerCase(),
6276                         min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0,
6277                         max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1,
6278                         step = (cType === "input" && parseFloat( control.attr( "step" ) ) > 0) ? parseFloat(control.attr("step")) : 1;
6279
6280                 if ( typeof val === "object" ) {
6281                         var data = val,
6282                                 // a slight tolerance helped get to the ends of the slider
6283                                 tol = 8;
6284                         if ( !this.dragging ||
6285                                         data.pageX < this.slider.offset().left - tol ||
6286                                         data.pageX > this.slider.offset().left + this.slider.width() + tol ) {
6287                                 return;
6288                         }
6289                         percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 );
6290                 } else {
6291                         if ( val == null ) {
6292                                 val = cType === "input" ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
6293                         }
6294                         percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
6295                 }
6296
6297                 if ( isNaN( percent ) ) {
6298                         return;
6299                 }
6300
6301                 if ( percent < 0 ) {
6302                         percent = 0;
6303                 }
6304
6305                 if ( percent > 100 ) {
6306                         percent = 100;
6307                 }
6308
6309                 var newval = ( percent / 100 ) * ( max - min ) + min;
6310
6311                 //from jQuery UI slider, the following source will round to the nearest step
6312                 var valModStep = ( newval - min ) % step;
6313                 var alignValue = newval - valModStep;
6314
6315                 if ( Math.abs( valModStep ) * 2 >= step ) {
6316                         alignValue += ( valModStep > 0 ) ? step : ( -step );
6317                 }
6318                 // Since JavaScript has problems with large floats, round
6319                 // the final value to 5 digits after the decimal point (see jQueryUI: #4124)
6320                 newval = parseFloat( alignValue.toFixed(5) );
6321
6322                 if ( newval < min ) {
6323                         newval = min;
6324                 }
6325
6326                 if ( newval > max ) {
6327                         newval = max;
6328                 }
6329
6330                 this.handle.css( "left", percent + "%" );
6331                 this.handle.attr( {
6332                                 "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ),
6333                                 "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText(),
6334                                 title: cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText()
6335                         });
6336                 this.valuebg && this.valuebg.css( "width", percent + "%" );
6337
6338                 // drag the label widths
6339                 if ( this._labels ) {
6340                         var handlePercent = this.handle.width() / this.slider.width() * 100,
6341                                 aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
6342                                 bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
6343
6344                         this._labels.each(function(){
6345                                 var ab = $(this).is( ".ui-slider-label-a" );
6346                                 $( this ).width( ( ab ? aPercent : bPercent  ) + "%" );
6347                         });
6348                 }
6349
6350                 if ( !preventInputUpdate ) {
6351                         var valueChanged = false;
6352
6353                         // update control"s value
6354                         if ( cType === "input" ) {
6355                                 valueChanged = control.val() !== newval;
6356                                 control.val( newval );
6357                         } else {
6358                                 valueChanged = control[ 0 ].selectedIndex !== newval;
6359                                 control[ 0 ].selectedIndex = newval;
6360                         }
6361                         if ( !isfromControl && valueChanged ) {
6362                                 control.trigger( "change" );
6363                         }
6364                 }
6365         },
6366
6367         enable: function() {
6368                 this.element.attr( "disabled", false );
6369                 this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
6370                 return this._setOption( "disabled", false );
6371         },
6372
6373         disable: function() {
6374                 this.element.attr( "disabled", true );
6375                 this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
6376                 return this._setOption( "disabled", true );
6377         }
6378
6379 });
6380
6381 //auto self-init widgets
6382 $( document ).bind( "pagecreate create", function( e ){
6383         $.mobile.slider.prototype.enhanceWithin( e.target, true );
6384 });
6385
6386 })( jQuery );
6387
6388 (function( $, undefined ) {
6389
6390 $.widget( "mobile.selectmenu", $.mobile.widget, {
6391         options: {
6392                 theme: null,
6393                 disabled: false,
6394                 icon: "arrow-d",
6395                 iconpos: "right",
6396                 inline: false,
6397                 corners: true,
6398                 shadow: true,
6399                 iconshadow: true,
6400                 overlayTheme: "a",
6401                 hidePlaceholderMenuItems: true,
6402                 closeText: "Close",
6403                 nativeMenu: true,
6404                 // This option defaults to true on iOS devices.
6405                 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
6406                 initSelector: "select:not(:jqmData(role='slider'))",
6407                 mini: false
6408         },
6409
6410         _button: function(){
6411                 return $( "<div/>" );
6412         },
6413
6414         _setDisabled: function( value ) {
6415                 this.element.attr( "disabled", value );
6416                 this.button.attr( "aria-disabled", value );
6417                 return this._setOption( "disabled", value );
6418         },
6419
6420         _focusButton : function() {
6421                 var self = this;
6422
6423                 setTimeout( function() {
6424                         self.button.focus();
6425                 }, 40);
6426         },
6427
6428   _selectOptions: function() {
6429     return this.select.find( "option" );
6430   },
6431
6432         // setup items that are generally necessary for select menu extension
6433         _preExtension: function(){
6434                 var classes = "";
6435                 // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
6436                 /* if( $el[0].className.length ) {
6437                         classes = $el[0].className;
6438                 } */
6439                 if( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
6440                         classes =  " ui-btn-left";
6441                 }
6442                 
6443                 if(  !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
6444                         classes = " ui-btn-right";
6445                 }
6446                 
6447                 this.select = this.element.wrap( "<div class='ui-select" + classes + "'>" );
6448                 this.selectID  = this.select.attr( "id" );
6449                 this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
6450                 this.isMultiple = this.select[ 0 ].multiple;
6451                 if ( !this.options.theme ) {
6452                         this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
6453                 }
6454         },
6455
6456         _create: function() {
6457                 this._preExtension();
6458
6459                 // Allows for extension of the native select for custom selects and other plugins
6460                 // see select.custom for example extension
6461                 // TODO explore plugin registration
6462                 this._trigger( "beforeCreate" );
6463
6464                 this.button = this._button();
6465
6466                 var self = this,
6467
6468                         options = this.options,
6469
6470                         inline = options.inline || this.select.jqmData( "inline" ),
6471                         mini = options.mini || this.select.jqmData( "mini" ),                   
6472                         iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
6473
6474                         // IE throws an exception at options.item() function when
6475                         // there is no selected item
6476                         // select first in this case
6477                         selectedIndex = this.select[ 0 ].selectedIndex == -1 ? 0 : this.select[ 0 ].selectedIndex,
6478
6479                         // TODO values buttonId and menuId are undefined here
6480                         button = this.button
6481                                 .text( $( this.select[ 0 ].options.item( selectedIndex ) ).text() )
6482                                 .insertBefore( this.select )
6483                                 .buttonMarkup( {
6484                                         theme: options.theme,
6485                                         icon: options.icon,
6486                                         iconpos: iconpos,
6487                                         inline: inline,
6488                                         corners: options.corners,
6489                                         shadow: options.shadow,
6490                                         iconshadow: options.iconshadow,
6491                                         mini: mini
6492                                 });
6493
6494                 // Opera does not properly support opacity on select elements
6495                 // In Mini, it hides the element, but not its text
6496                 // On the desktop,it seems to do the opposite
6497                 // for these reasons, using the nativeMenu option results in a full native select in Opera
6498                 if ( options.nativeMenu && window.opera && window.opera.version ) {
6499                         button.addClass( "ui-select-nativeonly" );
6500                 }       
6501
6502                 // Add counter for multi selects
6503                 if ( this.isMultiple ) {
6504                         this.buttonCount = $( "<span>" )
6505                                 .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
6506                                 .hide()
6507                                 .appendTo( button.addClass('ui-li-has-count') );
6508                 }
6509
6510                 // Disable if specified
6511                 if ( options.disabled || this.element.attr('disabled')) {
6512                         this.disable();
6513                 }
6514
6515                 // Events on native select
6516                 this.select.change( function() {
6517                         self.refresh();
6518                 });
6519
6520                 this.build();
6521         },
6522
6523         build: function() {
6524                 var self = this;
6525
6526                 this.select
6527                         .appendTo( self.button )
6528                         .bind( "vmousedown", function() {
6529                                 // Add active class to button
6530                                 self.button.addClass( $.mobile.activeBtnClass );
6531                         })
6532             .bind( "focus", function() {
6533                 self.button.addClass( $.mobile.focusClass );
6534             })
6535             .bind( "blur", function() {
6536                 self.button.removeClass( $.mobile.focusClass );
6537             })
6538                         .bind( "focus vmouseover", function() {
6539                                 self.button.trigger( "vmouseover" );
6540                         })
6541                         .bind( "vmousemove", function() {
6542                                 // Remove active class on scroll/touchmove
6543                                 self.button.removeClass( $.mobile.activeBtnClass );
6544                         })
6545                         .bind( "change blur vmouseout", function() {
6546                                 self.button.trigger( "vmouseout" )
6547                                         .removeClass( $.mobile.activeBtnClass );
6548                         })
6549                         .bind( "change blur", function() {
6550                                 self.button.removeClass( "ui-btn-down-" + self.options.theme );
6551                         });
6552
6553                 // In many situations, iOS will zoom into the select upon tap, this prevents that from happening
6554                 self.button.bind( "vmousedown", function() {
6555                         if( self.options.preventFocusZoom ){
6556                                 $.mobile.zoom.disable( true );
6557                         }
6558                 })
6559                 .bind( "mouseup", function() {
6560                         if( self.options.preventFocusZoom ){
6561                                 $.mobile.zoom.enable( true );
6562                         }
6563                 });
6564         },
6565
6566         selected: function() {
6567                 return this._selectOptions().filter( ":selected" );
6568         },
6569
6570         selectedIndices: function() {
6571                 var self = this;
6572
6573                 return this.selected().map( function() {
6574                         return self._selectOptions().index( this );
6575                 }).get();
6576         },
6577
6578         setButtonText: function() {
6579                 var self = this, selected = this.selected();
6580
6581                 this.button.find( ".ui-btn-text" ).text( function() {
6582                         if ( !self.isMultiple ) {
6583                                 return selected.text();
6584                         }
6585
6586                         return selected.length ? selected.map( function() {
6587                                 return $( this ).text();
6588                         }).get().join( ", " ) : self.placeholder;
6589                 });
6590         },
6591
6592         setButtonCount: function() {
6593                 var selected = this.selected();
6594
6595                 // multiple count inside button
6596                 if ( this.isMultiple ) {
6597                         this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
6598                 }
6599         },
6600
6601         refresh: function() {
6602                 this.setButtonText();
6603                 this.setButtonCount();
6604         },
6605
6606         // open and close preserved in native selects
6607         // to simplify users code when looping over selects
6608         open: $.noop,
6609         close: $.noop,
6610
6611         disable: function() {
6612                 this._setDisabled( true );
6613                 this.button.addClass( "ui-disabled" );
6614         },
6615
6616         enable: function() {
6617                 this._setDisabled( false );
6618                 this.button.removeClass( "ui-disabled" );
6619         }
6620 });
6621
6622 //auto self-init widgets
6623 $( document ).bind( "pagecreate create", function( e ){
6624         $.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
6625 });
6626 })( jQuery );
6627
6628 /*
6629 * custom "selectmenu" plugin
6630 */
6631
6632 (function( $, undefined ) {
6633         var extendSelect = function( widget ){
6634
6635                 var select = widget.select,
6636                         selectID  = widget.selectID,
6637                         label = widget.label,
6638                         thisPage = widget.select.closest( ".ui-page" ),
6639                         screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"} ).appendTo( thisPage ),
6640                         selectOptions = widget._selectOptions(),
6641                         isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
6642                         buttonId = selectID + "-button",
6643                         menuId = selectID + "-menu",
6644                         menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
6645                                 "<div data-" + $.mobile.ns + "role='header'>" +
6646                                 "<div class='ui-title'>" + label.getEncodedText() + "</div>"+
6647                                 "</div>"+
6648                                 "<div data-" + $.mobile.ns + "role='content'></div>"+
6649                                 "</div>" ),
6650
6651                         listbox =  $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + widget.options.overlayTheme + " " + $.mobile.defaultDialogTransition } ).insertAfter(screen),
6652
6653                         list = $( "<ul>", {
6654                                 "class": "ui-selectmenu-list",
6655                                 "id": menuId,
6656                                 "role": "listbox",
6657                                 "aria-labelledby": buttonId
6658                         }).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ).appendTo( listbox ),
6659
6660                         header = $( "<div>", {
6661                                 "class": "ui-header ui-bar-" + widget.options.theme
6662                         }).prependTo( listbox ),
6663
6664                         headerTitle = $( "<h1>", {
6665                                 "class": "ui-title"
6666                         }).appendTo( header ),
6667
6668                         menuPageContent,
6669                         menuPageClose,
6670                         headerClose;
6671
6672                 if( widget.isMultiple ) {
6673                         headerClose = $( "<a>", {
6674                                 "text": widget.options.closeText,
6675                                 "href": "#",
6676                                 "class": "ui-btn-left"
6677                         }).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
6678                 }
6679
6680                 $.extend( widget, {
6681                         select: widget.select,
6682                         selectID: selectID,
6683                         buttonId: buttonId,
6684                         menuId: menuId,
6685                         thisPage: thisPage,
6686                         menuPage: menuPage,
6687                         label: label,
6688                         screen: screen,
6689                         selectOptions: selectOptions,
6690                         isMultiple: isMultiple,
6691                         theme: widget.options.theme,
6692                         listbox: listbox,
6693                         list: list,
6694                         header: header,
6695                         headerTitle: headerTitle,
6696                         headerClose: headerClose,
6697                         menuPageContent: menuPageContent,
6698                         menuPageClose: menuPageClose,
6699                         placeholder: "",
6700
6701                         build: function() {
6702                                 var self = this;
6703
6704                                 // Create list from select, update state
6705                                 self.refresh();
6706
6707                                 self.select.attr( "tabindex", "-1" ).focus(function() {
6708                                         $( this ).blur();
6709                                         self.button.focus();
6710                                 });
6711
6712                                 // Button events
6713                                 self.button.bind( "vclick keydown" , function( event ) {
6714                                         if ( event.type == "vclick" ||
6715                                                          event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER ||
6716                                                                                                                                         event.keyCode === $.mobile.keyCode.SPACE ) ) {
6717
6718                                                 self.open();
6719                                                 event.preventDefault();
6720                                         }
6721                                 });
6722
6723                                 // Events for list items
6724                                 self.list.attr( "role", "listbox" )
6725                                         .bind( "focusin", function( e ){
6726                                                 $( e.target )
6727                                                         .attr( "tabindex", "0" )
6728                                                         .trigger( "vmouseover" );
6729
6730                                         })
6731                                         .bind( "focusout", function( e ){
6732                                                 $( e.target )
6733                                                         .attr( "tabindex", "-1" )
6734                                                         .trigger( "vmouseout" );
6735                                         })
6736                                         .delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
6737
6738                                                 // index of option tag to be selected
6739                                                 var oldIndex = self.select[ 0 ].selectedIndex,
6740                                                         newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
6741                                                         option = self._selectOptions().eq( newIndex )[ 0 ];
6742
6743                                                 // toggle selected status on the tag for multi selects
6744                                                 option.selected = self.isMultiple ? !option.selected : true;
6745
6746                                                 // toggle checkbox class for multiple selects
6747                                                 if ( self.isMultiple ) {
6748                                                         $( this ).find( ".ui-icon" )
6749                                                                 .toggleClass( "ui-icon-checkbox-on", option.selected )
6750                                                                 .toggleClass( "ui-icon-checkbox-off", !option.selected );
6751                                                 }
6752
6753                                                 // trigger change if value changed
6754                                                 if ( self.isMultiple || oldIndex !== newIndex ) {
6755                                                         self.select.trigger( "change" );
6756                                                 }
6757
6758                                                 // hide custom select for single selects only - otherwise focus clicked item
6759                                                 // We need to grab the clicked item the hard way, because the list may have been rebuilt
6760                                                 if ( self.isMultiple ) {
6761                                                         self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
6762                                                                 .addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6763                                                 }
6764                                                 else {
6765                                                         self.close();
6766                                                 }
6767
6768                                                 event.preventDefault();
6769                                         })
6770                                         .keydown(function( event ) {  //keyboard events for menu items
6771                                                 var target = $( event.target ),
6772                                                         li = target.closest( "li" ),
6773                                                         prev, next;
6774
6775                                                 // switch logic based on which key was pressed
6776                                                 switch ( event.keyCode ) {
6777                                                         // up or left arrow keys
6778                                                  case 38:
6779                                                         prev = li.prev().not( ".ui-selectmenu-placeholder" );
6780
6781                                                         if( prev.is( ".ui-li-divider" ) ) {
6782                                                                 prev = prev.prev();
6783                                                         }
6784
6785                                                         // if there's a previous option, focus it
6786                                                         if ( prev.length ) {
6787                                                                 target
6788                                                                         .blur()
6789                                                                         .attr( "tabindex", "-1" );
6790
6791                                                                 prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6792                                                         }
6793
6794                                                         return false;
6795                                                         break;
6796
6797                                                         // down or right arrow keys
6798                                                  case 40:
6799                                                         next = li.next();
6800
6801                                                         if( next.is( ".ui-li-divider" ) ) {
6802                                                                 next = next.next();
6803                                                         }
6804
6805                                                         // if there's a next option, focus it
6806                                                         if ( next.length ) {
6807                                                                 target
6808                                                                         .blur()
6809                                                                         .attr( "tabindex", "-1" );
6810
6811                                                                 next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6812                                                         }
6813
6814                                                         return false;
6815                                                         break;
6816
6817                                                         // If enter or space is pressed, trigger click
6818                                                  case 13:
6819                                                  case 32:
6820                                                         target.trigger( "click" );
6821
6822                                                         return false;
6823                                                         break;
6824                                                 }
6825                                         });
6826
6827                                 // button refocus ensures proper height calculation
6828                                 // by removing the inline style and ensuring page inclusion
6829                                 self.menuPage.bind( "pagehide", function() {
6830                                         self.list.appendTo( self.listbox );
6831                                         self._focusButton();
6832
6833                                         // TODO centralize page removal binding / handling in the page plugin.
6834                                         // Suggestion from @jblas to do refcounting
6835                                         //
6836                                         // TODO extremely confusing dependency on the open method where the pagehide.remove
6837                                         // bindings are stripped to prevent the parent page from disappearing. The way
6838                                         // we're keeping pages in the DOM right now sucks
6839                                         //
6840                                         // rebind the page remove that was unbound in the open function
6841                                         // to allow for the parent page removal from actions other than the use
6842                                         // of a dialog sized custom select
6843                                         //
6844                                         // doing this here provides for the back button on the custom select dialog
6845                                         $.mobile._bindPageRemove.call( self.thisPage );
6846                                 });
6847
6848                                 // Events on "screen" overlay
6849                                 self.screen.bind( "vclick", function( event ) {
6850                                         self.close();
6851                                 });
6852
6853                                 // Close button on small overlays
6854                                 if( self.isMultiple ){
6855                                         self.headerClose.click( function() {
6856                                                 if ( self.menuType == "overlay" ) {
6857                                                         self.close();
6858                                                         return false;
6859                                                 }
6860                                         });
6861                                 }
6862
6863                                 // track this dependency so that when the parent page
6864                                 // is removed on pagehide it will also remove the menupage
6865                                 self.thisPage.addDependents( this.menuPage );
6866                         },
6867
6868                         _isRebuildRequired: function() {
6869                                 var list = this.list.find( "li" ),
6870                                         options = this._selectOptions();
6871
6872                                 // TODO exceedingly naive method to determine difference
6873                                 // ignores value changes etc in favor of a forcedRebuild
6874                                 // from the user in the refresh method
6875                                 return options.text() !== list.text();
6876                         },
6877
6878                         selected: function() {
6879                                 return this._selectOptions().filter( ":selected:not(:jqmData(placeholder='true'))" );
6880                         },
6881
6882                         refresh: function( forceRebuild , foo ){
6883                                 var self = this,
6884                                 select = this.element,
6885                                 isMultiple = this.isMultiple,
6886                                 indicies;
6887
6888                                 if (  forceRebuild || this._isRebuildRequired() ) {
6889                                         self._buildList();
6890                                 }
6891
6892                                 indicies = this.selectedIndices();
6893
6894                                 self.setButtonText();
6895                                 self.setButtonCount();
6896
6897                                 self.list.find( "li:not(.ui-li-divider)" )
6898                                         .removeClass( $.mobile.activeBtnClass )
6899                                         .attr( "aria-selected", false )
6900                                         .each(function( i ) {
6901
6902                                                 if ( $.inArray( i, indicies ) > -1 ) {
6903                                                         var item = $( this );
6904
6905                                                         // Aria selected attr
6906                                                         item.attr( "aria-selected", true );
6907
6908                                                         // Multiple selects: add the "on" checkbox state to the icon
6909                                                         if ( self.isMultiple ) {
6910                                                                 item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
6911                                                         } else {
6912                                                                 if( item.is( ".ui-selectmenu-placeholder" ) ) {
6913                                                                         item.next().addClass( $.mobile.activeBtnClass );
6914                                                                 } else {
6915                                                                         item.addClass( $.mobile.activeBtnClass );
6916                                                                 }
6917                                                         }
6918                                                 }
6919                                         });
6920                         },
6921
6922                         close: function() {
6923                                 if ( this.options.disabled || !this.isOpen ) {
6924                                         return;
6925                                 }
6926
6927                                 var self = this;
6928
6929                                 if ( self.menuType == "page" ) {
6930                                         // doesn't solve the possible issue with calling change page
6931                                         // where the objects don't define data urls which prevents dialog key
6932                                         // stripping - changePage has incoming refactor
6933                                         window.history.back();
6934                                 } else {
6935                                         self.screen.addClass( "ui-screen-hidden" );
6936                                         self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" );
6937                                         self.list.appendTo( self.listbox );
6938                                         self._focusButton();
6939                                 }
6940
6941                                 // allow the dialog to be closed again
6942                                 self.isOpen = false;
6943                         },
6944
6945                         open: function() {
6946                                 if ( this.options.disabled ) {
6947                                         return;
6948                                 }
6949
6950                                 var self = this,
6951           $window = $( window ),
6952           selfListParent = self.list.parent(),
6953                                         menuHeight = selfListParent.outerHeight(),
6954                                         menuWidth = selfListParent.outerWidth(),
6955                                         activePage = $( ".ui-page-active" ),
6956                                         tScrollElem = activePage,
6957                                         scrollTop = $window.scrollTop(),
6958                                         btnOffset = self.button.offset().top,
6959                                         screenHeight = $window.height(),
6960                                         screenWidth = $window.width();
6961
6962                                 //add active class to button
6963                                 self.button.addClass( $.mobile.activeBtnClass );
6964
6965                                 //remove after delay
6966                                 setTimeout( function() {
6967                                         self.button.removeClass( $.mobile.activeBtnClass );
6968                                 }, 300);
6969
6970                                 function focusMenuItem() {
6971                                         var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
6972                                         if ( selector.length === 0 ) {
6973                                                 selector = self.list.find( "li.ui-btn:not(:jqmData(placeholder='true')) a" );
6974                                         }
6975                                         selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
6976                                 }
6977
6978                                 if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
6979
6980                                         self.menuPage.appendTo( $.mobile.pageContainer ).page();
6981                                         self.menuPageContent = menuPage.find( ".ui-content" );
6982                                         self.menuPageClose = menuPage.find( ".ui-header a" );
6983
6984                                         // prevent the parent page from being removed from the DOM,
6985                                         // otherwise the results of selecting a list item in the dialog
6986                                         // fall into a black hole
6987                                         self.thisPage.unbind( "pagehide.remove" );
6988
6989                                         //for WebOS/Opera Mini (set lastscroll using button offset)
6990                                         if ( scrollTop == 0 && btnOffset > screenHeight ) {
6991                                                 self.thisPage.one( "pagehide", function() {
6992                                                         $( this ).jqmData( "lastScroll", btnOffset );
6993                                                 });
6994                                         }
6995
6996                                         self.menuPage.one( "pageshow", function() {
6997                                                 focusMenuItem();
6998                                                 self.isOpen = true;
6999                                         });
7000
7001                                         self.menuType = "page";
7002                                         self.menuPageContent.append( self.list );
7003                                         self.menuPage.find("div .ui-title").text(self.label.text());
7004                                         $.mobile.changePage( self.menuPage, {
7005                                                 transition: $.mobile.defaultDialogTransition
7006                                         });
7007                                 } else {
7008                                         self.menuType = "overlay";
7009
7010                                         self.screen.height( $(document).height() )
7011                                                 .removeClass( "ui-screen-hidden" );
7012
7013                                         // Try and center the overlay over the button
7014                                         var roomtop = btnOffset - scrollTop,
7015                                                 roombot = scrollTop + screenHeight - btnOffset,
7016                                                 halfheight = menuHeight / 2,
7017                                                 maxwidth = parseFloat( self.list.parent().css( "max-width" ) ),
7018                                                 newtop, newleft;
7019
7020                                         if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) {
7021                                                 newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight;
7022                                         } else {
7023                                                 // 30px tolerance off the edges
7024                                                 newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30;
7025                                         }
7026
7027                                         // If the menuwidth is smaller than the screen center is
7028                                         if ( menuWidth < maxwidth ) {
7029                                                 newleft = ( screenWidth - menuWidth ) / 2;
7030                                         } else {
7031
7032                                                 //otherwise insure a >= 30px offset from the left
7033                                                 newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2;
7034
7035                                                 // 30px tolerance off the edges
7036                                                 if ( newleft < 30 ) {
7037                                                         newleft = 30;
7038                                                 } else if ( (newleft + menuWidth) > screenWidth ) {
7039                                                         newleft = screenWidth - menuWidth - 30;
7040                                                 }
7041                                         }
7042
7043                                         self.listbox.append( self.list )
7044                                                 .removeClass( "ui-selectmenu-hidden" )
7045                                                 .css({
7046                                                         top: newtop,
7047                                                         left: newleft
7048                                                 })
7049                                                 .addClass( "in" );
7050
7051                                         focusMenuItem();
7052
7053                                         // duplicate with value set in page show for dialog sized selects
7054                                         self.isOpen = true;
7055                                 }
7056                         },
7057
7058                         _buildList: function() {
7059                                 var self = this,
7060                                         o = this.options,
7061                                         placeholder = this.placeholder,
7062                                         needPlaceholder = true,
7063                                         optgroups = [],
7064                                         lis = [],
7065                                         dataIcon = self.isMultiple ? "checkbox-off" : "false";
7066
7067                                 self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
7068
7069                                 var $options = self.select.find("option"),
7070                                         numOptions = $options.length,
7071                                         select = this.select[ 0 ],
7072                                         dataPrefix = 'data-' + $.mobile.ns,
7073                                         dataIndexAttr = dataPrefix + 'option-index',
7074                                         dataIconAttr = dataPrefix + 'icon',
7075                                         dataRoleAttr = dataPrefix + 'role',
7076                                         dataPlaceholderAttr = dataPrefix + 'placeholder',
7077                                         fragment = document.createDocumentFragment(),
7078                                         isPlaceholderItem = false,
7079                                         optGroup;
7080
7081                                 for (var i = 0; i < numOptions;i++, isPlaceholderItem = false){
7082                                         var option = $options[i],
7083                                                 $option = $(option),
7084                                                 parent = option.parentNode,
7085                                                 text = $option.text(),
7086                                                 anchor  = document.createElement('a'),
7087                                                 classes = [];
7088
7089                                         anchor.setAttribute('href','#');
7090                                         anchor.appendChild(document.createTextNode(text));
7091
7092                                         // Are we inside an optgroup?
7093                                         if (parent !== select && parent.nodeName.toLowerCase() === "optgroup"){
7094                                                 var optLabel = parent.getAttribute('label');
7095                                                 if ( optLabel != optGroup) {
7096                                                         var divider = document.createElement('li');
7097                                                         divider.setAttribute(dataRoleAttr,'list-divider');
7098                                                         divider.setAttribute('role','option');
7099                                                         divider.setAttribute('tabindex','-1');
7100                                                         divider.appendChild(document.createTextNode(optLabel));
7101                                                         fragment.appendChild(divider);
7102                                                         optGroup = optLabel;
7103                                                 }
7104                                         }
7105
7106                                         if (needPlaceholder && (!option.getAttribute( "value" ) || text.length == 0 || $option.jqmData( "placeholder" ))) {
7107                                                 needPlaceholder = false;
7108                                                 isPlaceholderItem = true;
7109
7110                                                 // If we have identified a placeholder, mark it retroactively in the select as well
7111                                                 option.setAttribute( dataPlaceholderAttr, true );
7112                                                 if ( o.hidePlaceholderMenuItems ) {
7113                                                         classes.push( "ui-selectmenu-placeholder" );
7114                                                 }
7115                                                 if (!placeholder) {
7116                                                         placeholder = self.placeholder = text;
7117                                                 }
7118                                         }
7119
7120                                         var item = document.createElement('li');
7121                                         if ( option.disabled ) {
7122                                                 classes.push( "ui-disabled" );
7123                                                 item.setAttribute('aria-disabled',true);
7124                                         }
7125                                         item.setAttribute(dataIndexAttr,i);
7126                                         item.setAttribute(dataIconAttr,dataIcon);
7127                                         if ( isPlaceholderItem ) {
7128                                                 item.setAttribute( dataPlaceholderAttr, true );
7129                                         }
7130                                         item.className = classes.join(" ");
7131                                         item.setAttribute('role','option');
7132                                         anchor.setAttribute('tabindex','-1');
7133                                         item.appendChild(anchor);
7134                                         fragment.appendChild(item);
7135                                 }
7136
7137                                 self.list[0].appendChild(fragment);
7138
7139                                 // Hide header if it's not a multiselect and there's no placeholder
7140                                 if ( !this.isMultiple && !placeholder.length ) {
7141                                         this.header.hide();
7142                                 } else {
7143                                         this.headerTitle.text( this.placeholder );
7144                                 }
7145
7146                                 // Now populated, create listview
7147                                 self.list.listview();
7148                         },
7149
7150                         _button: function(){
7151                                 return $( "<a>", {
7152                                         "href": "#",
7153                                         "role": "button",
7154                                         // TODO value is undefined at creation
7155                                         "id": this.buttonId,
7156                                         "aria-haspopup": "true",
7157
7158                                         // TODO value is undefined at creation
7159                                         "aria-owns": this.menuId
7160                                 });
7161                         }
7162                 });
7163         };
7164
7165         // issue #3894 - core doesn't triggered events on disabled delegates
7166         $( document ).bind( "selectmenubeforecreate", function( event ){
7167                 var selectmenuWidget = $( event.target ).data( "selectmenu" );
7168
7169                 if( !selectmenuWidget.options.nativeMenu ){
7170                         extendSelect( selectmenuWidget );
7171                 }
7172         });
7173 })( jQuery );
7174
7175 (function( $, undefined ) {
7176
7177
7178         $.widget( "mobile.fixedtoolbar", $.mobile.widget, {
7179                 options: {
7180                         visibleOnPageShow: true,
7181                         disablePageZoom: true,
7182                         transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
7183                         fullscreen: false,
7184                         tapToggle: true,
7185                         tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed",
7186                         hideDuringFocus: "input, textarea, select",
7187                         updatePagePadding: true,
7188                         trackPersistentToolbars: true,
7189
7190                         // Browser detection! Weeee, here we go...
7191                         // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
7192                         // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
7193                         // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
7194                         // The following function serves to rule out some popular browsers with known fixed-positioning issues
7195                         // This is a plugin option like any other, so feel free to improve or overwrite it
7196                         supportBlacklist: function(){
7197                                 var w = window,
7198                                         ua = navigator.userAgent,
7199                                         platform = navigator.platform,
7200                                         // Rendering engine is Webkit, and capture major version
7201                                         wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
7202                                         wkversion = !!wkmatch && wkmatch[ 1 ],
7203                                         ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
7204                                         ffversion = !!ffmatch && ffmatch[ 1 ],
7205                                         operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
7206                                         omversion = !!operammobilematch && operammobilematch[ 1 ];
7207
7208                                 if(
7209                                         // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
7210                                         ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1  || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 )
7211                                         ||
7212                                         // Opera Mini
7213                                         ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" )
7214                                         ||
7215                                         ( operammobilematch && omversion < 7458 )
7216                                         ||
7217                                         //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
7218                                         ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 )
7219                                         ||
7220                                         // Firefox Mobile before 6.0 -
7221                                         ( ffversion && ffversion < 6 )
7222                                         ||
7223                                         // WebOS less than 3
7224                                         ( "palmGetResource" in window && wkversion && wkversion < 534 )
7225                                         ||
7226                                         // MeeGo
7227                                         ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 )
7228                                 ){
7229                                         return true;
7230                                 }
7231
7232                                 return false;
7233                         },
7234                         initSelector: ":jqmData(position='fixed')"
7235                 },
7236
7237                 _create: function() {
7238
7239                         var self = this,
7240                                 o = self.options,
7241                                 $el = self.element,
7242                                 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
7243                                 $page = $el.closest(".ui-page");
7244
7245                         // Feature detecting support for
7246                         if( o.supportBlacklist() ){
7247                                 self.destroy();
7248                                 return;
7249                         }
7250
7251                         $el.addClass( "ui-"+ tbtype +"-fixed" );
7252
7253                         // "fullscreen" overlay positioning
7254                         if( o.fullscreen ){
7255                                 $el.addClass( "ui-"+ tbtype +"-fullscreen" );
7256                                 $page.addClass( "ui-page-" + tbtype + "-fullscreen" );
7257                         }
7258                         // If not fullscreen, add class to page to set top or bottom padding
7259                         else{
7260                                 $page.addClass( "ui-page-" + tbtype + "-fixed" );
7261                         }
7262
7263                         self._addTransitionClass();
7264                         self._bindPageEvents();
7265                         self._bindToggleHandlers();
7266                 },
7267
7268                 _addTransitionClass: function(){
7269                         var tclass = this.options.transition;
7270
7271                         if( tclass && tclass !== "none" ){
7272                                 // use appropriate slide for header or footer
7273                                 if( tclass === "slide" ){
7274                                         tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
7275                                 }
7276
7277                                 this.element.addClass( tclass );
7278                         }
7279                 },
7280
7281                 _bindPageEvents: function(){
7282                         var self = this,
7283                                 o = self.options,
7284                                 $el = self.element;
7285
7286                         //page event bindings
7287                         // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
7288                         // This method is meant to disable zoom while a fixed-positioned toolbar page is visible
7289                         $el.closest( ".ui-page" )
7290                                 .bind( "pagebeforeshow", function(){
7291                                         if( o.disablePageZoom ){
7292                                                 $.mobile.zoom.disable( true );
7293                                         }
7294                                         if( !o.visibleOnPageShow ){
7295                                                 self.hide( true );
7296                                         }
7297                                 } )
7298                                 .bind( "webkitAnimationStart animationstart updatelayout", function(){
7299                                         var thisPage = this;
7300                                         if( o.updatePagePadding ){
7301                                                 self.updatePagePadding( thisPage );
7302                                         }
7303                                 })
7304                                 .bind( "pageshow", function(){
7305                                         var thisPage = this;
7306                                         self.updatePagePadding( thisPage );
7307                                         if( o.updatePagePadding ){
7308                                                 $( window ).bind( "throttledresize." + self.widgetName, function(){
7309                                                         self.updatePagePadding( thisPage );
7310                                                 });
7311                                         }
7312                                 })
7313                                 .bind( "pagebeforehide", function( e, ui ){
7314                                         if( o.disablePageZoom ){
7315                                                 $.mobile.zoom.enable( true );
7316                                         }
7317                                         if( o.updatePagePadding ){
7318                                                 $( window ).unbind( "throttledresize." + self.widgetName );
7319                                         }
7320
7321                                         if( o.trackPersistentToolbars ){
7322                                                 var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this ),
7323                                                         thisHeader = $( ".ui-header-fixed:jqmData(id)", this ),
7324                                                         nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ),
7325                                                         nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage );
7326
7327                                                 nextFooter = nextFooter || $();
7328
7329                                                         if( nextFooter.length || nextHeader.length ){
7330
7331                                                                 nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
7332
7333                                                                 ui.nextPage.one( "pageshow", function(){
7334                                                                         nextFooter.add( nextHeader ).appendTo( this );
7335                                                                 });
7336                                                         }
7337                                         }
7338                                 });
7339                 },
7340
7341                 _visible: true,
7342
7343                 // This will set the content element's top or bottom padding equal to the toolbar's height
7344                 updatePagePadding: function( tbPage ) {
7345                         var $el = this.element,
7346                                 header = $el.is( ".ui-header" );
7347
7348                         // This behavior only applies to "fixed", not "fullscreen"
7349                         if( this.options.fullscreen ){ return; }
7350
7351                         tbPage = tbPage || $el.closest( ".ui-page" );
7352                         $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() );
7353                 },
7354                 
7355                 _useTransition: function( notransition ){
7356                         var $win = $( window ),
7357                                 $el = this.element,
7358                                 scroll = $win.scrollTop(),
7359                                 elHeight = $el.height(),
7360                                 pHeight = $el.closest( ".ui-page" ).height(),
7361                                 viewportHeight = $.mobile.getScreenHeight(),
7362                                 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
7363                                 
7364                         return !notransition &&
7365                                 ( this.options.transition && this.options.transition !== "none" &&
7366                                 (
7367                                         ( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
7368                                         ( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
7369                                 ) || this.options.fullscreen
7370                                 );
7371                 },
7372
7373                 show: function( notransition ){
7374                         var hideClass = "ui-fixed-hidden",
7375                                 $el = this.element;
7376
7377                                 if( this._useTransition( notransition ) ){
7378                                 $el
7379                                         .removeClass( "out " + hideClass )
7380                                         .addClass( "in" );
7381                         }
7382                         else {
7383                                 $el.removeClass( hideClass );
7384                         }
7385                         this._visible = true;
7386                 },
7387
7388                 hide: function( notransition ){
7389                         var hideClass = "ui-fixed-hidden",
7390                                 $el = this.element,
7391                                 // if it's a slide transition, our new transitions need the reverse class as well to slide outward
7392                                 outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
7393
7394                         if( this._useTransition( notransition ) ){
7395                                 $el
7396                                         .addClass( outclass )
7397                                         .removeClass( "in" )
7398                                         .animationComplete( function(){
7399                                                 $el.addClass( hideClass ).removeClass( outclass );
7400                                         });
7401                         }
7402                         else {
7403                                 $el.addClass( hideClass ).removeClass( outclass );
7404                         }
7405                         this._visible = false;
7406                 },
7407
7408                 toggle: function(){
7409                         this[ this._visible ? "hide" : "show" ]();
7410                 },
7411
7412                 _bindToggleHandlers: function(){
7413                         var self = this,
7414                                 o = self.options,
7415                                 $el = self.element;
7416
7417                         // tap toggle
7418                         $el.closest( ".ui-page" )
7419                                 .bind( "vclick", function( e ){
7420                                         if( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ){
7421                                                 self.toggle();
7422                                         }
7423                                 })
7424                                 .bind( "focusin focusout", function( e ){
7425                                         if( screen.width < 500 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ){
7426                                                 self[ ( e.type === "focusin" && self._visible ) ? "hide" : "show" ]();
7427                                         }
7428                                 });
7429                 },
7430
7431                 destroy: function(){
7432                         this.element.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
7433                         this.element.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
7434                 }
7435
7436         });
7437
7438         //auto self-init widgets
7439         $( document )
7440                 .bind( "pagecreate create", function( e ){
7441                         
7442                         // DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
7443                         // This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
7444                         if( $( e.target ).jqmData( "fullscreen" ) ){
7445                                 $( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
7446                         }
7447                         
7448                         $.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
7449                 });
7450
7451 })( jQuery );
7452
7453 ( function( $, window ) {
7454         
7455         // This fix addresses an iOS bug, so return early if the UA claims it's something else.
7456         if( !(/iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){
7457                 return;
7458         }
7459         
7460     var zoom = $.mobile.zoom,
7461                 evt, x, y, z, aig;
7462         
7463     function checkTilt( e ){
7464                 evt = e.originalEvent;
7465                 aig = evt.accelerationIncludingGravity;
7466                 
7467                 x = Math.abs( aig.x );
7468                 y = Math.abs( aig.y );
7469                 z = Math.abs( aig.z );
7470                                 
7471                 // If portrait orientation and in one of the danger zones
7472         if( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
7473                         if( zoom.enabled ){
7474                                 zoom.disable();
7475                         }               
7476         }
7477                 else if( !zoom.enabled ){
7478                         zoom.enable();
7479         }
7480     }
7481
7482     $( window )
7483                 .bind( "orientationchange.iosorientationfix", zoom.enable )
7484                 .bind( "devicemotion.iosorientationfix", checkTilt );
7485
7486 }( jQuery, this ));
7487
7488 ( function( $, window, undefined ) {
7489         var     $html = $( "html" ),
7490                         $head = $( "head" ),
7491                         $window = $( window );
7492
7493         // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
7494         $( window.document ).trigger( "mobileinit" );
7495
7496         // support conditions
7497         // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
7498         // otherwise, proceed with the enhancements
7499         if ( !$.mobile.gradeA() ) {
7500                 return;
7501         }
7502
7503         // override ajaxEnabled on platforms that have known conflicts with hash history updates
7504         // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
7505         if ( $.mobile.ajaxBlacklist ) {
7506                 $.mobile.ajaxEnabled = false;
7507         }
7508
7509         // Add mobile, initial load "rendering" classes to docEl
7510         $html.addClass( "ui-mobile ui-mobile-rendering" );
7511
7512         // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
7513         // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
7514         setTimeout( hideRenderingClass, 5000 );
7515
7516         // loading div which appears during Ajax requests
7517         // will not appear if $.mobile.loadingMessage is false
7518         var loaderClass = "ui-loader",
7519                 $loader = $( "<div class='" + loaderClass + "'><span class='ui-icon ui-icon-loading'></span><h1></h1></div>" );
7520
7521         // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
7522         function fakeFixLoader(){
7523                 var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
7524
7525                 $loader
7526                         .css({
7527                                 top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
7528                                 activeBtn.length && activeBtn.offset().top || 100
7529                         });
7530         }
7531
7532         // check position of loader to see if it appears to be "fixed" to center
7533         // if not, use abs positioning
7534         function checkLoaderPosition(){
7535                 var offset = $loader.offset(),
7536                         scrollTop = $window.scrollTop(),
7537                         screenHeight = $.mobile.getScreenHeight();
7538
7539                 if( offset.top < scrollTop || (offset.top - scrollTop) > screenHeight ) {
7540                         $loader.addClass( "ui-loader-fakefix" );
7541                         fakeFixLoader();
7542                         $window
7543                                 .unbind( "scroll", checkLoaderPosition )
7544                                 .bind( "scroll", fakeFixLoader );
7545                 }
7546         }
7547
7548         //remove initial build class (only present on first pageshow)
7549         function hideRenderingClass(){
7550                 $html.removeClass( "ui-mobile-rendering" );
7551         }
7552
7553         $.extend($.mobile, {
7554                 // turn on/off page loading message.
7555                 showPageLoadingMsg: function( theme, msgText, textonly ) {
7556                         $html.addClass( "ui-loading" );
7557
7558                         if ( $.mobile.loadingMessage ) {
7559                                 // text visibility from argument takes priority
7560                                 var textVisible = textonly || $.mobile.loadingMessageTextVisible;
7561
7562                                 theme = theme || $.mobile.loadingMessageTheme,
7563
7564                                 $loader
7565                                         .attr( "class", loaderClass + " ui-corner-all ui-body-" + ( theme || "a" ) + " ui-loader-" + ( textVisible ? "verbose" : "default" ) + ( textonly ? " ui-loader-textonly" : "" ) )
7566                                         .find( "h1" )
7567                                                 .text( msgText || $.mobile.loadingMessage )
7568                                                 .end()
7569                                         .appendTo( $.mobile.pageContainer );
7570
7571                                 checkLoaderPosition();
7572                                 $window.bind( "scroll", checkLoaderPosition );
7573                         }
7574                 },
7575
7576                 hidePageLoadingMsg: function() {
7577                         $html.removeClass( "ui-loading" );
7578
7579                         if( $.mobile.loadingMessage ){
7580                                 $loader.removeClass( "ui-loader-fakefix" );
7581                         }
7582
7583                         $( window ).unbind( "scroll", fakeFixLoader );
7584                         $( window ).unbind( "scroll", checkLoaderPosition );
7585                 },
7586
7587                 // find and enhance the pages in the dom and transition to the first page.
7588                 initializePage: function() {
7589                         // find present pages
7590                         var $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" );
7591
7592                         // if no pages are found, create one with body's inner html
7593                         if ( !$pages.length ) {
7594                                 $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
7595                         }
7596
7597                         // add dialogs, set data-url attrs
7598                         $pages.each(function() {
7599                                 var $this = $(this);
7600
7601                                 // unless the data url is already set set it to the pathname
7602                                 if ( !$this.jqmData("url") ) {
7603                                         $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
7604                                 }
7605                         });
7606
7607                         // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
7608                         $.mobile.firstPage = $pages.first();
7609
7610                         // define page container
7611                         $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" );
7612
7613                         // alert listeners that the pagecontainer has been determined for binding
7614                         // to events triggered on it
7615                         $window.trigger( "pagecontainercreate" );
7616
7617                         // cue page loading message
7618                         $.mobile.showPageLoadingMsg();
7619
7620                         //remove initial build class (only present on first pageshow)
7621                         hideRenderingClass();
7622
7623                         // if hashchange listening is disabled, there's no hash deeplink,
7624                         // the hash is not valid (contains more than one # or does not start with #)
7625                         // or there is no page with that hash, change to the first page in the DOM
7626                         // Remember, however, that the hash can also be a path!
7627                         if ( ! ( $.mobile.hashListeningEnabled &&
7628                                  $.mobile.path.isHashValid( location.hash ) &&
7629                                  ( $( location.hash + ':jqmData(role="page")' ).length ||
7630                                    $.mobile.path.isPath( location.hash ) ) ) ) {
7631                                 $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } );
7632                         }
7633                         // otherwise, trigger a hashchange to load a deeplink
7634                         else {
7635                                 $window.trigger( "hashchange", [ true ] );
7636                         }
7637                 }
7638         });
7639
7640         // initialize events now, after mobileinit has occurred
7641         $.mobile.navreadyDeferred.resolve();
7642
7643         // check which scrollTop value should be used by scrolling to 1 immediately at domready
7644         // then check what the scroll top is. Android will report 0... others 1
7645         // note that this initial scroll won't hide the address bar. It's just for the check.
7646         $(function() {
7647                 window.scrollTo( 0, 1 );
7648
7649                 // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
7650                 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
7651                 // so if it's 1, use 0 from now on
7652                 $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1;
7653
7654
7655                 // TODO: Implement a proper registration mechanism with dependency handling in order to not have exceptions like the one below
7656                 //auto self-init widgets for those widgets that have a soft dependency on others
7657                 if ( $.fn.controlgroup ) {
7658                         $( document ).bind( "pagecreate create", function( e ){
7659                                 $( ":jqmData(role='controlgroup')", e.target )
7660                                         .jqmEnhanceable()
7661                                         .controlgroup({ excludeInvisible: false });
7662                         });
7663                 }
7664
7665                 //dom-ready inits
7666                 if( $.mobile.autoInitializePage ){
7667                         $.mobile.initializePage();
7668                 }
7669
7670                 // window load event
7671                 // hide iOS browser chrome on load
7672                 $window.load( $.mobile.silentScroll );
7673
7674                 if ( !$.support.cssPointerEvents ) {
7675                         // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
7676                         // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
7677                         // https://github.com/jquery/jquery-mobile/issues/3558
7678
7679                         $( document ).delegate( ".ui-disabled", "vclick",
7680                                 function( e ) {
7681                                         e.preventDefault();
7682                                         e.stopImmediatePropagation();
7683                                 }
7684                         );
7685                 }
7686         });
7687 }( jQuery, this ));
7688
7689
7690 }));