Full Code of defunkt/jquery-pjax for AI

master 153262eda33e cached
43 files
956.5 KB
274.8k tokens
281 symbols
1 requests
Download .txt
Showing preview only (986K chars total). Download the full file or copy to clipboard to get everything.
Repository: defunkt/jquery-pjax
Branch: master
Commit: 153262eda33e
Files: 43
Total size: 956.5 KB

Directory structure:
gitextract_1662e_mz/

├── .eslintrc
├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── Gemfile
├── LICENSE
├── README.md
├── bower.json
├── jquery.pjax.js
├── package.json
├── script/
│   ├── bootstrap
│   ├── server
│   └── test
├── test/
│   ├── app.rb
│   ├── evaled.js
│   ├── run-qunit.js
│   ├── unit/
│   │   ├── fn_pjax.js
│   │   ├── helpers.js
│   │   ├── pjax.js
│   │   └── pjax_fallback.js
│   └── views/
│       ├── aliens.erb
│       ├── anchor.erb
│       ├── boom.erb
│       ├── boom_sans_pjax.erb
│       ├── dinosaurs.erb
│       ├── double_title.erb
│       ├── empty.erb
│       ├── env.erb
│       ├── fragment.erb
│       ├── hello.erb
│       ├── home.erb
│       ├── layout.erb
│       ├── long.erb
│       ├── nested_title.erb
│       ├── qunit.erb
│       ├── referer.erb
│       ├── scripts.erb
│       └── timeout.erb
└── vendor/
    ├── jquery-1.12.js
    ├── jquery-2.2.js
    ├── jquery-3.2.js
    ├── qunit.css
    └── qunit.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .eslintrc
================================================
{ "extends": "eslint:recommended",
  "env": {
    "browser": true,
    "jquery": true
  },
  "rules": {
    "eqeqeq": "warn",
    "no-eval": "error",
    "no-extra-parens": "error",
    "no-implicit-globals": "error",
    "no-trailing-spaces": "error",
    "no-unused-expressions": "error",
    "semi": ["error", "never"]
  }
}


================================================
FILE: .gitignore
================================================
node_modules/


================================================
FILE: .travis.yml
================================================
sudo: false
language: node_js
node_js: "6"
before_script: script/bootstrap

notifications:
  email: false
deploy:
  provider: npm
  email: mislav.marohnic@gmail.com
  api_key:
    secure: nstPtsdxAHGPkKl2wOnMW4FXHg1nKxG/yCYQYqiC61JqhbfSaZFVjIQrdH+9GSel7F/K7VLwGZwSVgfiWUymWeEsNw8R/cyI9xCXf5iNF6WHIwuX6Q3Tnvb3Cx/bkeoc8+4v7qR172FtzwKWJq2iKXawd58/4zf2sduOwld1PMw=
  on:
    tags: true
    repo: defunkt/jquery-pjax


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

For running the tests, you will need:

* Ruby 1.9.3+ with Bundler
* PhantomJS (for headless testing)

First run bootstrap to ensure necessary dependencies:

```
$ script/bootstrap
```

Then run headless tests in the console:

```
$ script/test [<test-file>]
```

To run tests in other browsers, start a server:

```
$ script/server
# now open http://localhost:4567/
```

## Test structure

There are 3 main test modules:

* `test/unit/fn_pjax.js` - Primarily tests the `$.fn.pjax` method and its options
* `test/unit/pjax.js` - Main comprehensive pjax functionality tests
* `test/unit/pjax_fallback.js` - Tests that verify same result after navigation
  even if pjax is disabled (like for browsers that don't support pushState).

Each test drives a hidden test page in an `<iframe>`. See other tests to see how
they trigger pjax by using the `frame` reference and remember to do so as well.


================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'

gem 'sinatra'


================================================
FILE: LICENSE
================================================
Copyright (c) Chris Wanstrath

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Software), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: README.md
================================================
# pjax = pushState + ajax

pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.

pjax works by fetching HTML from your server via ajax and replacing the content
of a container element on your page with the loaded HTML. It then updates the
current URL in the browser using pushState. This results in faster page
navigation for two reasons:

* No page resources (JS, CSS) get re-executed or re-applied;
* If the server is configured for pjax, it can render only partial page
  contents and thus avoid the potentially costly full layout render.

### Status of this project

jquery-pjax is **largely unmaintained** at this point. It might continue to
receive important bug fixes, but _its feature set is frozen_ and it's unlikely
that it will get new features or enhancements.

## Installation

pjax depends on jQuery 1.8 or higher.

### npm

```
$ npm install jquery-pjax
```

### standalone script

Download and include `jquery.pjax.js` in your web page:

```
curl -LO https://raw.github.com/defunkt/jquery-pjax/master/jquery.pjax.js
```

## Usage

### `$.fn.pjax`

The simplest and most common use of pjax looks like this:

``` javascript
$(document).pjax('a', '#pjax-container')
```

This will enable pjax on all links on the page and designate the container as `#pjax-container`.

If you are migrating an existing site, you probably don't want to enable pjax
everywhere just yet. Instead of using a global selector like `a`, try annotating
pjaxable links with `data-pjax`, then use `'a[data-pjax]'` as your selector. Or,
try this selector that matches any `<a data-pjax href=>` links inside a `<div
data-pjax>` container:

``` javascript
$(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container')
```

#### Server-side configuration

Ideally, your server should detect pjax requests by looking at the special
`X-PJAX` HTTP header, and render only the HTML meant to replace the contents of
the container element (`#pjax-container` in our example) without the rest of
the page layout. Here is an example of how this might be done in Ruby on Rails:

``` ruby
def index
  if request.headers['X-PJAX']
    render :layout => false
  end
end
```

If you'd like a more automatic solution than pjax for Rails check out [Turbolinks][].

[Check if there is a pjax plugin][plugins] for your favorite server framework.

Also check out [RailsCasts #294: Playing with PJAX][railscasts].

#### Arguments

The synopsis for the `$.fn.pjax` function is:

``` javascript
$(document).pjax(selector, [container], options)
```

1. `selector` is a string to be used for click [event delegation][$.fn.on].
2. `container` is a string selector that uniquely identifies the pjax container.
3. `options` is an object with keys described below.

##### pjax options

key | default | description
----|---------|------------
`timeout` | 650 | ajax timeout in milliseconds after which a full refresh is forced
`push` | true | use [pushState][] to add a browser history entry upon navigation
`replace` | false | replace URL without adding browser history entry
`maxCacheLength` | 20 | maximum cache size for previous container contents
`version` | | a string or function returning the current pjax version
`scrollTo` | 0 | vertical position to scroll to after navigation. To avoid changing scroll position, pass `false`.
`type` | `"GET"` | see [$.ajax][]
`dataType` | `"html"` | see [$.ajax][]
`container` | | CSS selector for the element where content should be replaced
`url` | link.href | a string or function that returns the URL for the ajax request
`target` | link | eventually the `relatedTarget` value for [pjax events](#events)
`fragment` | | CSS selector for the fragment to extract from ajax response

You can change the defaults globally by writing to the `$.pjax.defaults` object:

``` javascript
$.pjax.defaults.timeout = 1200
```

### `$.pjax.click`

This is a lower level function used by `$.fn.pjax` itself. It allows you to get a little more control over the pjax event handling.

This example uses the current click context to set an ancestor element as the container:

``` javascript
if ($.support.pjax) {
  $(document).on('click', 'a[data-pjax]', function(event) {
    var container = $(this).closest('[data-pjax-container]')
    var containerSelector = '#' + container.id
    $.pjax.click(event, {container: containerSelector})
  })
}
```

**NOTE** Use the explicit `$.support.pjax` guard. We aren't using `$.fn.pjax` so we should avoid binding this event handler unless the browser is actually going to use pjax.

### `$.pjax.submit`

Submits a form via pjax.

``` javascript
$(document).on('submit', 'form[data-pjax]', function(event) {
  $.pjax.submit(event, '#pjax-container')
})
```

### `$.pjax.reload`

Initiates a request for the current URL to the server using pjax mechanism and replaces the container with the response. Does not add a browser history entry.

``` javascript
$.pjax.reload('#pjax-container', options)
```

### `$.pjax`

Manual pjax invocation. Used mainly when you want to start a pjax request in a handler that didn't originate from a click. If you can get access to a click `event`, consider `$.pjax.click(event)` instead.

``` javascript
function applyFilters() {
  var url = urlForFilters()
  $.pjax({url: url, container: '#pjax-container'})
}
```

## Events

All pjax events except `pjax:click` & `pjax:clicked` are fired from the pjax
container element.

<table>
<tr>
  <th>event</th>
  <th>cancel</th>
  <th>arguments</th>
  <th>notes</th>
</tr>
<tr>
  <th colspan=4>event lifecycle upon following a pjaxed link</th>
</tr>
<tr>
  <td><code>pjax:click</code></td>
  <td>✔︎</td>
  <td><code>options</code></td>
  <td>fires from a link that got activated; cancel to prevent pjax</td>
</tr>
<tr>
  <td><code>pjax:beforeSend</code></td>
  <td>✔︎</td>
  <td><code>xhr, options</code></td>
  <td>can set XHR headers</td>
</tr>
<tr>
  <td><code>pjax:start</code></td>
  <td></td>
  <td><code>xhr, options</code></td>
  <td></td>
</tr>
<tr>
  <td><code>pjax:send</code></td>
  <td></td>
  <td><code>xhr, options</code></td>
  <td></td>
</tr>
<tr>
  <td><code>pjax:clicked</code></td>
  <td></td>
  <td><code>options</code></td>
  <td>fires after pjax has started from a link that got clicked</td>
</tr>
<tr>
  <td><code>pjax:beforeReplace</code></td>
  <td></td>
  <td><code>contents, options</code></td>
  <td>before replacing HTML with content loaded from the server</td>
</tr>
<tr>
  <td><code>pjax:success</code></td>
  <td></td>
  <td><code>data, status, xhr, options</code></td>
  <td>after replacing HTML content loaded from the server</td>
</tr>
<tr>
  <td><code>pjax:timeout</code></td>
  <td>✔︎</td>
  <td><code>xhr, options</code></td>
  <td>fires after <code>options.timeout</code>; will hard refresh unless canceled</td>
</tr>
<tr>
  <td><code>pjax:error</code></td>
  <td>✔︎</td>
  <td><code>xhr, textStatus, error, options</code></td>
  <td>on ajax error; will hard refresh unless canceled</td>
</tr>
<tr>
  <td><code>pjax:complete</code></td>
  <td></td>
  <td><code>xhr, textStatus, options</code></td>
  <td>always fires after ajax, regardless of result</td>
</tr>
<tr>
  <td><code>pjax:end</code></td>
  <td></td>
  <td><code>xhr, options</code></td>
  <td></td>
</tr>
<tr>
  <th colspan=4>event lifecycle on browser Back/Forward navigation</th>
</tr>
<tr>
  <td><code>pjax:popstate</code></td>
  <td></td>
  <td></td>
  <td>event <code>direction</code> property: &quot;back&quot;/&quot;forward&quot;</td>
</tr>
<tr>
  <td><code>pjax:start</code></td>
  <td></td>
  <td><code>null, options</code></td>
  <td>before replacing content</td>
</tr>
<tr>
  <td><code>pjax:beforeReplace</code></td>
  <td></td>
  <td><code>contents, options</code></td>
  <td>right before replacing HTML with content from cache</td>
</tr>
<tr>
  <td><code>pjax:end</code></td>
  <td></td>
  <td><code>null, options</code></td>
  <td>after replacing content</td>
</tr>
</table>

`pjax:send` & `pjax:complete` are a good pair of events to use if you are implementing a
loading indicator. They'll only be triggered if an actual XHR request is made,
not if the content is loaded from cache:

``` javascript
$(document).on('pjax:send', function() {
  $('#loading').show()
})
$(document).on('pjax:complete', function() {
  $('#loading').hide()
})
```

An example of canceling a `pjax:timeout` event would be to disable the fallback
timeout behavior if a spinner is being shown:

``` javascript
$(document).on('pjax:timeout', function(event) {
  // Prevent default timeout redirection behavior
  event.preventDefault()
})
```

## Advanced configuration

### Reinitializing plugins/widget on new page content

The whole point of pjax is that it fetches and inserts new content _without_
refreshing the page. However, other jQuery plugins or libraries that are set to
react on page loaded event (such as `DOMContentLoaded`) will not pick up on
these changes. Therefore, it's usually a good idea to configure these plugins to
reinitialize in the scope of the updated page content. This can be done like so:

``` js
$(document).on('ready pjax:end', function(event) {
  $(event.target).initializeMyPlugin()
})
```

This will make `$.fn.initializeMyPlugin()` be called at the document level on
normal page load, and on the container level after any pjax navigation (either
after clicking on a link or going Back in the browser).

### Response types that force a reload

By default, pjax will force a full reload of the page if it receives one of the
following responses from the server:

* Page content that includes `<html>` when `fragment` selector wasn't explicitly
  configured. Pjax presumes that the server's response hasn't been properly
  configured for pjax. If `fragment` pjax option is given, pjax will extract the
  content based on that selector.

* Page content that is blank. Pjax assumes that the server is unable to deliver
  proper pjax contents.

* HTTP response code that is 4xx or 5xx, indicating some server error.

### Affecting the browser URL

If the server needs to affect the URL which will appear in the browser URL after
pjax navigation (like HTTP redirects work for normal requests), it can set the
`X-PJAX-URL` header:

``` ruby
def index
  request.headers['X-PJAX-URL'] = "http://example.com/hello"
end
```

### Layout Reloading

Layouts can be forced to do a hard reload when assets or html changes.

First set the initial layout version in your header with a custom meta tag.

``` html
<meta http-equiv="x-pjax-version" content="v123">
```

Then from the server side, set the `X-PJAX-Version` header to the same.

``` ruby
if request.headers['X-PJAX']
  response.headers['X-PJAX-Version'] = "v123"
end
```

Deploying a deploy, bumping the version constant to force clients to do a full reload the next request getting the new layout and assets.


[$.fn.on]: http://api.jquery.com/on/
[$.ajax]: http://api.jquery.com/jQuery.ajax/
[pushState]: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
[plugins]: https://gist.github.com/4283721
[turbolinks]: https://github.com/rails/turbolinks
[railscasts]: http://railscasts.com/episodes/294-playing-with-pjax


================================================
FILE: bower.json
================================================
{
  "name": "jquery-pjax",
  "main": "./jquery.pjax.js",
  "dependencies": {
    "jquery": ">=1.8"
  },
  "ignore": [
    ".travis.yml",
    "Gemfile",
    "Gemfile.lock",
    "CONTRIBUTING.md",
    "vendor/",
    "script/",
    "test/"
  ]
}


================================================
FILE: jquery.pjax.js
================================================
/*!
 * Copyright 2012, Chris Wanstrath
 * Released under the MIT License
 * https://github.com/defunkt/jquery-pjax
 */

(function($){

// When called on a container with a selector, fetches the href with
// ajax into the container or with the data-pjax attribute on the link
// itself.
//
// Tries to make sure the back button and ctrl+click work the way
// you'd expect.
//
// Exported as $.fn.pjax
//
// Accepts a jQuery ajax options object that may include these
// pjax specific options:
//
//
// container - String selector for the element where to place the response body.
//      push - Whether to pushState the URL. Defaults to true (of course).
//   replace - Want to use replaceState instead? That's cool.
//
// For convenience the second parameter can be either the container or
// the options object.
//
// Returns the jQuery object
function fnPjax(selector, container, options) {
  options = optionsFor(container, options)
  return this.on('click.pjax', selector, function(event) {
    var opts = options
    if (!opts.container) {
      opts = $.extend({}, options)
      opts.container = $(this).attr('data-pjax')
    }
    handleClick(event, opts)
  })
}

// Public: pjax on click handler
//
// Exported as $.pjax.click.
//
// event   - "click" jQuery.Event
// options - pjax options
//
// Examples
//
//   $(document).on('click', 'a', $.pjax.click)
//   // is the same as
//   $(document).pjax('a')
//
// Returns nothing.
function handleClick(event, container, options) {
  options = optionsFor(container, options)

  var link = event.currentTarget
  var $link = $(link)

  if (link.tagName.toUpperCase() !== 'A')
    throw "$.fn.pjax or $.pjax.click requires an anchor element"

  // Middle click, cmd click, and ctrl click should open
  // links in a new tab as normal.
  if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey )
    return

  // Ignore cross origin links
  if ( location.protocol !== link.protocol || location.hostname !== link.hostname )
    return

  // Ignore case when a hash is being tacked on the current URL
  if ( link.href.indexOf('#') > -1 && stripHash(link) == stripHash(location) )
    return

  // Ignore event with default prevented
  if (event.isDefaultPrevented())
    return

  var defaults = {
    url: link.href,
    container: $link.attr('data-pjax'),
    target: link
  }

  var opts = $.extend({}, defaults, options)
  var clickEvent = $.Event('pjax:click')
  $link.trigger(clickEvent, [opts])

  if (!clickEvent.isDefaultPrevented()) {
    pjax(opts)
    event.preventDefault()
    $link.trigger('pjax:clicked', [opts])
  }
}

// Public: pjax on form submit handler
//
// Exported as $.pjax.submit
//
// event   - "click" jQuery.Event
// options - pjax options
//
// Examples
//
//  $(document).on('submit', 'form', function(event) {
//    $.pjax.submit(event, '[data-pjax-container]')
//  })
//
// Returns nothing.
function handleSubmit(event, container, options) {
  options = optionsFor(container, options)

  var form = event.currentTarget
  var $form = $(form)

  if (form.tagName.toUpperCase() !== 'FORM')
    throw "$.pjax.submit requires a form element"

  var defaults = {
    type: ($form.attr('method') || 'GET').toUpperCase(),
    url: $form.attr('action'),
    container: $form.attr('data-pjax'),
    target: form
  }

  if (defaults.type !== 'GET' && window.FormData !== undefined) {
    defaults.data = new FormData(form)
    defaults.processData = false
    defaults.contentType = false
  } else {
    // Can't handle file uploads, exit
    if ($form.find(':file').length) {
      return
    }

    // Fallback to manually serializing the fields
    defaults.data = $form.serializeArray()
  }

  pjax($.extend({}, defaults, options))

  event.preventDefault()
}

// Loads a URL with ajax, puts the response body inside a container,
// then pushState()'s the loaded URL.
//
// Works just like $.ajax in that it accepts a jQuery ajax
// settings object (with keys like url, type, data, etc).
//
// Accepts these extra keys:
//
// container - String selector for where to stick the response body.
//      push - Whether to pushState the URL. Defaults to true (of course).
//   replace - Want to use replaceState instead? That's cool.
//
// Use it just like $.ajax:
//
//   var xhr = $.pjax({ url: this.href, container: '#main' })
//   console.log( xhr.readyState )
//
// Returns whatever $.ajax returns.
function pjax(options) {
  options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options)

  if ($.isFunction(options.url)) {
    options.url = options.url()
  }

  var hash = parseURL(options.url).hash

  var containerType = $.type(options.container)
  if (containerType !== 'string') {
    throw "expected string value for 'container' option; got " + containerType
  }
  var context = options.context = $(options.container)
  if (!context.length) {
    throw "the container selector '" + options.container + "' did not match anything"
  }

  // We want the browser to maintain two separate internal caches: one
  // for pjax'd partial page loads and one for normal page loads.
  // Without adding this secret parameter, some browsers will often
  // confuse the two.
  if (!options.data) options.data = {}
  if ($.isArray(options.data)) {
    options.data.push({name: '_pjax', value: options.container})
  } else {
    options.data._pjax = options.container
  }

  function fire(type, args, props) {
    if (!props) props = {}
    props.relatedTarget = options.target
    var event = $.Event(type, props)
    context.trigger(event, args)
    return !event.isDefaultPrevented()
  }

  var timeoutTimer

  options.beforeSend = function(xhr, settings) {
    // No timeout for non-GET requests
    // Its not safe to request the resource again with a fallback method.
    if (settings.type !== 'GET') {
      settings.timeout = 0
    }

    xhr.setRequestHeader('X-PJAX', 'true')
    xhr.setRequestHeader('X-PJAX-Container', options.container)

    if (!fire('pjax:beforeSend', [xhr, settings]))
      return false

    if (settings.timeout > 0) {
      timeoutTimer = setTimeout(function() {
        if (fire('pjax:timeout', [xhr, options]))
          xhr.abort('timeout')
      }, settings.timeout)

      // Clear timeout setting so jquerys internal timeout isn't invoked
      settings.timeout = 0
    }

    var url = parseURL(settings.url)
    if (hash) url.hash = hash
    options.requestUrl = stripInternalParams(url)
  }

  options.complete = function(xhr, textStatus) {
    if (timeoutTimer)
      clearTimeout(timeoutTimer)

    fire('pjax:complete', [xhr, textStatus, options])

    fire('pjax:end', [xhr, options])
  }

  options.error = function(xhr, textStatus, errorThrown) {
    var container = extractContainer("", xhr, options)

    var allowed = fire('pjax:error', [xhr, textStatus, errorThrown, options])
    if (options.type == 'GET' && textStatus !== 'abort' && allowed) {
      locationReplace(container.url)
    }
  }

  options.success = function(data, status, xhr) {
    var previousState = pjax.state

    // If $.pjax.defaults.version is a function, invoke it first.
    // Otherwise it can be a static string.
    var currentVersion = typeof $.pjax.defaults.version === 'function' ?
      $.pjax.defaults.version() :
      $.pjax.defaults.version

    var latestVersion = xhr.getResponseHeader('X-PJAX-Version')

    var container = extractContainer(data, xhr, options)

    var url = parseURL(container.url)
    if (hash) {
      url.hash = hash
      container.url = url.href
    }

    // If there is a layout version mismatch, hard load the new url
    if (currentVersion && latestVersion && currentVersion !== latestVersion) {
      locationReplace(container.url)
      return
    }

    // If the new response is missing a body, hard load the page
    if (!container.contents) {
      locationReplace(container.url)
      return
    }

    pjax.state = {
      id: options.id || uniqueId(),
      url: container.url,
      title: container.title,
      container: options.container,
      fragment: options.fragment,
      timeout: options.timeout
    }

    if (options.push || options.replace) {
      window.history.replaceState(pjax.state, container.title, container.url)
    }

    // Only blur the focus if the focused element is within the container.
    var blurFocus = $.contains(context, document.activeElement)

    // Clear out any focused controls before inserting new page contents.
    if (blurFocus) {
      try {
        document.activeElement.blur()
      } catch (e) { /* ignore */ }
    }

    if (container.title) document.title = container.title

    fire('pjax:beforeReplace', [container.contents, options], {
      state: pjax.state,
      previousState: previousState
    })
    context.html(container.contents)

    // FF bug: Won't autofocus fields that are inserted via JS.
    // This behavior is incorrect. So if theres no current focus, autofocus
    // the last field.
    //
    // http://www.w3.org/html/wg/drafts/html/master/forms.html
    var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0]
    if (autofocusEl && document.activeElement !== autofocusEl) {
      autofocusEl.focus()
    }

    executeScriptTags(container.scripts)

    var scrollTo = options.scrollTo

    // Ensure browser scrolls to the element referenced by the URL anchor
    if (hash) {
      var name = decodeURIComponent(hash.slice(1))
      var target = document.getElementById(name) || document.getElementsByName(name)[0]
      if (target) scrollTo = $(target).offset().top
    }

    if (typeof scrollTo == 'number') $(window).scrollTop(scrollTo)

    fire('pjax:success', [data, status, xhr, options])
  }


  // Initialize pjax.state for the initial page load. Assume we're
  // using the container and options of the link we're loading for the
  // back button to the initial page. This ensures good back button
  // behavior.
  if (!pjax.state) {
    pjax.state = {
      id: uniqueId(),
      url: window.location.href,
      title: document.title,
      container: options.container,
      fragment: options.fragment,
      timeout: options.timeout
    }
    window.history.replaceState(pjax.state, document.title)
  }

  // Cancel the current request if we're already pjaxing
  abortXHR(pjax.xhr)

  pjax.options = options
  var xhr = pjax.xhr = $.ajax(options)

  if (xhr.readyState > 0) {
    if (options.push && !options.replace) {
      // Cache current container element before replacing it
      cachePush(pjax.state.id, [options.container, cloneContents(context)])

      window.history.pushState(null, "", options.requestUrl)
    }

    fire('pjax:start', [xhr, options])
    fire('pjax:send', [xhr, options])
  }

  return pjax.xhr
}

// Public: Reload current page with pjax.
//
// Returns whatever $.pjax returns.
function pjaxReload(container, options) {
  var defaults = {
    url: window.location.href,
    push: false,
    replace: true,
    scrollTo: false
  }

  return pjax($.extend(defaults, optionsFor(container, options)))
}

// Internal: Hard replace current state with url.
//
// Work for around WebKit
//   https://bugs.webkit.org/show_bug.cgi?id=93506
//
// Returns nothing.
function locationReplace(url) {
  window.history.replaceState(null, "", pjax.state.url)
  window.location.replace(url)
}


var initialPop = true
var initialURL = window.location.href
var initialState = window.history.state

// Initialize $.pjax.state if possible
// Happens when reloading a page and coming forward from a different
// session history.
if (initialState && initialState.container) {
  pjax.state = initialState
}

// Non-webkit browsers don't fire an initial popstate event
if ('state' in window.history) {
  initialPop = false
}

// popstate handler takes care of the back and forward buttons
//
// You probably shouldn't use pjax on pages with other pushState
// stuff yet.
function onPjaxPopstate(event) {

  // Hitting back or forward should override any pending PJAX request.
  if (!initialPop) {
    abortXHR(pjax.xhr)
  }

  var previousState = pjax.state
  var state = event.state
  var direction

  if (state && state.container) {
    // When coming forward from a separate history session, will get an
    // initial pop with a state we are already at. Skip reloading the current
    // page.
    if (initialPop && initialURL == state.url) return

    if (previousState) {
      // If popping back to the same state, just skip.
      // Could be clicking back from hashchange rather than a pushState.
      if (previousState.id === state.id) return

      // Since state IDs always increase, we can deduce the navigation direction
      direction = previousState.id < state.id ? 'forward' : 'back'
    }

    var cache = cacheMapping[state.id] || []
    var containerSelector = cache[0] || state.container
    var container = $(containerSelector), contents = cache[1]

    if (container.length) {
      if (previousState) {
        // Cache current container before replacement and inform the
        // cache which direction the history shifted.
        cachePop(direction, previousState.id, [containerSelector, cloneContents(container)])
      }

      var popstateEvent = $.Event('pjax:popstate', {
        state: state,
        direction: direction
      })
      container.trigger(popstateEvent)

      var options = {
        id: state.id,
        url: state.url,
        container: containerSelector,
        push: false,
        fragment: state.fragment,
        timeout: state.timeout,
        scrollTo: false
      }

      if (contents) {
        container.trigger('pjax:start', [null, options])

        pjax.state = state
        if (state.title) document.title = state.title
        var beforeReplaceEvent = $.Event('pjax:beforeReplace', {
          state: state,
          previousState: previousState
        })
        container.trigger(beforeReplaceEvent, [contents, options])
        container.html(contents)

        container.trigger('pjax:end', [null, options])
      } else {
        pjax(options)
      }

      // Force reflow/relayout before the browser tries to restore the
      // scroll position.
      container[0].offsetHeight // eslint-disable-line no-unused-expressions
    } else {
      locationReplace(location.href)
    }
  }
  initialPop = false
}

// Fallback version of main pjax function for browsers that don't
// support pushState.
//
// Returns nothing since it retriggers a hard form submission.
function fallbackPjax(options) {
  var url = $.isFunction(options.url) ? options.url() : options.url,
      method = options.type ? options.type.toUpperCase() : 'GET'

  var form = $('<form>', {
    method: method === 'GET' ? 'GET' : 'POST',
    action: url,
    style: 'display:none'
  })

  if (method !== 'GET' && method !== 'POST') {
    form.append($('<input>', {
      type: 'hidden',
      name: '_method',
      value: method.toLowerCase()
    }))
  }

  var data = options.data
  if (typeof data === 'string') {
    $.each(data.split('&'), function(index, value) {
      var pair = value.split('=')
      form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]}))
    })
  } else if ($.isArray(data)) {
    $.each(data, function(index, value) {
      form.append($('<input>', {type: 'hidden', name: value.name, value: value.value}))
    })
  } else if (typeof data === 'object') {
    var key
    for (key in data)
      form.append($('<input>', {type: 'hidden', name: key, value: data[key]}))
  }

  $(document.body).append(form)
  form.submit()
}

// Internal: Abort an XmlHttpRequest if it hasn't been completed,
// also removing its event handlers.
function abortXHR(xhr) {
  if ( xhr && xhr.readyState < 4) {
    xhr.onreadystatechange = $.noop
    xhr.abort()
  }
}

// Internal: Generate unique id for state object.
//
// Use a timestamp instead of a counter since ids should still be
// unique across page loads.
//
// Returns Number.
function uniqueId() {
  return (new Date).getTime()
}

function cloneContents(container) {
  var cloned = container.clone()
  // Unmark script tags as already being eval'd so they can get executed again
  // when restored from cache. HAXX: Uses jQuery internal method.
  cloned.find('script').each(function(){
    if (!this.src) $._data(this, 'globalEval', false)
  })
  return cloned.contents()
}

// Internal: Strip internal query params from parsed URL.
//
// Returns sanitized url.href String.
function stripInternalParams(url) {
  url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '').replace(/^&/, '')
  return url.href.replace(/\?($|#)/, '$1')
}

// Internal: Parse URL components and returns a Locationish object.
//
// url - String URL
//
// Returns HTMLAnchorElement that acts like Location.
function parseURL(url) {
  var a = document.createElement('a')
  a.href = url
  return a
}

// Internal: Return the `href` component of given URL object with the hash
// portion removed.
//
// location - Location or HTMLAnchorElement
//
// Returns String
function stripHash(location) {
  return location.href.replace(/#.*/, '')
}

// Internal: Build options Object for arguments.
//
// For convenience the first parameter can be either the container or
// the options object.
//
// Examples
//
//   optionsFor('#container')
//   // => {container: '#container'}
//
//   optionsFor('#container', {push: true})
//   // => {container: '#container', push: true}
//
//   optionsFor({container: '#container', push: true})
//   // => {container: '#container', push: true}
//
// Returns options Object.
function optionsFor(container, options) {
  if (container && options) {
    options = $.extend({}, options)
    options.container = container
    return options
  } else if ($.isPlainObject(container)) {
    return container
  } else {
    return {container: container}
  }
}

// Internal: Filter and find all elements matching the selector.
//
// Where $.fn.find only matches descendants, findAll will test all the
// top level elements in the jQuery object as well.
//
// elems    - jQuery object of Elements
// selector - String selector to match
//
// Returns a jQuery object.
function findAll(elems, selector) {
  return elems.filter(selector).add(elems.find(selector))
}

function parseHTML(html) {
  return $.parseHTML(html, document, true)
}

// Internal: Extracts container and metadata from response.
//
// 1. Extracts X-PJAX-URL header if set
// 2. Extracts inline <title> tags
// 3. Builds response Element and extracts fragment if set
//
// data    - String response data
// xhr     - XHR response
// options - pjax options Object
//
// Returns an Object with url, title, and contents keys.
function extractContainer(data, xhr, options) {
  var obj = {}, fullDocument = /<html/i.test(data)

  // Prefer X-PJAX-URL header if it was set, otherwise fallback to
  // using the original requested url.
  var serverUrl = xhr.getResponseHeader('X-PJAX-URL')
  obj.url = serverUrl ? stripInternalParams(parseURL(serverUrl)) : options.requestUrl

  var $head, $body
  // Attempt to parse response html into elements
  if (fullDocument) {
    $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0]))
    var head = data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)
    $head = head != null ? $(parseHTML(head[0])) : $body
  } else {
    $head = $body = $(parseHTML(data))
  }

  // If response data is empty, return fast
  if ($body.length === 0)
    return obj

  // If there's a <title> tag in the header, use it as
  // the page's title.
  obj.title = findAll($head, 'title').last().text()

  if (options.fragment) {
    var $fragment = $body
    // If they specified a fragment, look for it in the response
    // and pull it out.
    if (options.fragment !== 'body') {
      $fragment = findAll($fragment, options.fragment).first()
    }

    if ($fragment.length) {
      obj.contents = options.fragment === 'body' ? $fragment : $fragment.contents()

      // If there's no title, look for data-title and title attributes
      // on the fragment
      if (!obj.title)
        obj.title = $fragment.attr('title') || $fragment.data('title')
    }

  } else if (!fullDocument) {
    obj.contents = $body
  }

  // Clean up any <title> tags
  if (obj.contents) {
    // Remove any parent title elements
    obj.contents = obj.contents.not(function() { return $(this).is('title') })

    // Then scrub any titles from their descendants
    obj.contents.find('title').remove()

    // Gather all script[src] elements
    obj.scripts = findAll(obj.contents, 'script[src]').remove()
    obj.contents = obj.contents.not(obj.scripts)
  }

  // Trim any whitespace off the title
  if (obj.title) obj.title = $.trim(obj.title)

  return obj
}

// Load an execute scripts using standard script request.
//
// Avoids jQuery's traditional $.getScript which does a XHR request and
// globalEval.
//
// scripts - jQuery object of script Elements
//
// Returns nothing.
function executeScriptTags(scripts) {
  if (!scripts) return

  var existingScripts = $('script[src]')

  scripts.each(function() {
    var src = this.src
    var matchedScripts = existingScripts.filter(function() {
      return this.src === src
    })
    if (matchedScripts.length) return

    var script = document.createElement('script')
    var type = $(this).attr('type')
    if (type) script.type = type
    script.src = $(this).attr('src')
    document.head.appendChild(script)
  })
}

// Internal: History DOM caching class.
var cacheMapping      = {}
var cacheForwardStack = []
var cacheBackStack    = []

// Push previous state id and container contents into the history
// cache. Should be called in conjunction with `pushState` to save the
// previous container contents.
//
// id    - State ID Number
// value - DOM Element to cache
//
// Returns nothing.
function cachePush(id, value) {
  cacheMapping[id] = value
  cacheBackStack.push(id)

  // Remove all entries in forward history stack after pushing a new page.
  trimCacheStack(cacheForwardStack, 0)

  // Trim back history stack to max cache length.
  trimCacheStack(cacheBackStack, pjax.defaults.maxCacheLength)
}

// Shifts cache from directional history cache. Should be
// called on `popstate` with the previous state id and container
// contents.
//
// direction - "forward" or "back" String
// id        - State ID Number
// value     - DOM Element to cache
//
// Returns nothing.
function cachePop(direction, id, value) {
  var pushStack, popStack
  cacheMapping[id] = value

  if (direction === 'forward') {
    pushStack = cacheBackStack
    popStack  = cacheForwardStack
  } else {
    pushStack = cacheForwardStack
    popStack  = cacheBackStack
  }

  pushStack.push(id)
  id = popStack.pop()
  if (id) delete cacheMapping[id]

  // Trim whichever stack we just pushed to to max cache length.
  trimCacheStack(pushStack, pjax.defaults.maxCacheLength)
}

// Trim a cache stack (either cacheBackStack or cacheForwardStack) to be no
// longer than the specified length, deleting cached DOM elements as necessary.
//
// stack  - Array of state IDs
// length - Maximum length to trim to
//
// Returns nothing.
function trimCacheStack(stack, length) {
  while (stack.length > length)
    delete cacheMapping[stack.shift()]
}

// Public: Find version identifier for the initial page load.
//
// Returns String version or undefined.
function findVersion() {
  return $('meta').filter(function() {
    var name = $(this).attr('http-equiv')
    return name && name.toUpperCase() === 'X-PJAX-VERSION'
  }).attr('content')
}

// Install pjax functions on $.pjax to enable pushState behavior.
//
// Does nothing if already enabled.
//
// Examples
//
//     $.pjax.enable()
//
// Returns nothing.
function enable() {
  $.fn.pjax = fnPjax
  $.pjax = pjax
  $.pjax.enable = $.noop
  $.pjax.disable = disable
  $.pjax.click = handleClick
  $.pjax.submit = handleSubmit
  $.pjax.reload = pjaxReload
  $.pjax.defaults = {
    timeout: 650,
    push: true,
    replace: false,
    type: 'GET',
    dataType: 'html',
    scrollTo: 0,
    maxCacheLength: 20,
    version: findVersion
  }
  $(window).on('popstate.pjax', onPjaxPopstate)
}

// Disable pushState behavior.
//
// This is the case when a browser doesn't support pushState. It is
// sometimes useful to disable pushState for debugging on a modern
// browser.
//
// Examples
//
//     $.pjax.disable()
//
// Returns nothing.
function disable() {
  $.fn.pjax = function() { return this }
  $.pjax = fallbackPjax
  $.pjax.enable = enable
  $.pjax.disable = $.noop
  $.pjax.click = $.noop
  $.pjax.submit = $.noop
  $.pjax.reload = function() { window.location.reload() }

  $(window).off('popstate.pjax', onPjaxPopstate)
}


// Add the state property to jQuery's event object so we can use it in
// $(window).bind('popstate')
if ($.event.props && $.inArray('state', $.event.props) < 0) {
  $.event.props.push('state')
} else if (!('state' in $.Event.prototype)) {
  $.event.addProp('state')
}

// Is pjax supported by this browser?
$.support.pjax =
  window.history && window.history.pushState && window.history.replaceState &&
  // pushState isn't reliable on iOS until 5.
  !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)

if ($.support.pjax) {
  enable()
} else {
  disable()
}

})(jQuery)


================================================
FILE: package.json
================================================
{
  "name": "jquery-pjax",
  "description": "jQuery plugin for ajax + pushState navigation",
  "version": "2.0.1",
  "main": "jquery.pjax.js",
  "repository": "defunkt/jquery-pjax",
  "license": "MIT",
  "files": [
    "LICENSE",
    "jquery.pjax.js"
  ],
  "devDependencies": {
    "eslint": "^3.19.0"
  },
  "scripts": {
    "test": "./script/test"
  }
}


================================================
FILE: script/bootstrap
================================================
#!/usr/bin/env bash
set -e

[ -n "$CI" ] || npm install
bundle install

if phantom_version="$(phantomjs --version)"; then
  echo "PhantomJS $phantom_version"
else
  echo "Warning: script/test will not be able to run, but you can still start" >&2
  echo "script/server and open the test suite in your browser." >&2
fi


================================================
FILE: script/server
================================================
#!/usr/bin/env bash
set -e

exec bundle exec ruby ./test/app.rb "$@"


================================================
FILE: script/test
================================================
#!/usr/bin/env bash
set -e

./node_modules/.bin/eslint *.js

port=3999
script/server -p "$port" &>/dev/null &
pid=$!

trap "kill $pid" EXIT INT

while ! lsof -i :$port >/dev/null; do
  sleep .05
done

phantomjs ./test/run-qunit.js \
  "http://localhost:$port/?jquery=3.2" \
  "http://localhost:$port/?jquery=2.2" \
  "http://localhost:$port/?jquery=1.12"


================================================
FILE: test/app.rb
================================================
require 'sinatra'
require 'json'

set :public_folder, File.dirname(settings.root)
enable :static

jquery_version = '3.2'

helpers do
  def pjax?
    env['HTTP_X_PJAX'] && !params[:layout]
  end

  def title(str)
    if pjax?
      "<title>#{str}</title>"
    else
      @title = str
      nil
    end
  end

  define_method(:jquery_version) do
    jquery_version
  end
end

after do
  if pjax?
    response.headers['X-PJAX-URL'] ||= request.url
    response.headers['X-PJAX-Version'] = 'v1'
  end
end


get '/' do
  jquery_version = params[:jquery] if params[:jquery]
  erb :qunit
end

get '/env.html' do
  erb :env, :layout => !pjax?
end

post '/env.html' do
  erb :env, :layout => !pjax?
end

put '/env.html' do
  erb :env, :layout => !pjax?
end

delete '/env.html' do
  erb :env, :layout => !pjax?
end

get '/redirect.html' do
  if params[:anchor]
    path = "/hello.html##{params[:anchor]}"
    if pjax?
      response.headers['X-PJAX-URL'] = uri(path)
      status 200
    else
      redirect path
    end
  else
    redirect "/hello.html"
  end
end

get '/timeout.html' do
  if pjax?
    sleep 1
    erb :timeout, :layout => false
  else
    erb :timeout
  end
end

post '/timeout.html' do
  if pjax?
    sleep 1
    erb :timeout, :layout => false
  else
    status 500
    erb :boom
  end
end

get '/boom.html' do
  status 500
  erb :boom, :layout => !pjax?
end

get '/boom_sans_pjax.html' do
  status 500
  erb :boom_sans_pjax, :layout => false
end

get '/:page.html' do
  erb :"#{params[:page]}", :layout => !pjax?
end

get '/some-&-path/hello.html' do
  erb :hello, :layout => !pjax?
end


================================================
FILE: test/evaled.js
================================================
window.externalScriptLoaded()


================================================
FILE: test/run-qunit.js
================================================
var fs = require('fs')
var suites = require('system').args.slice(1)

function print(s) {
  fs.write('/dev/stdout', s, 'w')
}

var page = require('webpage').create()
page.onConsoleMessage = function(msg) {
  console.log(msg)
}
page.onError = function(msg) {
  console.error('ERROR: ' + msg)
}

var timeoutId = null
function deferTimeout() {
  if (timeoutId) clearTimeout(timeoutId)
  timeoutId = setTimeout(function() {
    console.error('Timeout')
    phantom.exit(1)
  }, 3000)
}

var endresult = 0

function runSuite() {
  var suite = suites.shift()
  if (!suite) {
    phantom.exit(endresult)
    return
  }

  page.open(suite, function() {
    deferTimeout()

    var interval = setInterval(function() {
      var tests = page.evaluate(function() {
        var results = []
        var els = document.getElementById('qunit-tests').children

        for (var i = 0; i < els.length; i++) {
          var test = els[i]
          if (test.className !== 'running' && !test.recorded) {
            test.recorded = true
            if (test.className === 'pass') results.push('.')
            else if (test.className === 'fail') results.push('F')
          }
        }

        return results
      })

      for (var i = 0; i < tests.length; i++) {
        deferTimeout()
        print(tests[i])
      }

      var result = page.evaluate(function() {
        var testresult = document.getElementById('qunit-testresult')
        var els = document.getElementById('qunit-tests').children

        if (testresult.innerText.match(/completed/)) {
          console.log('')

          for (var i = 0; i < els.length; i++) {
            var test = els[i]
            if (test.className === 'fail') {
              console.error(test.innerText)
            }
          }

          console.log(testresult.innerText)
          return parseInt(testresult.getElementsByClassName('failed')[0].innerText)
        }
      })

      if (result != null) {
        endresult = result
        clearInterval(interval)
        runSuite()
      }
    }, 100)
  })
}

runSuite()


================================================
FILE: test/unit/fn_pjax.js
================================================
if ($.support.pjax) {
  module("$.fn.pjax", {
    setup: function() {
      var self = this
      stop()
      window.iframeLoad = function(frame) {
        self.frame = frame
        window.iframeLoad = $.noop
        start()
      }
      $("#qunit-fixture").append("<iframe src='home.html'>")
    },
    teardown: function() {
      delete window.iframeLoad
    }
  })


  asyncTest("pushes new url", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main").on("pjax:end", function() {
      equal(frame.location.pathname, "/dinosaurs.html")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("replaces container html from response data", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main").on("pjax:end", function() {
      equal(frame.$("iframe").attr('title'), "YouTube video player")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("sets title to response title tag", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main").on("pjax:end", function() {
      equal(frame.document.title, "dinosaurs")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").trigger('click')
  })

  asyncTest("uses second argument as options", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", {container: "#main", push: true}).on("pjax:end", function() {
      equal(frame.location.pathname, "/dinosaurs.html")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("uses second argument as container and third as options", function() {
    var frame = this.frame

    frame.$("body").pjax("a", "#main", {push: true}).on("pjax:end", function() {
      equal(frame.location.pathname, "/dinosaurs.html")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })


  asyncTest("defaults to data-pjax container", function() {
    var frame = this.frame

    frame.$("a").attr('data-pjax', "#main")

    frame.$("body").pjax("a")

    frame.$("#main").on("pjax:end", function() {
      equal(frame.location.pathname, "/dinosaurs.html")
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("sets relatedTarget to clicked element", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main")

    var link = frame.$("a[href='/dinosaurs.html']")[0]

    frame.$("#main").on("pjax:end", function(event, xhr, options) {
      equal(link, event.relatedTarget)
      start()
    })

    frame.$(link).click()
  })


  asyncTest("doesn't ignore left click", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main")

    var event = frame.$.Event('click')
    event.which = 0
    frame.$("a[href='/dinosaurs.html']").trigger(event)
    ok(event.isDefaultPrevented())

    start()
  })

  asyncTest("ignores middle clicks", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main")

    var event = frame.$.Event('click')
    event.which = 3
    frame.$("a[href='/dinosaurs.html']").trigger(event)
    ok(!event.isDefaultPrevented())

    start()
  })

  asyncTest("ignores command clicks", function() {
    var frame = this.frame

    frame.$("#main").pjax("a")

    var event = frame.$.Event('click')
    event.metaKey = true
    frame.$("a[href='/dinosaurs.html']").trigger(event)
    ok(!event.isDefaultPrevented())

    start()
  })

  asyncTest("ignores ctrl clicks", function() {
    var frame = this.frame

    frame.$("#main").pjax("a")

    var event = frame.$.Event('click')
    event.ctrlKey = true
    frame.$("a[href='/dinosaurs.html']").trigger(event)
    ok(!event.isDefaultPrevented())

    start()
  })

  asyncTest("ignores cross origin links", function() {
    var frame = this.frame

    frame.$("#main").pjax("a")

    var event = frame.$.Event('click')
    frame.$("a[href='https://www.google.com/']").trigger(event)
    notEqual(event.result, false)

    start()
  })

  asyncTest("ignores same page anchors", function() {
    var event, frame = this.frame

    frame.$("#main").pjax("a")

    event = frame.$.Event('click')
    frame.$("a[href='#main']").trigger(event)
    equal(event.isDefaultPrevented(), false)

    event = frame.$.Event('click')
    frame.$("a[href='#']").trigger(event)
    equal(event.isDefaultPrevented(), false)

    start()
  })

  asyncTest("ignores same page anchors from URL that has hash", function() {
    var event, frame = this.frame

    frame.window.location = "#foo"
    frame.$("#main").pjax("a")

    event = frame.$.Event('click')
    frame.$("a[href='#main']").trigger(event)
    equal(event.isDefaultPrevented(), false)

    event = frame.$.Event('click')
    frame.$("a[href='#']").trigger(event)
    equal(event.isDefaultPrevented(), false)

    start()
  })

  asyncTest("ignores event with prevented default", function() {
    var frame = this.frame
    var eventIgnored = true

    frame.$("#main").pjax("a").on("pjax:click", function() {
      eventIgnored = false
    })
    frame.$("a[href='/dinosaurs.html']").on("click", function(event) {
      event.preventDefault()
      setTimeout(function() {
        ok(eventIgnored, "Event with prevented default ignored")
        start()
      }, 10)
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("triggers pjax:click event from link", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main").on("pjax:click", function(event, options) {
      ok(event)
      equal(options.container, "#main")
      ok(options.url.match("/dinosaurs.html"))
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })

  asyncTest("triggers pjax:clicked event from link", function() {
    var frame = this.frame

    frame.$("#main").pjax("a", "#main").on("pjax:clicked", function(event, options) {
      ok(event)
      equal(options.container, "#main")
      ok(options.url.match("/dinosaurs.html"))
      start()
    })

    frame.$("a[href='/dinosaurs.html']").click()
  })
}


================================================
FILE: test/unit/helpers.js
================================================
// Navigation helper for the test iframe. Queues navigation actions and
// callbacks, then executes them serially with respect to async. This is to
// avoid deep nesting of callbacks in tests.
//
// If a `then`able object is returned from a callback, then the navigation will
// resume only after the promise has been resolved.
//
// After last successful navigation, asyncTest is automatically resumed.
//
// Usage:
//
//   navigate(this.frame)
//   .pjax(pjaxOptions, function(frame){ ... }
//   .back(-1, function(frame){ ... }
//
function navigate(frame) {
  var queue = []
  var api = {}

  api.pjax = function(options, callback) {
    queue.push([options, callback])
    return api
  }
  api.back = api.pjax

  var workOff = function() {
    var item = queue.shift()
    if (!item) {
      start()
      return
    }

    var target = item[0], callback = item[1]

    frame.$(frame.document).one("pjax:end", function() {
      var promise = callback && callback(frame)
      if (promise && typeof promise.then == "function") promise.then(workOff)
      else setTimeout(workOff, 0)
    })

    if (typeof target == "number") {
      frame.history.go(target)
    } else {
      frame.$.pjax(target)
    }
  }

  setTimeout(workOff, 0)

  return api
}

// A poor man's Promise implementation. Only resolvable promises with no
// reject/catch support.
function PoorMansPromise(setup) {
  var result, callback, i = 0, callbacks = []
  setup(function(_result) {
    result = _result
    while (callback = callbacks[i++]) callback(result)
  })
  this.then = function(done) {
    if (i == 0) callbacks.push(done)
    else setTimeout(function(){ done(result) }, 0)
    return this
  }
}


================================================
FILE: test/unit/pjax.js
================================================
if ($.support.pjax) {
  module("$.pjax", {
    setup: function() {
      var self = this
      stop()
      window.iframeLoad = function(frame) {
        self.frame = frame
        window.iframeLoad = $.noop
        start()
      }
      $("#qunit-fixture").append("<iframe src='home.html'>")
      this.iframe = $("iframe")[0]
    },
    teardown: function() {
      delete window.iframeLoad
    }
  })

  asyncTest("pushes new url", 2, function() {
    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main", cache: false }, function(frame) {
      equal(frame.location.pathname, "/hello.html")
      equal(frame.location.search, "")
    })
  })

  asyncTest("replaces container html from response data", 2, function() {
    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(frame.$("#main > p").html().trim(), "Hello!")
      equal(frame.$("#main").contents().eq(1).text().trim(), "How's it going?")
    })
  })

  asyncTest("sets title to response title tag", 2, function() {
    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(frame.document.title, "Hello")
      equal(frame.$("#main title").length, 0)
    })
  })

  asyncTest("sets title to response nested title tag", 2, function() {
    navigate(this.frame)
    .pjax({ url: "nested_title.html", container: "#main" }, function(frame) {
      equal(frame.document.title, "Hello")
      equal(frame.$("#main title").length, 0)
    })
  })

  asyncTest("sets title to response last title tag", 2, function() {
    navigate(this.frame)
    .pjax({ url: "double_title.html", container: "#main" }, function(frame) {
      equal(frame.document.title, "World!")
      equal(frame.$("#main title").length, 0)
    })
  })

  asyncTest("scrolls to top of page", 2, function() {
    this.frame.scrollTo(0, 100)
    equal(this.frame.pageYOffset, 100)

    navigate(this.frame)
    .pjax({ url: "long.html", container: "#main" }, function(frame) {
      equal(frame.pageYOffset, 0)
    })
  })

  asyncTest("scrollTo: false avoids changing current scroll position", 2, function() {
    this.frame.scrollTo(0, 100)
    equal(this.frame.pageYOffset, 100)

    navigate(this.frame)
    .pjax({ url: "long.html", scrollTo: false, container: "#main" }, function(frame) {
      equal(frame.window.pageYOffset, 100)
    })
  })

  asyncTest("evals scripts", 7, function() {
    var externalLoadedCount = 0
    this.frame.externalScriptLoaded = function() {
      externalLoadedCount++
    }

    navigate(this.frame)
    .pjax({ url: "scripts.html?name=one", container: "#main" }, function(frame) {
      deepEqual(frame.evaledInlineLog, ["one"])
      equal(externalLoadedCount, 0)
      return new PoorMansPromise(function(resolve) {
        setTimeout(resolve, 100)
      }).then(function() {
        equal(externalLoadedCount, 2, "expected scripts to have loaded")
      })
    })
    .pjax({ url: "scripts.html?name=two", container: "#main" }, function(frame) {
      deepEqual(frame.evaledInlineLog, ["one", "two"])
    })
    .back(-1, function(frame) {
      deepEqual(frame.evaledInlineLog, ["one", "two", "one"])
    })
    .back(+1, function(frame) {
      deepEqual(frame.evaledInlineLog, ["one", "two", "one", "two"])
      return new PoorMansPromise(function(resolve) {
        setTimeout(resolve, 100)
      }).then(function() {
        equal(externalLoadedCount, 2, "expected no extra scripts to load")
      })
    })
  })

  asyncTest("url option accepts function", 2, function() {
    var numCalls = 0
    var url = function() {
      numCalls++
      return "hello.html"
    }

    navigate(this.frame)
    .pjax({ url: url, container: "#main" }, function(frame) {
      equal(frame.$("#main > p").html().trim(), "Hello!")
      equal(numCalls, 1)
    })
  })

  asyncTest("sets X-PJAX header on XHR request", 1, function() {
    navigate(this.frame)
    .pjax({ url: "env.html", container: "#main" }, function(frame) {
      var env = JSON.parse(frame.$("#env").text())
      equal(env["HTTP_X_PJAX"], "true")
    })
  })

  asyncTest("sets X-PJAX-Container header to container on XHR request", 1, function() {
    navigate(this.frame)
    .pjax({ url: "env.html", container: "#main" }, function(frame) {
      var env = JSON.parse(frame.$("#env").text())
      equal(env["HTTP_X_PJAX_CONTAINER"], "#main")
    })
  })

  asyncTest("sets hidden _pjax param on XHR GET request", 1, function() {
    navigate(this.frame)
    .pjax({ data: undefined, url: "env.html", container: "#main" }, function(frame) {
      var env = JSON.parse(frame.$("#env").text())
      equal(env["rack.request.query_hash"]["_pjax"], "#main")
    })
  })

  asyncTest("sets hidden _pjax param if array data is supplied", 1, function() {
    var data = [{ name: "foo", value: "bar" }]

    navigate(this.frame)
    .pjax({ data: data, url: "env.html", container: "#main" }, function(frame) {
      var env = JSON.parse(frame.$("#env").text())
      deepEqual(env["rack.request.query_hash"], {
        "_pjax": "#main"
      , "foo": "bar"
      })
    })
  })

  asyncTest("sets hidden _pjax param if object data is supplied", 1, function() {
    var data = { foo: "bar" }

    navigate(this.frame)
    .pjax({ data: data, url: "env.html", container: "#main" }, function(frame) {
      var env = JSON.parse(frame.$("#env").text())
      deepEqual(env["rack.request.query_hash"], {
        "_pjax": "#main"
      , "foo": "bar"
      })
    })
  })

  asyncTest("preserves query string on GET request", 3, function() {
    navigate(this.frame)
    .pjax({ url: "env.html?foo=1&bar=2", container: "#main" }, function(frame) {
      equal(frame.location.pathname, "/env.html")
      equal(frame.location.search, "?foo=1&bar=2")

      var env = JSON.parse(frame.$("#env").text())
      deepEqual(env["rack.request.query_hash"], {
        "_pjax": "#main"
      , "foo": "1"
      , "bar": "2"
      })
    })
  })

  asyncTest("GET data is appended to query string", 6, function() {
    var data = { foo: 1, bar: 2 }

    navigate(this.frame)
    .pjax({ data: data, url: "env.html", container: "#main" }, function(frame) {
      equal(frame.location.pathname, "/env.html")
      equal(frame.location.search, "?foo=1&bar=2")

      var env = JSON.parse(frame.$("#env").text())
      deepEqual(env["rack.request.query_hash"], {
        "_pjax": "#main"
      , "foo": "1"
      , "bar": "2"
      })
    })

    var frame = this.frame
    setTimeout(function() {
      // URL is set immediately
      equal(frame.location.pathname, "/env.html")
      equal(frame.location.search, "?foo=1&bar=2")
      equal(frame.location.href.indexOf("#"), -1)
    }, 0)
  })

  asyncTest("GET data is merged into query string", 6, function() {
    var data = { bar: 2 }

    navigate(this.frame)
    .pjax({ data: data, url: "env.html?foo=1", container: "#main" }, function(frame) {
      equal(frame.location.pathname, "/env.html")
      equal(frame.location.search, "?foo=1&bar=2")

      var env = JSON.parse(frame.$("#env").text())
      deepEqual(env["rack.request.query_hash"], {
        "_pjax": "#main"
      , "foo": "1"
      , "bar": "2"
      })
    })

    var frame = this.frame
    setTimeout(function() {
      // URL is set immediately
      equal(frame.location.pathname, "/env.html")
      equal(frame.location.search, "?foo=1&bar=2")
      equal(frame.location.href.indexOf("#"), -1)
    }, 0)
  })

  asyncTest("mixed containers", 6, function() {
    navigate(this.frame)
    .pjax({ url: "fragment.html", container: "#main" })
    .pjax({ url: "aliens.html", container: "#foo" }, function(frame) {
      equal(frame.$("#main > #foo > ul > li").last().text(), "aliens")
    })
    .back(-1, function(frame) {
      equal(frame.$("#main > #foo").text().trim(), "Foo")
    })
    .pjax({ url: "env.html", replace: true, fragment: "#env", container: "#bar" }, function(frame) {
      // This replaceState shouldn't affect restoring other popstates
      equal(frame.$("#main > #foo").text().trim(), "Foo")
      ok(JSON.parse(frame.$("#bar").text()))
    })
    .back(-1, function(frame) {
      equal(frame.$("#main > ul > li").first().text(), "home")
    })
    .back(+1)
    .back(+1, function(frame) {
      equal(frame.$("#main > #foo > ul > li").last().text(), "aliens")
    })
  })

  asyncTest("only fragment is inserted", 2, function() {
    navigate(this.frame)
    .pjax({ url: "hello.html?layout=true", fragment: "#main", container: "#main" }, function(frame) {
      equal(frame.$("#main > p").html().trim(), "Hello!")
      equal(frame.document.title, "Hello")
    })
  })

  asyncTest("use body as fragment", 2, function() {
    navigate(this.frame)
    .pjax({ url: "hello.html?layout=true", fragment: "body", container: "body" }, function(frame) {
      equal(frame.$("body > #main > p").html().trim(), "Hello!")
      equal(frame.document.title, "Hello")
    })
  })

  asyncTest("fragment sets title to response title attr", 2, function() {
    navigate(this.frame)
    .pjax({ url: "fragment.html", fragment: "#foo", container: "#main" }, function(frame) {
      equal(frame.$("#main > p").html(), "Foo")
      equal(frame.document.title, "Foo")
    })
  })

  asyncTest("fragment sets title to response data-title attr", 2, function() {
    navigate(this.frame)
    .pjax({ url: "fragment.html", fragment: "#bar", container: "#main" }, function(frame) {
      equal(frame.$("#main > p").html(), "Bar")
      equal(frame.document.title, "Bar")
    })
  })

  asyncTest("missing fragment falls back to full load", 2, function() {
    var iframe = this.iframe

    navigate(this.frame)
    .pjax({ url: "hello.html?layout=true", fragment: "#missing", container: "#main" }, function() {
      return new PoorMansPromise(function(resolve) {
        iframe.onload = function() { resolve(this.contentWindow) }
      }).then(function(frame) {
        equal(frame.$("#main p").html(), "Hello!")
        equal(frame.location.pathname, "/hello.html")
      })
    })
  })

  asyncTest("missing data falls back to full load", 2, function() {
    var iframe = this.iframe

    navigate(this.frame)
    .pjax({ url: "empty.html", container: "#main" }, function() {
      return new PoorMansPromise(function(resolve) {
        iframe.onload = function() { resolve(this.contentWindow) }
      }).then(function(frame) {
        equal(frame.$("#main").html().trim(), "")
        equal(frame.location.pathname, "/empty.html")
      })
    })
  })

  asyncTest("full html page falls back to full load", 2, function() {
    var iframe = this.iframe

    navigate(this.frame)
    .pjax({ url: "hello.html?layout=true", container: "#main" }, function() {
      return new PoorMansPromise(function(resolve) {
        iframe.onload = function() { resolve(this.contentWindow) }
      }).then(function(frame) {
        equal(frame.$("#main p").html(), "Hello!")
        equal(frame.location.pathname, "/hello.html")
      })
    })
  })

  asyncTest("header version mismatch does a full load", 2, function() {
    var iframe = this.iframe
    this.frame.$.pjax.defaults.version = "v2"

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function() {
      return new PoorMansPromise(function(resolve) {
        iframe.onload = function() { resolve(this.contentWindow) }
      }).then(function(frame) {
        equal(frame.$("#main p").html(), "Hello!")
        equal(frame.location.pathname, "/hello.html")
      })
    })
  })

  asyncTest("triggers pjax:start/end events from container", 12, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:start pjax:end", function(event, xhr, options) {
      eventLog.push(arguments)
    })

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(eventLog.length, 2)
      $.each(["pjax:start", "pjax:end"], function(i, expectedType) {
        (function(event, xhr, options){
          equal(event.type, expectedType)
          equal(event.target, container)
          equal(event.relatedTarget, null)
          equal(typeof xhr.abort, "function")
          equal(options.url, "hello.html")
        }).apply(this, eventLog[i])
      })
    })
  })

  asyncTest("events preserve explicit target as relatedTarget", 7, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:start pjax:end", function(event, xhr, options) {
      eventLog.push(event)
    })

    navigate(this.frame)
    .pjax({ url: "hello.html", target: container, container: "#main" }, function(frame) {
      $.each(["pjax:start", "pjax:end"], function(i, expectedType) {
        var event = eventLog[i]
        equal(event.type, expectedType)
        equal(event.target, container)
        equal(event.relatedTarget, container)
      })
    })
  })

  asyncTest("stopping pjax:beforeSend prevents the request", 6, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:beforeSend", function(event, xhr, settings) {
      eventLog.push(arguments)
      return false
    })

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      ok(false)
    })

    setTimeout(function() {
      equal(eventLog.length, 1)
      ;(function(event, xhr, settings){
        equal(event.type, "pjax:beforeSend")
        equal(event.target, container)
        equal(typeof xhr.abort, "function")
        equal(settings.dataType, "html")
      }).apply(this, eventLog[0])
      start()
    }, 100)
  })

  asyncTest("triggers pjax:beforeReplace event from container", 9, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:beforeReplace", function(event, contents, options) {
      eventLog.push(arguments)
      equal(container.textContent.indexOf("Hello!"), -1)
    })

    var urlPrefix = location.protocol + "//" + location.host

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(eventLog.length, 1)

      ;(function(event, contents, options){
        equal(event.target, container)
        equal(event.state.url, urlPrefix + "/hello.html")
        equal(event.previousState.url, urlPrefix + "/home.html")
        equal(contents[0].nodeName, "P")
        // FIXME: Should this be absolute URL?
        equal(options.url, "hello.html")
      }).apply(this, eventLog[0])

      ok(container.textContent.indexOf("Hello!") >= 0)
    })
  })

  asyncTest("triggers pjax:success/complete events from container", function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:success pjax:complete", function(event) {
      eventLog.push(arguments)
    })

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(eventLog.length, 2)

      ;(function(event, data, status, xhr, options){
        equal(event.type, "pjax:success")
        equal(event.target, container)
        ok(data.indexOf("<p>Hello!</p>") >= 0)
        equal(status, "success")
        equal(typeof xhr.abort, "function")
        equal(options.url, "hello.html")
      }).apply(this, eventLog[0])

      ;(function(event, xhr, status, options){
        equal(event.type, "pjax:complete")
        equal(event.target, container)
        equal(typeof xhr.abort, "function")
        equal(status, "success")
        equal(options.url, "hello.html")
      }).apply(this, eventLog[1])
    })
  })

  asyncTest("triggers pjax:error event from container", function() {
    var frame = this.frame

    frame.$("#main").on("pjax:error", function(event, xhr, status, error, options) {
      ok(event)
      equal(xhr.status, 500)
      equal(status, 'error')
      equal(error.trim(), 'Internal Server Error')
      equal(options.url, "boom.html")
      start()
    })

    frame.$.pjax({
      url: "boom.html",
      container: "#main"
    })
  })

  asyncTest("stopping pjax:error disables default behavior", function() {
    var frame = this.frame

    frame.$("#main").on("pjax:error", function(event, xhr) {
      ok(true)

      setTimeout(function() {
        xhr.abort()
        start()
      }, 0)

      return false
    })

    this.iframe.onload = function() { ok(false) }

    frame.$.pjax({
      url: "boom.html",
      container: "#main"
    })
  })

  asyncTest("loads fallback if timeout event isn't handled", function() {
    var frame = this.frame

    frame.$.pjax({
      url: "timeout.html#hello",
      container: "#main"
    })

    equal(frame.location.pathname, "/timeout.html")
    equal(frame.location.hash, "#hello")

    this.iframe.onload = function() {
      equal(frame.$("#main p").html(), "SLOW DOWN!")
      equal(frame.location.pathname, "/timeout.html")
      equal(frame.location.hash, "#hello")
      start()
    }
  })

  asyncTest("stopping pjax:timeout disables default behavior", function() {
    var frame = this.frame

    frame.$("#main").on("pjax:timeout", function(event, xhr) {
      ok(true)

      setTimeout(function() {
        xhr.abort()
        start()
      }, 0)

      return false
    })

    this.iframe.onload = function() { ok(false) }

    frame.$.pjax({
      url: "timeout.html",
      container: "#main"
    })
  })

  asyncTest("POST never times out", function() {
    var frame = this.frame

    frame.$("#main").on("pjax:complete", function() {
      equal(frame.$("#main p").html(), "SLOW DOWN!")
      equal(frame.location.pathname, "/timeout.html")
      start()
    })
    frame.$("#main").on("pjax:timeout", function(event, xhr) {
      ok(false)
    })
    this.iframe.onload = function() { ok(false) }

    frame.$.pjax({
      type: 'POST',
      url: "timeout.html",
      container: "#main"
    })
  })

  asyncTest("500 loads fallback", function() {
    var frame = this.frame

    frame.$.pjax({
      url: "boom.html",
      container: "#main"
    })

    this.iframe.onload = function() {
      equal(frame.$("#main p").html(), "500")
      equal(frame.location.pathname, "/boom.html")
      start()
    }
  })

  asyncTest("POST 500 never loads fallback", function() {
    var frame = this.frame

    frame.$("#main").on("pjax:complete", function() {
      equal(frame.location.pathname, "/boom.html")
      start()
    })
    frame.$("#main").on("pjax:error", function(event, xhr) {
      ok(true)
    })
    frame.$("#main").on("pjax:timeout", function(event, xhr) {
      ok(false)
    })
    this.iframe.onload = function() { ok(false) }

    frame.$.pjax({
      type: 'POST',
      url: "boom.html",
      container: "#main"
    })
  })

  function goBack(frame, callback) {
    setTimeout(function() {
      frame.$("#main").one("pjax:end", callback)
      frame.history.back()
    }, 0)
  }

  asyncTest("clicking back while loading cancels XHR", function() {
    var frame = this.frame

    frame.$('#main').on('pjax:timeout', function(event) {
      event.preventDefault()
    })

    frame.$("#main").one('pjax:send', function() {

      // Check that our request is aborted (need to check
      // how robust this is across browsers)
      frame.$("#main").one('pjax:complete', function(e, xhr, textStatus) {
        equal(xhr.status, 0)
        equal(textStatus, 'abort')
      })

      setTimeout(function() {
        frame.history.back()
      }, 250)

      // Make sure the URL and content remain the same after the
      // XHR would have arrived (delay on timeout.html is 1s)
      setTimeout(function() {
        var afterBackLocation = frame.location.pathname
        var afterBackTitle = frame.document.title

        setTimeout(function() {
          equal(frame.location.pathname, afterBackLocation)
          equal(frame.document.title, afterBackTitle)
          start()
        }, 1000)
      }, 500)
    })

    frame.$.pjax({
      url: "timeout.html",
      container: "#main"
    })
  })

  asyncTest("popstate going back/forward in history", 14, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:popstate", function(event) {
      eventLog.push(event)
    })

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" }, function(frame) {
      equal(frame.location.pathname, "/hello.html")
      equal(frame.document.title, "Hello")
      equal(eventLog.length, 0)
    })
    .back(-1, function(frame) {
      equal(frame.location.pathname, "/home.html")
      equal(frame.document.title, "Home")
      equal(eventLog.length, 1)
      equal(eventLog[0].direction, "back")
      equal(eventLog[0].state.container, "#main")
    })
    .back(+1, function(frame) {
      equal(frame.location.pathname, "/hello.html")
      equal(frame.document.title, "Hello")
      equal(eventLog.length, 2)
      equal(eventLog[1].direction, "forward")
      equal(eventLog[1].state.container, "#main")
    })
  })

  asyncTest("popstate restores original scroll position", 2, function() {
    this.frame.scrollTo(0, 100)
    equal(this.frame.pageYOffset, 100)

    navigate(this.frame)
    .pjax({ url: "long.html", container: "#main" }, function(frame) {
      equal(frame.pageYOffset, 0)
    })
    .back(-1, function(frame) {
      // FIXME: Seems like this functionality is natively broken in PhantomJS and Safari
      // equal(frame.pageYOffset, 100)
    })
  })

  asyncTest("popstate triggers pjax:beforeReplace event", 10, function() {
    var eventLog = []
    var container = this.frame.document.getElementById("main")
    ok(container)

    this.frame.$(container).on("pjax:beforeReplace", function(event, contents, options) {
      eventLog.push(arguments)
      if (eventLog.length == 2) {
        equal(container.textContent.indexOf("home"), -1)
      }
    })

    var urlPrefix = location.protocol + "//" + location.host

    navigate(this.frame)
    .pjax({ url: "hello.html", container: "#main" })
    .back(-1, function(frame) {
      equal(eventLog.length, 2)

      // FIXME: First "pjax:beforeReplace" event has relative URL,
      // while the 2nd (triggered by popstate) has absolute URL.
      equal(eventLog[0][2].url, "hello.html")

      ;(function(event, contents, options){
        equal(event.target, container)
        equal(event.previousState.url, urlPrefix + "/hello.html")
        equal(event.state.url, urlPrefix + "/home.html")
        equal(contents[1].nodeName, "UL")
        equal(options.url, urlPrefix + "/home.html")
      }).apply(this, eventLog[1])

      ok(container.textContent.indexOf("home") >= 0)
    })
  })

  asyncTest("no initial pjax:popstate event", function() {
    var frame = this.frame
    var count = 0

    window.iframeLoad = function() {
      count++

      if (count == 1) {
        equal(frame.location.pathname, "/home.html")
        frame.location.pathname = "/hello.html"
      } else if (count == 2) {
        equal(frame.location.pathname, "/hello.html")
        frame.$.pjax({url: "env.html", container: "#main"})
      } else if (count == 3) {
        equal(frame.location.pathname, "/env.html")
        frame.history.back()
      } else if (count == 4) {
        equal(frame.location.pathname, "/hello.html")
        frame.history.back()
      } else if (count == 5) {
        equal(frame.location.pathname, "/home.html")
        frame.history.forward()
      } else if (count == 6) {
        frame.$('#main').on('pjax:popstate', function(event) {
          if (count == 6) {
            // Should skip pjax:popstate since there's no initial pjax.state
            ok(event.state.url.match("/hello.html"), event.state.url)
            ok(false)
          } else if (count == 7) {
            ok(event.state.url.match("/env.html"), event.state.url)
            ok(true)
          }
        })

        frame.$(frame.window).on('popstate', function() {
          if (count == 6) {
            count++
            frame.history.forward()
          }
        })

        // Browsers that don't fire initial "popstate" should just resume
        setTimeout(function() {
          start()
        }, 100)
      }
    }

    window.iframeLoad()
  })

  asyncTest("hitting the back button obeys maxCacheLength", function() {
    var frame = this.frame
    var count = 0
    var didHitServer

    // Reduce the maxCacheLength for this spec to make it easier to test.
    frame.$.pjax.defaults.maxCacheLength = 1

    // This event will fire only when we request a page from the server, so we
    // can use it to detect a cache miss.
    frame.$("#main").on("pjax:beforeSend", function() {
      didHitServer = true
    })

    frame.$("#main").on("pjax:end", function() {
      count++

      // First, navigate twice.
      if (count == 1) {
        frame.$.pjax({url: "env.html", container: "#main"})
      } else if (count == 2) {
        frame.$.pjax({url: "hello.html", container: "#main"})
      } else if (count == 3) {
        // There should now be one item in the back cache.
        didHitServer = false
        frame.history.back()
      } else if (count == 4) {
        equal(frame.location.pathname, "/env.html", "Went backward")
        equal(didHitServer, false, "Hit cache")
        frame.history.back()
      } else if (count == 5) {
        equal(frame.location.pathname, "/hello.html", "Went backward")
        equal(didHitServer, true, "Hit server")
        start()
      }
    })

    frame.$.pjax({url: "hello.html", container: "#main"})
  })

  asyncTest("hitting the forward button obeys maxCacheLength", function() {
    var frame = this.frame
    var count = 0
    var didHitServer

    // Reduce the maxCacheLength for this spec to make it easier to test.
    frame.$.pjax.defaults.maxCacheLength = 1

    // This event will fire only when we request a page from the server, so we
    // can use it to detect a cache miss.
    frame.$("#main").on("pjax:beforeSend", function() {
      didHitServer = true
    })

    frame.$("#main").on("pjax:end", function() {
      count++

      if (count == 1) {
        frame.$.pjax({url: "env.html", container: "#main"})
      } else if (count == 2) {
        frame.$.pjax({url: "hello.html", container: "#main"})
      } else if (count == 3) {
        frame.history.back()
      } else if (count == 4) {
        frame.history.back()
      } else if (count == 5) {
        // There should now be one item in the forward cache.
        didHitServer = false
        frame.history.forward()
      } else if (count == 6) {
        equal(frame.location.pathname, "/env.html", "Went forward")
        equal(didHitServer, false, "Hit cache")
        frame.history.forward()
      } else if (count == 7) {
        equal(frame.location.pathname, "/hello.html", "Went forward")
        equal(didHitServer, true, "Hit server")
        start()
      }
    })

    frame.$.pjax({url: "hello.html", container: "#main"})
  })

  asyncTest("setting maxCacheLength to 0 disables caching", function() {
    var frame = this.frame
    var count = 0
    var didHitServer

    // Set maxCacheLength to 0 to disable caching completely.
    frame.$.pjax.defaults.maxCacheLength = 0

    // This event will fire only when we request a page from the server, so we
    // can use it to detect a cache miss.
    frame.$("#main").on("pjax:beforeSend", function() {
      didHitServer = true
    })

    frame.$("#main").on("pjax:end", function() {
      count++

      if (count == 1) {
        didHitServer = false
        frame.$.pjax({url: "env.html", container: "#main"})
      } else if (count == 2) {
        equal(frame.location.pathname, "/env.html", "Navigated to a new page")
        equal(didHitServer, true, "Hit server")
        didHitServer = false
        frame.history.back()
      } else if (count == 3) {
        equal(frame.location.pathname, "/hello.html", "Went backward")
        equal(didHitServer, true, "Hit server")
        didHitServer = false
        frame.history.forward()
      } else if (count == 4) {
        equal(frame.location.pathname, "/env.html", "Went forward")
        equal(didHitServer, true, "Hit server")
        start()
      }
    })

    frame.$.pjax({url: "hello.html", container: "#main"})
  })

  asyncTest("lazily sets initial $.pjax.state", function() {
    var frame = this.frame

    equal(frame.$.pjax.state, null)

    frame.$('#main').on("pjax:success", function() {
      start()
    })
    frame.$.pjax({
      url: "hello.html",
      container: "#main"
    })

    var initialState = frame.$.pjax.state
    ok(initialState.id)
    equal(initialState.url, "http://" + frame.location.host + "/home.html")
    equal(initialState.container, "#main")
  })

  asyncTest("updates $.pjax.state to new page", function() {
    var frame = this.frame

    frame.$('#main').on("pjax:success", function() {
      var state = frame.$.pjax.state
      ok(state.id)
      equal(state.url, "http://" + frame.location.host + "/hello.html#new")
      equal(state.container, "#main")
      start()
    })
    frame.$.pjax({
      url: "hello.html#new",
      container: "#main"
    })

    var initialState = frame.$.pjax.state
  })

  asyncTest("new id is generated for new pages", function() {
    var frame = this.frame

    var oldId

    frame.$('#main').on("pjax:success", function() {
      ok(frame.$.pjax.state.id)
      notEqual(oldId, frame.$.pjax.state.id)
      start()
    })
    frame.$.pjax({
      url: "hello.html",
      container: "#main"
    })

    ok(frame.$.pjax.state.id)
    oldId = frame.$.pjax.state.id
  })

  asyncTest("id is the same going back", function() {
    var frame = this.frame

    var oldId

    equal(frame.location.pathname, "/home.html")

    frame.$('#main').on("pjax:complete", function() {
      ok(frame.$.pjax.state.id)
      notEqual(oldId, frame.$.pjax.state.id)

      ok(frame.history.length > 1)
      goBack(frame, function() {
        ok(frame.$.pjax.state.id)
        equal(oldId, frame.$.pjax.state.id)
        start()
      })
    })
    frame.$.pjax({
      url: "hello.html",
      container: "#main"
    })

    ok(frame.$.pjax.state.id)
    oldId = frame.$.pjax.state.id
  })

  asyncTest("handles going back to pjaxed state after reloading a fragment navigation", function() {
    var iframe = this.iframe
    var frame = this.frame
    var supportsHistoryState = 'state' in window.history

    // Get some pjax state in the history.
    frame.$.pjax({
      url: "hello.html",
      container: "#main",
    })
    frame.$("#main").on("pjax:complete", function() {
      var state = frame.history.state
      ok(frame.$.pjax.state)
      if (supportsHistoryState)
        ok(frame.history.state)

      // Navigate to a fragment, which will result in a new history entry with
      // no state object. $.pjax.state remains unchanged however.
      iframe.src = frame.location.href + '#foo'
      ok(frame.$.pjax.state)
      if (supportsHistoryState)
        ok(!frame.history.state)

      // Reload the frame. This will clear out $.pjax.state.
      frame.location.reload()
      $(iframe).one("load", function() {
        ok(!frame.$.pjax.state)
        if (supportsHistoryState)
          ok(!frame.history.state)

        // Go back to #main. We'll get a popstate event with a pjax state
        // object attached from the initial pjax navigation, even though
        // $.pjax.state is null.
        window.iframeLoad = function() {
          ok(frame.$.pjax.state)
          if (supportsHistoryState) {
            ok(frame.history.state)
            equal(frame.$.pjax.state.id, state.id)
          }
          start()
        }
        frame.history.back()
      })
    })
  })

  asyncTest("handles going back to page after loading an error page", function() {
    var frame = this.frame
    var iframe = this.iframe

    equal(frame.location.pathname, "/home.html")
    equal(frame.document.title, "Home")

    $(iframe).one("load", function() {

      window.iframeLoad = function() {
        equal(frame.location.pathname, "/home.html")
        equal(frame.document.title, "Home")

        start()
      }

      frame.history.back()
    })

    frame.$.pjax({
      url: "boom_sans_pjax.html",
      container: "#main"
    })
  })

  asyncTest("copes with ampersands when pushing urls", 2, function() {
    navigate(this.frame)
    .pjax({ url: "/some-&-path/hello.html", container: "#main" }, function(frame) {
      equal(frame.location.pathname, "/some-&-path/hello.html")
      equal(frame.location.search, "")
    })
  })
}


================================================
FILE: test/unit/pjax_fallback.js
================================================
// $.pjax fallback tests should run on both pushState and
// non-pushState compatible browsers.
$.each([true, false], function() {

var disabled = this == false
var s = disabled ? " (disabled)" : ""

var ua = navigator.userAgent
var safari = ua.match("Safari") && !ua.match("Chrome") && !ua.match("Edge")
var chrome = ua.match("Chrome") && !ua.match("Edge")

module("$.pjax fallback"+s, {
  setup: function() {
    var self = this
    stop()
    this.loaded = function(frame) {
      self.frame  = frame
      self.loaded = $.noop
      start()
    }
    window.iframeLoad = function(frame) {
      setTimeout(function() {
        if (disabled && frame.$ && frame.$.pjax) frame.$.pjax.disable()
        self.loaded(frame)
      }, 0)
    }
    $("#qunit-fixture").append("<iframe src='home.html'>")
  },
  teardown: function() {
    delete window.iframeLoad
  }
})


asyncTest("sets new url"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: "hello.html",
    container: "#main"
  })
})

asyncTest("sets new url for function"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    start()
  }

  frame.$.pjax({
    url: function() { return "hello.html" },
    container: "#main"
  })
})

asyncTest("updates container html"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.$("#main p").html(), "Hello!")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sets title to response <title>"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    equal(frame.document.title, "Hello")
    start()
  }

  frame.$.pjax({
    url: "/hello.html",
    container: "#main"
  })
})

asyncTest("sends correct HTTP referer"+s, function() {
  var frame = this.frame

  this.loaded = function(frame) {
    var referer = frame.document.getElementById("referer").textContent
    ok(referer.match("/home.html"), referer)
    start()
  }

  frame.$.pjax({
    url: "/referer.html",
    container: "#main"
  })
})

asyncTest("scrolls to top of the page"+s, function() {
  var frame = this.frame

  frame.window.scrollTo(0, 100)
  equal(frame.window.pageYOffset, 100)

  this.loaded = function(frame) {
    equal(frame.window.pageYOffset, 0)
    start()
  }

  frame.$.pjax({
    url: "/long.html",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at top page"+s, function() {
  var frame = this.frame

  equal(frame.window.pageYOffset, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.location.pathname, "/anchor.html")
      equal(frame.location.hash, "#top")
      equal(frame.window.pageYOffset, 8)
      start()
    }, 100)
  }

  frame.$.pjax({
    url: "/anchor.html#top",
    container: "#main"
  })

  if (disabled) {
    equal(frame.location.pathname, "/home.html")
    equal(frame.location.href.indexOf("#"), -1)
  } else {
    equal(frame.location.pathname, "/anchor.html")
    equal(frame.location.hash, "#top")
  }
})

asyncTest("empty anchor doesn't scroll page"+s, function() {
  var frame = this.frame

  equal(frame.window.pageYOffset, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.pageYOffset, 0)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#",
    container: "#main"
  })
})

asyncTest("scrolls to anchor at bottom page"+s, function() {
  var frame = this.frame

  equal(frame.window.pageYOffset, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.pageYOffset, 10008)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#bottom",
    container: "#main"
  })
})

asyncTest("scrolls to named encoded anchor"+s, function() {
  var frame = this.frame

  equal(frame.window.pageYOffset, 0)

  this.loaded = function(frame) {
    setTimeout(function() {
      equal(frame.window.pageYOffset, 10008)
      start()
    }, 10)
  }

  frame.$.pjax({
    url: "/anchor.html#%62%6F%74%74%6F%6D",
    container: "#main"
  })
})

asyncTest("sets GET method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    container: "#main"
  })
})


asyncTest("sets POST method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets PUT method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "PUT")
    start()
  }

  frame.$.pjax({
    type: 'PUT',
    url: "env.html",
    container: "#main"
  })
})

asyncTest("sets DELETE method"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "DELETE")
    start()
  }

  frame.$.pjax({
    type: 'DELETE',
    url: "env.html",
    container: "#main"
  })
})


asyncTest("GET with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("POST with data object"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: {foo: 'bar'},
    container: "#main"
  })
})

asyncTest("GET with data array"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo%5B%5D=bar&foo%5B%5D=baz")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    var expected = {'foo': ['bar', 'baz']}
    if (!disabled) expected._pjax = "#main"
    deepEqual(env['rack.request.query_hash'], expected)

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: [{name: "foo[]", value: "bar"}, {name: "foo[]", value: "baz"}],
    container: "#main"
  })
})

asyncTest("POST with data array"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    var expected = {'foo': ['bar', 'baz']}
    if (!disabled) expected._pjax = "#main"
    deepEqual(env['rack.request.form_hash'], expected)

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: [{name: "foo[]", value: "bar"}, {name: "foo[]", value: "baz"}],
    container: "#main"
  })
})

asyncTest("GET with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "?foo=bar")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "GET")
    equal(env['rack.request.query_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'GET',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

asyncTest("POST with data string"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/env.html")
    equal(frame.location.search, "")

    var env = JSON.parse(frame.$("#env").text())
    equal(env['REQUEST_METHOD'], "POST")
    equal(env['rack.request.form_hash']['foo'], 'bar')

    start()
  }

  frame.$.pjax({
    type: 'POST',
    url: "env.html",
    data: "foo=bar",
    container: "#main"
  })
})

asyncTest("handle form submit"+s, function() {
  var frame = this.frame

  frame.$(frame.document).on("submit", "form", function(event) {
    frame.$.pjax.submit(event, "#main")
  })

  this.loaded = function() {
    var env = JSON.parse(frame.$("#env").text())
    var expected = {foo: "1", bar: "2"}
    if (!disabled) expected._pjax = "#main"
    deepEqual(env['rack.request.query_hash'], expected)
    start()
  }

  frame.$("form").submit()
})

asyncTest("browser URL is correct after redirect"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    var expectedHash = safari && disabled ? "" : "#new"
    equal(frame.location.hash, expectedHash)
    start()
  }

  frame.$.pjax({
    url: "redirect.html#new",
    container: "#main"
  })
})

asyncTest("server can't affect anchor after redirect"+s, function() {
  var frame = this.frame

  this.loaded = function() {
    equal(frame.location.pathname, "/hello.html")
    var expectedHash = safari && disabled ? "" : "#new"
    equal(frame.location.hash, expectedHash)
    start()
  }

  frame.$.pjax({
    url: "redirect.html?anchor=server#new",
    container: "#main"
  })
})

})


================================================
FILE: test/views/aliens.erb
================================================
<%= title 'aliens' %>

<ul>
  <li><a href="/home.html">home</a></li>
  <li><a href="/dinosaurs.html">dinosaurs</a></li>
  <li>aliens</li>
</ul>

<img src="/img/aliens.jpg" title="aliens">

<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/anchor.erb
================================================
<%= title 'Anchor' %>
<div id="top" style="width:500px;height:10000px;"></div>
<a name="bottom" style="width:500px;height:10000px;display:block;"></a>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/boom.erb
================================================
<p>500</p>


================================================
FILE: test/views/boom_sans_pjax.erb
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>500 sans pjax</title>
</head>
<body>
  <div id="main">
    <p>500 sans pjax</p>
  </div>
</body>
</html>


================================================
FILE: test/views/dinosaurs.erb
================================================
<%= title 'dinosaurs' %>

<ul>
  <li><a href="/home.html">home</a></li>
  <li>dinosaurs</li>
  <li><a href="/aliens.html">aliens</a></li>
</ul>

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/GcjxwXCxBBU" frameborder="0" allowfullscreen></iframe>

<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/double_title.erb
================================================
<%= title 'Hello' %>
<p><title>World!</title> Hello!</p>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/empty.erb
================================================


================================================
FILE: test/views/env.erb
================================================
<div id="env"><%= Rack::Utils.escape_html JSON.generate(request.env) %></div>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/fragment.erb
================================================
<div id="foo" title="Foo">
  <p>Foo</p>
</div>

<div id="bar" data-title="Bar">
  <p>Bar</p>
</div>


================================================
FILE: test/views/hello.erb
================================================
<%= title 'Hello' %>
<p>Hello!</p>
How's it going?
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/home.erb
================================================
<%= title 'Home' %>

<ul>
  <li>home</li>
  <li><a href="/dinosaurs.html">dinosaurs</a></li>
  <li><a href="/aliens.html">aliens</a></li>
  <li><a href="https://www.google.com/">Google</a></li>
  <li><a href="#main">Main</a></li>
  <li><a href="#">Empty</a></li>
</ul>

<form action="env.html" method="GET">
  <input name="foo" value="1">
  <input name="bar" value="2">
</form>

<div style="width:500px;height:10000px;"></div>

<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/layout.erb
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><%= @title %></title>
  <script type="text/javascript" src="/vendor/jquery-<%= jquery_version %>.js"></script>
  <script type="text/javascript" src="/jquery.pjax.js"></script>
</head>
<body>
  <div id="main">
    <%= yield %>
  </div>
</body>
</html>


================================================
FILE: test/views/long.erb
================================================
<%= title 'Long' %>
<p>Long Page</p>
<div style="width:500px;height:10000px;"></div>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/nested_title.erb
================================================
<p><%= title 'Hello' %> Hello!</p>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/qunit.erb
================================================
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/vendor/qunit.css">
  <meta name="viewport" content="initial-scale=1.0,width=device-width">

  <script type="text/javascript" src="/vendor/jquery-<%= jquery_version %>.js"></script>
  <script type="text/javascript" src="/vendor/qunit.js"></script>
  <script type="text/javascript">QUnit.config.testTimeout = 2000</script>
  <script type="text/javascript" src="/jquery.pjax.js"></script>
  <script type="text/javascript" src="/test/unit/helpers.js"></script>
  <script type="text/javascript" src="/test/unit/pjax.js"></script>
  <script type="text/javascript" src="/test/unit/fn_pjax.js"></script>
  <script type="text/javascript" src="/test/unit/pjax_fallback.js"></script>
</head>
<body>
  <div id="qunit"></div>
  <ol id="qunit-fixture"></ol>
</body>
</html>


================================================
FILE: test/views/referer.erb
================================================
<p id="referer"><%= request.referer %></p>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/scripts.erb
================================================
<p>Got some script tags here</p>
<script type="text/javascript" src="/test/evaled.js?1"></script>
<script src="/test/evaled.js?2"></script>
<script type="text/javascript">
  window.evaledInlineLog = window.evaledInlineLog || []
  window.evaledInlineLog.push('<%= params[:name] %>')
</script>
<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: test/views/timeout.erb
================================================
<%= title 'Timeout!' %>

<p>SLOW DOWN!</p>

<script type="text/javascript">window.parent.iframeLoad(window)</script>


================================================
FILE: vendor/jquery-1.12.js
================================================
/*!
 * jQuery JavaScript Library v1.12.4
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2016-05-20T17:17Z
 */

(function( global, factory ) {

	if ( typeof module === "object" && typeof module.exports === "object" ) {
		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket #14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//"use strict";
var deletedIds = [];

var document = window.document;

var slice = deletedIds.slice;

var concat = deletedIds.concat;

var push = deletedIds.push;

var indexOf = deletedIds.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var support = {};



var
	version = "1.12.4",

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	},

	// Support: Android<4.1, IE<9
	// Make sure we trim BOM and NBSP
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

	// Matches dashed string for camelizing
	rmsPrefix = /^-ms-/,
	rdashAlpha = /-([\da-z])/gi,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// Start with an empty selector
	selector: "",

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num != null ?

			// Return just the one element from the set
			( num < 0 ? this[ num + this.length ] : this[ num ] ) :

			// Return all the elements in a clean array
			slice.call( this );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;
		ret.context = this.context;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: deletedIds.sort,
	splice: deletedIds.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var src, copyIsArray, copy, name, options, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = jQuery.isArray( copy ) ) ) ) {

					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray( src ) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject( src ) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type( obj ) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type( obj ) === "array";
	},

	isWindow: function( obj ) {
		/* jshint eqeqeq: false */
		return obj != null && obj == obj.window;
	},

	isNumeric: function( obj ) {

		// parseFloat NaNs numeric-cast false positives (null|true|false|"")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		// adding 1 corrects loss of precision from parseFloat (#15100)
		var realStringObj = obj && obj.toString();
		return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	isPlainObject: function( obj ) {
		var key;

		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {

			// Not own constructor property must be Object
			if ( obj.constructor &&
				!hasOwn.call( obj, "constructor" ) &&
				!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
				return false;
			}
		} catch ( e ) {

			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Support: IE<9
		// Handle iteration over inherited properties before own properties.
		if ( !support.ownFirst ) {
			for ( key in obj ) {
				return hasOwn.call( obj, key );
			}
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	type: function( obj ) {
		if ( obj == null ) {
			return obj + "";
		}
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ toString.call( obj ) ] || "object" :
			typeof obj;
	},

	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && jQuery.trim( data ) ) {

			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data ); // jscs:ignore requireDotNotation
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// Support: Android<4.1, IE<9
	trim: function( text ) {
		return text == null ?
			"" :
			( text + "" ).replace( rtrim, "" );
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
					[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		var len;

		if ( arr ) {
			if ( indexOf ) {
				return indexOf.call( arr, elem, i );
			}

			len = arr.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {

				// Skip accessing in sparse arrays
				if ( i in arr && arr[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		while ( j < len ) {
			first[ i++ ] = second[ j++ ];
		}

		// Support: IE<9
		// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
		if ( len !== len ) {
			while ( second[ j ] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		var args, proxy, tmp;

		if ( typeof context === "string" ) {
			tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		args = slice.call( arguments, 2 );
		proxy = function() {
			return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	},

	now: function() {
		return +( new Date() );
	},

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
}
/* jshint ignore: end */

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );

function isArrayLike( obj ) {

	// Support: iOS 8.2 (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj && "length" in obj && obj.length,
		type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.2.1
 * http://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2015-10-17
 */
(function( window ) {

var i,
	support,
	Expr,
	getText,
	isXML,
	tokenize,
	compile,
	select,
	outermostContext,
	sortInput,
	hasDuplicate,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsHTML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,

	// Instance-specific data
	expando = "sizzle" + 1 * new Date(),
	preferredDoc = window.document,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// General-purpose constants
	MAX_NEGATIVE = 1 << 31,

	// Instance methods
	hasOwn = ({}).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	push_native = arr.push,
	push = arr.push,
	slice = arr.slice,
	// Use a stripped-down indexOf as it's faster than native
	// http://jsperf.com/thor-indexof-vs-for/5
	indexOf = function( list, elem ) {
		var i = 0,
			len = list.length;
		for ( ; i < len; i++ ) {
			if ( list[i] === elem ) {
				return i;
			}
		}
		return -1;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",

	// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
		"*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +
		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),

	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + identifier + ")" ),
		"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
		"TAG": new RegExp( "^(" + identifier + "|[*])" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rnative = /^[^{]+\{\s*\[native \w/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,
	rescape = /'|\\/g,

	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
	funescape = function( _, escaped, escapedWhitespace ) {
		var high = "0x" + escaped - 0x10000;
		// NaN means non-codepoint
		// Support: Firefox<24
		// Workaround erroneous numeric interpretation of +"0x"
		return high !== high || escapedWhitespace ?
			escaped :
			high < 0 ?
				// BMP codepoint
				String.fromCharCode( high + 0x10000 ) :
				// Supplemental Plane codepoint (surrogate pair)
				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	},

	// Used for iframes
	// See setDocument()
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE
	unloadHandler = function() {
		setDocument();
	};

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		(arr = slice.call( preferredDoc.childNodes )),
		preferredDoc.childNodes
	);
	// Support: Android<4.0
	// Detect silently failing push.apply
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			push_native.apply( target, slice.call(els) );
		} :

		// Support: IE<9
		// Otherwise append directly
		function( target, els ) {
			var j = target.length,
				i = 0;
			// Can't trust NodeList.length
			while ( (target[j++] = els[i++]) ) {}
			target.length = j - 1;
		}
	};
}

function Sizzle( selector, context, results, seed ) {
	var m, i, elem, nid, nidselect, match, groups, newSelector,
		newContext = context && context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {

		if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
			setDocument( context );
		}
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {

				// ID selector
				if ( (m = match[1]) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( (elem = context.getElementById( m )) ) {

							// Support: IE, Opera, Webkit
							// TODO: identify versions
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								results.push( elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE, Opera, Webkit
						// TODO: identify versions
						// getElementById can match elements by name instead of ID
						if ( newContext && (elem = newContext.getElementById( m )) &&
							contains( context, elem ) &&
							elem.id === m ) {

							results.push( elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[2] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( (m = match[3]) && support.getElementsByClassName &&
					context.getElementsByClassName ) {

					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( support.qsa &&
				!compilerCache[ selector + " " ] &&
				(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {

				if ( nodeType !== 1 ) {
					newContext = context;
					newSelector = selector;

				// qSA looks outside Element context, which is not what we want
				// Thanks to Andrew Dupont for this workaround technique
				// Support: IE <=8
				// Exclude object elements
				} else if ( context.nodeName.toLowerCase() !== "object" ) {

					// Capture the context ID, setting it first if necessary
					if ( (nid = context.getAttribute( "id" )) ) {
						nid = nid.replace( rescape, "\\$&" );
					} else {
						context.setAttribute( "id", (nid = expando) );
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
					while ( i-- ) {
						groups[i] = nidselect + " " + toSelector( groups[i] );
					}
					newSelector = groups.join( "," );

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;
				}

				if ( newSelector ) {
					try {
						push.apply( results,
							newContext.querySelectorAll( newSelector )
						);
						return results;
					} catch ( qsaError ) {
					} finally {
						if ( nid === expando ) {
							context.removeAttribute( "id" );
						}
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {
		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key + " " ) > Expr.cacheLength ) {
			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return (cache[ key + " " ] = value);
	}
	return cache;
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created div and expects a boolean result
 */
function assert( fn ) {
	var div = document.createElement("div");

	try {
		return !!fn( div );
	} catch (e) {
		return false;
	} finally {
		// Remove from its parent by default
		if ( div.parentNode ) {
			div.parentNode.removeChild( div );
		}
		// release memory in IE
		div = null;
	}
}

/**
 * Adds the same handler for all of the specified attrs
 * @param {String} attrs Pipe-separated list of attributes
 * @param {Function} handler The method that will be applied
 */
function addHandle( attrs, handler ) {
	var arr = attrs.split("|"),
		i = arr.length;

	while ( i-- ) {
		Expr.attrHandle[ arr[i] ] = handler;
	}
}

/**
 * Checks document order of two siblings
 * @param {Element} a
 * @param {Element} b
 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
 */
function siblingCheck( a, b ) {
	var cur = b && a,
		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
			( ~b.sourceIndex || MAX_NEGATIVE ) -
			( ~a.sourceIndex || MAX_NEGATIVE );

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( (cur = cur.nextSibling) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return (name === "input" || name === "button") && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction(function( argument ) {
		argument = +argument;
		return markFunction(function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ (j = matchIndexes[i]) ] ) {
					seed[j] = !(matches[j] = seed[j]);
				}
			}
		});
	});
}

/**
 * Checks a node for validity as a Sizzle context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context && typeof context.getElementsByTagName !== "undefined" && context;
}

// Expose support vars for convenience
support = Sizzle.support = {};

/**
 * Detects XML nodes
 * @param {Element|Object} elem An element or a document
 * @returns {Boolean} True iff elem is a non-HTML XML node
 */
isXML = Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var hasCompare, parent,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	docElem = document.documentElement;
	documentIsHTML = !isXML( document );

	// Support: IE 9-11, Edge
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	if ( (parent = document.defaultView) && parent.top !== parent ) {
		// Support: IE 11
		if ( parent.addEventListener ) {
			parent.addEventListener( "unload", unloadHandler, false );

		// Support: IE 9 - 10 only
		} else if ( parent.attachEvent ) {
			parent.attachEvent( "onunload", unloadHandler );
		}
	}

	/* Attributes
	---------------------------------------------------------------------- */

	// Support: IE<8
	// Verify that getAttribute really returns attributes and not properties
	// (excepting IE8 booleans)
	support.attributes = assert(function( div ) {
		div.className = "i";
		return !div.getAttribute("className");
	});

	/* getElement(s)By*
	---------------------------------------------------------------------- */

	// Check if getElementsByTagName("*") returns only elements
	support.getElementsByTagName = assert(function( div ) {
		div.appendChild( document.createComment("") );
		return !div.getElementsByTagName("*").length;
	});

	// Support: IE<9
	support.getElementsByClassName = rnative.test( document.getElementsByClassName );

	// Support: IE<10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert(function( div ) {
		docElem.appendChild( div ).id = expando;
		return !document.getElementsByName || !document.getElementsByName( expando ).length;
	});

	// ID find and filter
	if ( support.getById ) {
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var m = context.getElementById( id );
				return m ? [ m ] : [];
			}
		};
		Expr.filter["ID"] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute("id") === attrId;
			};
		};
	} else {
		// Support: IE6/7
		// getElementById is not reliable as a find shortcut
		delete Expr.find["ID"];

		Expr.filter["ID"] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &&
					elem.getAttributeNode("id");
				return node && node.value === attrId;
			};
		};
	}

	// Tag
	Expr.find["TAG"] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( tag );

			// DocumentFragment nodes don't have gEBTN
			} else if ( support.qsa ) {
				return context.querySelectorAll( tag );
			}
		} :

		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,
				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( (elem = results[i++]) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21)
	// We allow this because of a bug in IE8/9 that throws an error
	// whenever `document.activeElement` is accessed on an iframe
	// So, we allow :focus to pass through QSA all the time to avoid the IE error
	// See http://bugs.jquery.com/ticket/13378
	rbuggyQSA = [];

	if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert(function( div ) {
			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explicitly
			// setting a boolean content attribute,
			// since its presence should be enough
			// http://bugs.jquery.com/ticket/12359
			docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
				"<select id='" + expando + "-\r\\' msallowcapture=''>" +
				"<option selected=''></option></select>";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
			if ( div.querySelectorAll("[msallowcapture^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !div.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

			// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
			if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
				rbuggyQSA.push("~=");
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":checked").length ) {
				rbuggyQSA.push(":checked");
			}

			// Support: Safari 8+, iOS 8+
			// https://bugs.webkit.org/show_bug.cgi?id=136851
			// In-page `selector#id sibing-combinator selector` fails
			if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
				rbuggyQSA.push(".#.+[+~]");
			}
		});

		assert(function( div ) {
			// Support: Windows 8 Native Apps
			// The type and name attributes are restricted during .innerHTML assignment
			var input = document.createElement("input");
			input.setAttribute( "type", "hidden" );
			div.appendChild( input ).setAttribute( "name", "D" );

			// Support: IE8
			// Enforce case-sensitivity of name attribute
			if ( div.querySelectorAll("[name=d]").length ) {
				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":enabled").length ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Opera 10-11 does not throw on post-comma invalid pseudos
			div.querySelectorAll("*,:x");
			rbuggyQSA.push(",.*:");
		});
	}

	if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
		docElem.webkitMatchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector) )) ) {

		assert(function( div ) {
			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( div, "div" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( div, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		});
	}

	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );

	/* Contains
	---------------------------------------------------------------------- */
	hasCompare = rnative.test( docElem.compareDocumentPosition );

	// Element contains another
	// Purposefully self-exclusive
	// As in, an element does not contain itself
	contains = hasCompare || rnative.test( docElem.contains ) ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b && b.parentNode;
			return a === bup || !!( bup && bup.nodeType === 1 && (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
			));
		} :
		function( a, b ) {
			if ( b ) {
				while ( (b = b.parentNode) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = hasCompare ?
	function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare & 1 ||
			(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {

			// Choose the first element that is related to our preferred document
			if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;
		}

		return compare & 4 ? -1 : 1;
	} :
	function( a, b ) {
		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Parentless nodes are either documents or disconnected
		if ( !aup || !bup ) {
			return a === document ? -1 :
				b === document ? 1 :
				aup ? -1 :
				bup ? 1 :
				sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( (cur = cur.parentNode) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( (cur = cur.parentNode) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[i] === bp[i] ) {
			i++;
		}

		return i ?
			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[i], bp[i] ) :

			// Otherwise nodes in our document sort first
			ap[i] === preferredDoc ? -1 :
			bp[i] === preferredDoc ? 1 :
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	// Make sure that attribute selectors are quoted
	expr = expr.replace( rattributeQuotes, "='$1']" );

	if ( support.matchesSelector && documentIsHTML &&
		!compilerCache[ expr + " " ] &&
		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||
					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch (e) {}
	}

	return Sizzle( expr, document, null, [ elem ] ).length > 0;
};

Sizzle.contains = function( context, elem ) {
	// Set document vars if needed
	if ( ( context.ownerDocument || context ) !== document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],
		// Don't get fooled by Object.prototype properties (jQuery #13807)
		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	return val !== undefined ?
		val :
		support.attributes || !documentIsHTML ?
			elem.getAttribute( name ) :
			(val = elem.getAttributeNode(name)) && val.specified ?
				val.value :
				null;
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	sortInput = !support.sortStable && results.slice( 0 );
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		while ( (elem = results[i++]) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {
		// If no nodeType, this is expected to be an array
		while ( (node = elem[i++]) ) {
			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
		// Use textContent for elements
		// innerText usage removed for consistency of new lines (jQuery #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {
			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}
	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[1] = match[1].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );

			if ( match[2] === "~=" ) {
				match[3] = " " + match[3] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {
			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[1] = match[1].toLowerCase();

			if ( match[1].slice( 0, 3 ) === "nth" ) {
				// nth-* requires argument
				if ( !match[3] ) {
					Sizzle.error( match[0] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );

			// other types prohibit arguments
			} else if ( match[3] ) {
				Sizzle.error( match[0] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[6] && match[2];

			if ( matchExpr["CHILD"].test( match[0] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[3] ) {
				match[2] = match[4] || match[5] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&
				// Get excess from tokenize (recursively)
				(excess = tokenize( unquoted, true )) &&
				// advance to the next closing parenthesis
				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {

				// excess is a negative index
				match[0] = match[0].slice( 0, excess );
				match[2] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeNameSelector ) {
			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() { return true; } :
				function( elem ) {
					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
				};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
				classCache( className, function( elem ) {
					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
				});
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
			};
		},

		"CHILD": function( type, what, argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, context, xml ) {
					var cache, uniqueCache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( (node = node[ dir ]) ) {
									if ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) {

										return false;
									}
								}
								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {

							// Seek `elem` from a previously-cached index

							// ...in a gzip-friendly way
							node = parent;
							outerCache = node[ expando ] || (node[ expando ] = {});

							// Support: IE <9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[ node.uniqueID ] ||
								(outerCache[ node.uniqueID ] = {});

							cache = uniqueCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
							diff = nodeIndex && cache[ 2 ];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( (node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								(diff = nodeIndex = 0) || start.pop()) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {
							// Use previously-cached element index if available
							if ( useCache ) {
								// ...in a gzip-friendly way
								node = elem;
								outerCache = node[ expando ] || (node[ expando ] = {});

								// Support: IE <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[ node.uniqueID ] ||
									(outerCache[ node.uniqueID ] = {});

								cache = uniqueCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {
								// Use the same loop as above to seek `elem` from the start
								while ( (node = ++nodeIndex && node && node[ dir ] ||
									(diff = nodeIndex = 0) || start.pop()) ) {

									if ( ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) &&
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] || (node[ expando ] = {});

											// Support: IE <9 only
											// Defend against cloned attroperties (jQuery gh-1709)
											uniqueCache = outerCache[ node.uniqueID ] ||
												(outerCache[ node.uniqueID ] = {});

											uniqueCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {
			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction(function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf( seed, matched[i] );
							seed[ idx ] = !( matches[ idx ] = matched[i] );
						}
					}) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {
		// Potentially complex pseudos
		"not": markFunction(function( selector ) {
			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction(function( seed, matches, context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( (elem = unmatched[i]) ) {
							seed[i] = !(matches[i] = elem);
						}
					}
				}) :
				function( elem, context, xml ) {
					input[0] = elem;
					matcher( input, null, xml, results );
					// Don't keep the element (issue #299)
					input[0] = null;
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
			};
		}),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {
			// lang value must be a valid identifier
			if ( !ridentifier.test(lang || "") ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( (elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
				return false;
			};
		}),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
		},

		// Boolean properties
		"enabled": function( elem ) {
			return elem.disabled === false;
		},

		"disabled": function( elem ) {
			return elem.disabled === true;
		},

		"checked": function( elem ) {
			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
		},

		"selected": function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {
			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType < 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType < 6 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos["empty"]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			return elem.nodeName.toLowerCase() === "input" &&
				elem.type === "text" &&

				// Support: IE<8
				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		"first": createPositionalPseudo(function() {
			return [ 0 ];
		}),

		"last": createPositionalPseudo(function( matchIndexes, length ) {
			return [ length - 1 ];
		}),

		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		}),

		"even": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"odd": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		})
	}
};

Expr.pseudos["nth"] = Expr.pseudos["eq"];

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || (match = rcomma.exec( soFar )) ) {
			if ( match ) {
				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[0].length ) || soFar;
			}
			groups.push( (tokens = []) );
		}

		matched = false;

		// Combinators
		if ( (match = rcombinators.exec( soFar )) ) {
			matched = match.shift();
			tokens.push({
				value: matched,
				// Cast descendant combinators to space
				type: match[0].replace( rtrim, " " )
			});
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
				(match = preFilters[ type ]( match ))) ) {
				matched = match.shift();
				tokens.push({
					value: matched,
					type: type,
					matches: match
				});
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :
			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
};

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[i].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		checkNonElements = base && dir === "parentNode",
		doneName = done++;

	return combinator.first ?
		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( (elem = elem[ dir ]) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, uniqueCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || (elem[ expando ] = {});

						// Support: IE <9 only
						// Defend against cloned attroperties (jQuery gh-1709)
						uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});

						if ( (oldCache = uniqueCache[ dir ]) &&
							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return (newCache[ 2 ] = oldCache[ 2 ]);
						} else {
							// Reuse newcache so results back-propagate to previous elements
							uniqueCache[ dir ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
								return true;
							}
						}
					}
				}
			}
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[i]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[0];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[i], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( (elem = unmatched[i]) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction(function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( (elem = temp[i]) ) {
					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {
					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( (elem = matcherOut[i]) ) {
							// Restore matcherIn since elem is not yet a final match
							temp.push( (matcherIn[i] = elem) );
						}
					}
					postFinder( null, (matcherOut = []), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( (elem = matcherOut[i]) &&
						(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {

						seed[temp] = !(results[temp] = elem);
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	});
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[0].type ],
		implicitRelative = leadingRelative || Expr.relative[" "],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
			// Avoid hanging onto element (issue #299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i < len; i++ ) {
		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
		} else {
			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {
				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[j].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector(
						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
					).replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				setMatched = [],
				contextBackup = outermostContext,
				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
				len = elems.length;

			if ( outermost ) {
				outermostContext = context === document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: IE<9, Safari
			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
			for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;
					if ( !context && elem.ownerDocument !== document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context || document, xml) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( (matcher = setMatchers[j++]) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( (selector = compiled.selector || selector) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[0] = match[0].slice( 0 );
		if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
				support.getById && context.nodeType === 9 && documentIsHTML &&
				Expr.relative[ tokens[1].type ] ) {

			context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[i];

			// Abort if we hit a combinator
			if ( Expr.relative[ (type = token.type) ] ) {
				break;
			}
			if ( (find = Expr.find[ type ]) ) {
				// Search, expanding context for leading sibling combinators
				if ( (seed = find(
					token.matches[0].replace( runescape, funescape ),
					rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
				)) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
	// Should return 1, but returns 4 (following)
	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});

// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
	div.innerHTML = "<a href='#'></a>";
	return div.firstChild.getAttribute("href") === "#" ;
}) ) {
	addHandle( "type|href|height|width", function( elem, name, isXML ) {
		if ( !isXML ) {
			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
		}
	});
}

// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
	div.innerHTML = "<input/>";
	div.firstChild.setAttribute( "value", "" );
	return div.firstChild.getAttribute( "value" ) === "";
}) ) {
	addHandle( "value", function( elem, name, isXML ) {
		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
			return elem.defaultValue;
		}
	});
}

// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
	return div.getAttribute("disabled") == null;
}) ) {
	addHandle( booleans, function( elem, name, isXML ) {
		var val;
		if ( !isXML ) {
			return elem[ name ] === true ? name.toLowerCase() :
					(val = elem.getAttributeNode( name )) && val.specified ?
					val.value :
				null;
		}
	});
}

return Sizzle;

})( window );



jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;



var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate && jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType === 1 && n !== elem ) {
			matched.push( n );
		}
	}

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;

var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );



var risSimple = /^.[^:#\[\.,]*$/;

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			/* jshint -W018 */
			return !!qualifier.call( elem, i, elem ) !== not;
		} );

	}

	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );

	}

	if ( typeof qualifier === "string" ) {
		if ( risSimple.test( qualifier ) ) {
			return jQuery.filter( qualifier, elements, not );
		}

		qualifier = jQuery.filter( qualifier, elements );
	}

	return jQuery.grep( elements, function( elem ) {
		return ( jQuery.inArray( elem, qualifier ) > -1 ) !== not;
	} );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	return elems.length === 1 && elem.nodeType === 1 ?
		jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
		jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
			return elem.nodeType === 1;
		} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i,
			ret = [],
			self = this,
			len = self.length;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		// Needed because $( selector, context ) becomes $( context ).find( selector )
		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
		ret.selector = this.selector ? this.selector + " " + selector : selector;
		return ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// init accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector.charAt( 0 ) === "<" &&
				selector.charAt( selector.length - 1 ) === ">" &&
				selector.length >= 3 ) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( jQuery.isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {

						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[ 2 ] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[ 0 ] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this.context = this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return typeof root.ready !== "undefined" ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var i,
			targets = jQuery( target, this ),
			len = targets.length;

		return this.filter( function() {
			for ( i = 0; i < len; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {

				// Always skip document fragments
				if ( cur.nodeType < 11 && ( pos ?
					pos.index( cur ) > -1 :

					// Don't pass non-elements to Sizzle
					cur.nodeType === 1 &&
						jQuery.find.matchesSelector( cur, selectors ) ) ) {

					matched.push( cur );
					break;
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return jQuery.inArray( this[ 0 ], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem, this );
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	do {
		cur = cur[ dir ];
	} while ( cur && cur.nodeType !== 1 );

	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				ret = jQuery.uniqueSort( ret );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				ret = ret.reverse();
			}
		}

		return this.pushStack( ret );
	};
} );
var rnotwhite = ( /\S+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex < list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory && !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( jQuery.isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory && !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index <= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) > -1 :
					list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = true;
				if ( !memory ) {
					self.disable();
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks( "memory" ) ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];

							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && jQuery.isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this === promise ? newDefer.promise() : this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add( function() {

					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
			}

			// deferred[ resolve | reject | notify ]
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
				return this;
			};
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = slice.call( arguments ),
			length = resolveValues.length,

			// the count of uncompleted subordinates
			remaining = length !== 1 ||
				( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred.
			// If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

			// Update function for both resolve and progress values
			updateFunc = function( i, contexts, values ) {
				return function( value ) {
					contexts[ i ] = this;
					values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
					if ( values === progressValues ) {
						deferred.notifyWith( contexts, values );

					} else if ( !( --remaining ) ) {
						deferred.resolveWith( contexts, values );
					}
				};
			},

			progressValues, progressContexts, resolveContexts;

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			progressValues = new Array( length );
			progressContexts = new Array( length );
			resolveContexts = new Array( length );
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.progress( updateFunc( i, progressContexts, progressValues ) )
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( resolveContexts, resolveValues );
		}

		return deferred.promise();
	}
} );


// The deferred used on DOM ready
var readyList;

jQuery.fn.ready = function( fn ) {

	// Add the callback
	jQuery.ready.promise().done( fn );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady =
Download .txt
gitextract_1662e_mz/

├── .eslintrc
├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── Gemfile
├── LICENSE
├── README.md
├── bower.json
├── jquery.pjax.js
├── package.json
├── script/
│   ├── bootstrap
│   ├── server
│   └── test
├── test/
│   ├── app.rb
│   ├── evaled.js
│   ├── run-qunit.js
│   ├── unit/
│   │   ├── fn_pjax.js
│   │   ├── helpers.js
│   │   ├── pjax.js
│   │   └── pjax_fallback.js
│   └── views/
│       ├── aliens.erb
│       ├── anchor.erb
│       ├── boom.erb
│       ├── boom_sans_pjax.erb
│       ├── dinosaurs.erb
│       ├── double_title.erb
│       ├── empty.erb
│       ├── env.erb
│       ├── fragment.erb
│       ├── hello.erb
│       ├── home.erb
│       ├── layout.erb
│       ├── long.erb
│       ├── nested_title.erb
│       ├── qunit.erb
│       ├── referer.erb
│       ├── scripts.erb
│       └── timeout.erb
└── vendor/
    ├── jquery-1.12.js
    ├── jquery-2.2.js
    ├── jquery-3.2.js
    ├── qunit.css
    └── qunit.js
Download .txt
SYMBOL INDEX (281 symbols across 9 files)

FILE: jquery.pjax.js
  function fnPjax (line 30) | function fnPjax(selector, container, options) {
  function handleClick (line 56) | function handleClick(event, container, options) {
  function handleSubmit (line 113) | function handleSubmit(event, container, options) {
  function pjax (line 166) | function pjax(options) {
  function pjaxReload (line 380) | function pjaxReload(container, options) {
  function locationReplace (line 397) | function locationReplace(url) {
  function onPjaxPopstate (line 423) | function onPjaxPopstate(event) {
  function fallbackPjax (line 507) | function fallbackPjax(options) {
  function abortXHR (line 547) | function abortXHR(xhr) {
  function uniqueId (line 560) | function uniqueId() {
  function cloneContents (line 564) | function cloneContents(container) {
  function stripInternalParams (line 577) | function stripInternalParams(url) {
  function parseURL (line 587) | function parseURL(url) {
  function stripHash (line 599) | function stripHash(location) {
  function optionsFor (line 620) | function optionsFor(container, options) {
  function findAll (line 641) | function findAll(elems, selector) {
  function parseHTML (line 645) | function parseHTML(html) {
  function extractContainer (line 660) | function extractContainer(data, xhr, options) {
  function executeScriptTags (line 734) | function executeScriptTags(scripts) {
  function cachePush (line 767) | function cachePush(id, value) {
  function cachePop (line 787) | function cachePop(direction, id, value) {
  function trimCacheStack (line 814) | function trimCacheStack(stack, length) {
  function findVersion (line 822) | function findVersion() {
  function enable (line 838) | function enable() {
  function disable (line 870) | function disable() {

FILE: test/app.rb
  function pjax? (line 10) | def pjax?
  function title (line 14) | def title(str)

FILE: test/run-qunit.js
  function print (line 4) | function print(s) {
  function deferTimeout (line 17) | function deferTimeout() {
  function runSuite (line 27) | function runSuite() {

FILE: test/unit/helpers.js
  function navigate (line 16) | function navigate(frame) {
  function PoorMansPromise (line 55) | function PoorMansPromise(setup) {

FILE: test/unit/pjax.js
  function goBack (line 622) | function goBack(frame, callback) {

FILE: vendor/jquery-1.12.js
  function isArrayLike (line 563) | function isArrayLike( obj ) {
  function Sizzle (line 772) | function Sizzle( selector, context, results, seed ) {
  function createCache (line 912) | function createCache() {
  function markFunction (line 930) | function markFunction( fn ) {
  function assert (line 939) | function assert( fn ) {
  function addHandle (line 961) | function addHandle( attrs, handler ) {
  function siblingCheck (line 976) | function siblingCheck( a, b ) {
  function createInputPseudo (line 1003) | function createInputPseudo( type ) {
  function createButtonPseudo (line 1014) | function createButtonPseudo( type ) {
  function createPositionalPseudo (line 1025) | function createPositionalPseudo( fn ) {
  function testContext (line 1048) | function testContext( context ) {
  function setFilters (line 2093) | function setFilters() {}
  function toSelector (line 2164) | function toSelector( tokens ) {
  function addCombinator (line 2174) | function addCombinator( matcher, combinator, base ) {
  function elementMatcher (line 2232) | function elementMatcher( matchers ) {
  function multipleContexts (line 2246) | function multipleContexts( selector, contexts, results ) {
  function condense (line 2255) | function condense( unmatched, map, filter, context, xml ) {
  function setMatcher (line 2276) | function setMatcher( preFilter, selector, matcher, postFilter, postFinde...
  function matcherFromTokens (line 2369) | function matcherFromTokens( tokens ) {
  function matcherFromGroupMatchers (line 2427) | function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
  function winnow (line 2765) | function winnow( elements, qualifier, not ) {
  function sibling (line 3078) | function sibling( cur, dir ) {
  function createOptions (line 3159) | function createOptions( options ) {
  function detach (line 3595) | function detach() {
  function completed (line 3609) | function completed() {
  function dataAttr (line 3779) | function dataAttr( elem, key, data ) {
  function isEmptyDataObject (line 3813) | function isEmptyDataObject( obj ) {
  function internalData (line 3829) | function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
  function internalRemoveData (line 3921) | function internalRemoveData( elem, name, pvt ) {
  function adjustCSS (line 4314) | function adjustCSS( elem, prop, valueParts, tween ) {
  function createSafeFragment (line 4444) | function createSafeFragment( document ) {
  function getAll (line 4548) | function getAll( context, tag ) {
  function setGlobalEval (line 4577) | function setGlobalEval( elems, refElements ) {
  function fixDefaultChecked (line 4593) | function fixDefaultChecked( elem ) {
  function buildFragment (line 4599) | function buildFragment( elems, context, scripts, selection, ignored ) {
  function returnTrue (line 4759) | function returnTrue() {
  function returnFalse (line 4763) | function returnFalse() {
  function safeActiveElement (line 4769) | function safeActiveElement() {
  function on (line 4775) | function on( elem, types, selector, data, fn, one ) {
  function manipulationTarget (line 5890) | function manipulationTarget( elem, content ) {
  function disableScript (line 5900) | function disableScript( elem ) {
  function restoreScript (line 5904) | function restoreScript( elem ) {
  function cloneCopyEvent (line 5914) | function cloneCopyEvent( src, dest ) {
  function fixCloneNodeIssues (line 5941) | function fixCloneNodeIssues( src, dest ) {
  function domManip (line 6009) | function domManip( collection, args, callback, ignored ) {
  function remove (line 6106) | function remove( elem, selector, keepData ) {
  function actualDisplay (line 6442) | function actualDisplay( name, doc ) {
  function defaultDisplay (line 6458) | function defaultDisplay( nodeName ) {
  function computeStyleTests (line 6607) | function computeStyleTests() {
  function addGetHookIf (line 6819) | function addGetHookIf( conditionFn, hookFn ) {
  function vendorPropName (line 6862) | function vendorPropName( name ) {
  function showHide (line 6881) | function showHide( elements, show ) {
  function setPositiveNumber (line 6938) | function setPositiveNumber( elem, value, subtract ) {
  function augmentWidthOrHeight (line 6947) | function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
  function getWidthOrHeight (line 6991) | function getWidthOrHeight( elem, name, extra ) {
  function Tween (line 7374) | function Tween( elem, options, prop, end, easing ) {
  function createFxNow (line 7498) | function createFxNow() {
  function genFx (line 7506) | function genFx( type, includeWidth ) {
  function createTween (line 7526) | function createTween( value, prop, animation ) {
  function defaultPrefilter (line 7540) | function defaultPrefilter( elem, props, opts ) {
  function propFilter (line 7685) | function propFilter( props, specialEasing ) {
  function Animation (line 7722) | function Animation( elem, properties, options ) {
  function getClass (line 8803) | function getClass( elem ) {
  function addToPrefiltersOrTransports (line 9115) | function addToPrefiltersOrTransports( structure ) {
  function inspectPrefiltersOrTransports (line 9149) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
  function ajaxExtend (line 9178) | function ajaxExtend( target, src ) {
  function ajaxHandleResponses (line 9198) | function ajaxHandleResponses( s, jqXHR, responses ) {
  function ajaxConvert (line 9255) | function ajaxConvert( s, response, jqXHR, isSuccess ) {
  function done (line 9753) | function done( status, nativeStatusText, responses, headers ) {
  function getDisplay (line 9985) | function getDisplay( elem ) {
  function filterHidden (line 9989) | function filterHidden( elem ) {
  function buildParams (line 10027) | function buildParams( prefix, obj, traditional, add ) {
  function createStandardXHR (line 10346) | function createStandardXHR() {
  function createActiveXHR (line 10352) | function createActiveXHR() {
  function getWindow (line 10682) | function getWindow( elem ) {

FILE: vendor/jquery-2.2.js
  function isArrayLike (line 529) | function isArrayLike( obj ) {
  function Sizzle (line 738) | function Sizzle( selector, context, results, seed ) {
  function createCache (line 878) | function createCache() {
  function markFunction (line 896) | function markFunction( fn ) {
  function assert (line 905) | function assert( fn ) {
  function addHandle (line 927) | function addHandle( attrs, handler ) {
  function siblingCheck (line 942) | function siblingCheck( a, b ) {
  function createInputPseudo (line 969) | function createInputPseudo( type ) {
  function createButtonPseudo (line 980) | function createButtonPseudo( type ) {
  function createPositionalPseudo (line 991) | function createPositionalPseudo( fn ) {
  function testContext (line 1014) | function testContext( context ) {
  function setFilters (line 2059) | function setFilters() {}
  function toSelector (line 2130) | function toSelector( tokens ) {
  function addCombinator (line 2140) | function addCombinator( matcher, combinator, base ) {
  function elementMatcher (line 2198) | function elementMatcher( matchers ) {
  function multipleContexts (line 2212) | function multipleContexts( selector, contexts, results ) {
  function condense (line 2221) | function condense( unmatched, map, filter, context, xml ) {
  function setMatcher (line 2242) | function setMatcher( preFilter, selector, matcher, postFilter, postFinde...
  function matcherFromTokens (line 2335) | function matcherFromTokens( tokens ) {
  function matcherFromGroupMatchers (line 2393) | function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
  function winnow (line 2731) | function winnow( elements, qualifier, not ) {
  function sibling (line 3038) | function sibling( cur, dir ) {
  function createOptions (line 3114) | function createOptions( options ) {
  function completed (line 3549) | function completed() {
  function Data (line 3660) | function Data() {
  function dataAttr (line 3870) | function dataAttr( elem, key, data ) {
  function adjustCSS (line 4187) | function adjustCSS( elem, prop, valueParts, tween ) {
  function getAll (line 4276) | function getAll( context, tag ) {
  function setGlobalEval (line 4293) | function setGlobalEval( elems, refElements ) {
  function buildFragment (line 4309) | function buildFragment( elems, context, scripts, selection, ignored ) {
  function returnTrue (line 4430) | function returnTrue() {
  function returnFalse (line 4434) | function returnFalse() {
  function safeActiveElement (line 4440) | function safeActiveElement() {
  function on (line 4446) | function on( elem, types, selector, data, fn, one ) {
  function manipulationTarget (line 5138) | function manipulationTarget( elem, content ) {
  function disableScript (line 5148) | function disableScript( elem ) {
  function restoreScript (line 5152) | function restoreScript( elem ) {
  function cloneCopyEvent (line 5164) | function cloneCopyEvent( src, dest ) {
  function fixInput (line 5199) | function fixInput( src, dest ) {
  function domManip (line 5212) | function domManip( collection, args, callback, ignored ) {
  function remove (line 5302) | function remove( elem, selector, keepData ) {
  function actualDisplay (line 5593) | function actualDisplay( name, doc ) {
  function defaultDisplay (line 5609) | function defaultDisplay( nodeName ) {
  function computeStyleTests (line 5705) | function computeStyleTests() {
  function curCSS (line 5795) | function curCSS( elem, name, computed ) {
  function addGetHookIf (line 5845) | function addGetHookIf( conditionFn, hookFn ) {
  function vendorPropName (line 5882) | function vendorPropName( name ) {
  function setPositiveNumber (line 5901) | function setPositiveNumber( elem, value, subtract ) {
  function augmentWidthOrHeight (line 5913) | function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
  function getWidthOrHeight (line 5957) | function getWidthOrHeight( elem, name, extra ) {
  function showHide (line 6002) | function showHide( elements, show ) {
  function Tween (line 6341) | function Tween( elem, options, prop, end, easing ) {
  function createFxNow (line 6465) | function createFxNow() {
  function genFx (line 6473) | function genFx( type, includeWidth ) {
  function createTween (line 6493) | function createTween( value, prop, animation ) {
  function defaultPrefilter (line 6507) | function defaultPrefilter( elem, props, opts ) {
  function propFilter (line 6643) | function propFilter( props, specialEasing ) {
  function Animation (line 6680) | function Animation( elem, properties, options ) {
  function getClass (line 7369) | function getClass( elem ) {
  function addToPrefiltersOrTransports (line 8025) | function addToPrefiltersOrTransports( structure ) {
  function inspectPrefiltersOrTransports (line 8059) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
  function ajaxExtend (line 8088) | function ajaxExtend( target, src ) {
  function ajaxHandleResponses (line 8108) | function ajaxHandleResponses( s, jqXHR, responses ) {
  function ajaxConvert (line 8166) | function ajaxConvert( s, response, jqXHR, isSuccess ) {
  function done (line 8671) | function done( status, nativeStatusText, responses, headers ) {
  function buildParams (line 8924) | function buildParams( prefix, obj, traditional, add ) {
  function getWindow (line 9490) | function getWindow( elem ) {

FILE: vendor/jquery-3.2.js
  function DOMEval (line 76) | function DOMEval( code, doc ) {
  function isArrayLike (line 522) | function isArrayLike( obj ) {
  function Sizzle (line 754) | function Sizzle( selector, context, results, seed ) {
  function createCache (line 893) | function createCache() {
  function markFunction (line 911) | function markFunction( fn ) {
  function assert (line 920) | function assert( fn ) {
  function addHandle (line 942) | function addHandle( attrs, handler ) {
  function siblingCheck (line 957) | function siblingCheck( a, b ) {
  function createInputPseudo (line 983) | function createInputPseudo( type ) {
  function createButtonPseudo (line 994) | function createButtonPseudo( type ) {
  function createDisabledPseudo (line 1005) | function createDisabledPseudo( disabled ) {
  function createPositionalPseudo (line 1061) | function createPositionalPseudo( fn ) {
  function testContext (line 1084) | function testContext( context ) {
  function setFilters (line 2166) | function setFilters() {}
  function toSelector (line 2237) | function toSelector( tokens ) {
  function addCombinator (line 2247) | function addCombinator( matcher, combinator, base ) {
  function elementMatcher (line 2311) | function elementMatcher( matchers ) {
  function multipleContexts (line 2325) | function multipleContexts( selector, contexts, results ) {
  function condense (line 2334) | function condense( unmatched, map, filter, context, xml ) {
  function setMatcher (line 2355) | function setMatcher( preFilter, selector, matcher, postFilter, postFinde...
  function matcherFromTokens (line 2448) | function matcherFromTokens( tokens ) {
  function matcherFromGroupMatchers (line 2506) | function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
  function nodeName (line 2842) | function nodeName( elem, name ) {
  function winnow (line 2854) | function winnow( elements, qualifier, not ) {
  function sibling (line 3157) | function sibling( cur, dir ) {
  function createOptions (line 3244) | function createOptions( options ) {
  function Identity (line 3469) | function Identity( v ) {
  function Thrower (line 3472) | function Thrower( ex ) {
  function adoptValue (line 3476) | function adoptValue( value, resolve, reject, noValue ) {
  function resolve (line 3569) | function resolve( depth, deferred, handler, special ) {
  function completed (line 3927) | function completed() {
  function Data (line 4029) | function Data() {
  function getData (line 4198) | function getData( data ) {
  function dataAttr (line 4223) | function dataAttr( elem, key, data ) {
  function adjustCSS (line 4536) | function adjustCSS( elem, prop, valueParts, tween ) {
  function getDefaultDisplay (line 4601) | function getDefaultDisplay( elem ) {
  function showHide (line 4624) | function showHide( elements, show ) {
  function getAll (line 4725) | function getAll( context, tag ) {
  function setGlobalEval (line 4750) | function setGlobalEval( elems, refElements ) {
  function buildFragment (line 4766) | function buildFragment( elems, context, scripts, selection, ignored ) {
  function returnTrue (line 4889) | function returnTrue() {
  function returnFalse (line 4893) | function returnFalse() {
  function safeActiveElement (line 4899) | function safeActiveElement() {
  function on (line 4905) | function on( elem, types, selector, data, fn, one ) {
  function manipulationTarget (line 5634) | function manipulationTarget( elem, content ) {
  function disableScript (line 5645) | function disableScript( elem ) {
  function restoreScript (line 5649) | function restoreScript( elem ) {
  function cloneCopyEvent (line 5661) | function cloneCopyEvent( src, dest ) {
  function fixInput (line 5696) | function fixInput( src, dest ) {
  function domManip (line 5709) | function domManip( collection, args, callback, ignored ) {
  function remove (line 5799) | function remove( elem, selector, keepData ) {
  function computeStyleTests (line 6092) | function computeStyleTests() {
  function curCSS (line 6166) | function curCSS( elem, name, computed ) {
  function addGetHookIf (line 6219) | function addGetHookIf( conditionFn, hookFn ) {
  function vendorPropName (line 6256) | function vendorPropName( name ) {
  function finalPropName (line 6277) | function finalPropName( name ) {
  function setPositiveNumber (line 6285) | function setPositiveNumber( elem, value, subtract ) {
  function augmentWidthOrHeight (line 6297) | function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
  function getWidthOrHeight (line 6343) | function getWidthOrHeight( elem, name, extra ) {
  function Tween (line 6652) | function Tween( elem, options, prop, end, easing ) {
  function schedule (line 6775) | function schedule() {
  function createFxNow (line 6788) | function createFxNow() {
  function genFx (line 6796) | function genFx( type, includeWidth ) {
  function createTween (line 6816) | function createTween( value, prop, animation ) {
  function defaultPrefilter (line 6830) | function defaultPrefilter( elem, props, opts ) {
  function propFilter (line 7001) | function propFilter( props, specialEasing ) {
  function Animation (line 7038) | function Animation( elem, properties, options ) {
  function stripAndCollapse (line 7753) | function stripAndCollapse( value ) {
  function getClass (line 7759) | function getClass( elem ) {
  function buildParams (line 8383) | function buildParams( prefix, obj, traditional, add ) {
  function addToPrefiltersOrTransports (line 8533) | function addToPrefiltersOrTransports( structure ) {
  function inspectPrefiltersOrTransports (line 8567) | function inspectPrefiltersOrTransports( structure, options, originalOpti...
  function ajaxExtend (line 8596) | function ajaxExtend( target, src ) {
  function ajaxHandleResponses (line 8616) | function ajaxHandleResponses( s, jqXHR, responses ) {
  function ajaxConvert (line 8674) | function ajaxConvert( s, response, jqXHR, isSuccess ) {
  function done (line 9187) | function done( status, nativeStatusText, responses, headers ) {

FILE: vendor/qunit.js
  function Test (line 86) | function Test( settings ) {
  function run (line 342) | function run() {
  function F (line 676) | function F() {}
  function done (line 1218) | function done() {
  function validTest (line 1291) | function validTest( test ) {
  function extractStacktrace (line 1332) | function extractStacktrace( e, offset ) {
  function sourceFromStacktrace (line 1370) | function sourceFromStacktrace( offset ) {
  function escapeText (line 1381) | function escapeText( s ) {
  function synchronize (line 1403) | function synchronize( callback, last ) {
  function process (line 1411) | function process( last ) {
  function saveGlobal (line 1432) | function saveGlobal() {
  function checkPollution (line 1446) | function checkPollution() {
  function diff (line 1465) | function diff( a, b ) {
  function extend (line 1481) | function extend( a, b ) {
  function addEvent (line 1500) | function addEvent( elem, type, fn ) {
  function addEvents (line 1515) | function addEvents( elems, type, fn ) {
  function hasClass (line 1522) | function hasClass( elem, name ) {
  function addClass (line 1526) | function addClass( elem, name ) {
  function removeClass (line 1532) | function removeClass( elem, name ) {
  function id (line 1542) | function id( name ) {
  function registerLoggingCallback (line 1547) | function registerLoggingCallback( key ) {
  function runLoggingCallbacks (line 1554) | function runLoggingCallbacks( key, scope, args ) {
  function bindCallbacks (line 1571) | function bindCallbacks( o, callbacks, args ) {
  function useStrictEquality (line 1595) | function useStrictEquality( b, a ) {
  function quote (line 1763) | function quote( str ) {
  function literal (line 1766) | function literal( o ) {
  function join (line 1769) | function join( pre, arr, post ) {
  function array (line 1781) | function array( arr, stack ) {
  function inArray (line 1983) | function inArray( elem, array ) {
  function diff (line 2013) | function diff( o, n ) {
Condensed preview — 43 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,101K chars).
[
  {
    "path": ".eslintrc",
    "chars": 328,
    "preview": "{ \"extends\": \"eslint:recommended\",\n  \"env\": {\n    \"browser\": true,\n    \"jquery\": true\n  },\n  \"rules\": {\n    \"eqeqeq\": \"w"
  },
  {
    "path": ".gitignore",
    "chars": 14,
    "preview": "node_modules/\n"
  },
  {
    "path": ".travis.yml",
    "chars": 412,
    "preview": "sudo: false\nlanguage: node_js\nnode_js: \"6\"\nbefore_script: script/bootstrap\n\nnotifications:\n  email: false\ndeploy:\n  prov"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 907,
    "preview": "# Contributing\n\nFor running the tests, you will need:\n\n* Ruby 1.9.3+ with Bundler\n* PhantomJS (for headless testing)\n\nFi"
  },
  {
    "path": "Gemfile",
    "chars": 45,
    "preview": "source 'https://rubygems.org'\n\ngem 'sinatra'\n"
  },
  {
    "path": "LICENSE",
    "chars": 1050,
    "preview": "Copyright (c) Chris Wanstrath\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this soft"
  },
  {
    "path": "README.md",
    "chars": 11267,
    "preview": "# pjax = pushState + ajax\n\npjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience wi"
  },
  {
    "path": "bower.json",
    "chars": 243,
    "preview": "{\n  \"name\": \"jquery-pjax\",\n  \"main\": \"./jquery.pjax.js\",\n  \"dependencies\": {\n    \"jquery\": \">=1.8\"\n  },\n  \"ignore\": [\n  "
  },
  {
    "path": "jquery.pjax.js",
    "chars": 25260,
    "preview": "/*!\n * Copyright 2012, Chris Wanstrath\n * Released under the MIT License\n * https://github.com/defunkt/jquery-pjax\n */\n\n"
  },
  {
    "path": "package.json",
    "chars": 357,
    "preview": "{\n  \"name\": \"jquery-pjax\",\n  \"description\": \"jQuery plugin for ajax + pushState navigation\",\n  \"version\": \"2.0.1\",\n  \"ma"
  },
  {
    "path": "script/bootstrap",
    "chars": 317,
    "preview": "#!/usr/bin/env bash\nset -e\n\n[ -n \"$CI\" ] || npm install\nbundle install\n\nif phantom_version=\"$(phantomjs --version)\"; the"
  },
  {
    "path": "script/server",
    "chars": 69,
    "preview": "#!/usr/bin/env bash\nset -e\n\nexec bundle exec ruby ./test/app.rb \"$@\"\n"
  },
  {
    "path": "script/test",
    "chars": 355,
    "preview": "#!/usr/bin/env bash\nset -e\n\n./node_modules/.bin/eslint *.js\n\nport=3999\nscript/server -p \"$port\" &>/dev/null &\npid=$!\n\ntr"
  },
  {
    "path": "test/app.rb",
    "chars": 1598,
    "preview": "require 'sinatra'\nrequire 'json'\n\nset :public_folder, File.dirname(settings.root)\nenable :static\n\njquery_version = '3.2'"
  },
  {
    "path": "test/evaled.js",
    "chars": 30,
    "preview": "window.externalScriptLoaded()\n"
  },
  {
    "path": "test/run-qunit.js",
    "chars": 2055,
    "preview": "var fs = require('fs')\nvar suites = require('system').args.slice(1)\n\nfunction print(s) {\n  fs.write('/dev/stdout', s, 'w"
  },
  {
    "path": "test/unit/fn_pjax.js",
    "chars": 6065,
    "preview": "if ($.support.pjax) {\n  module(\"$.fn.pjax\", {\n    setup: function() {\n      var self = this\n      stop()\n      window.if"
  },
  {
    "path": "test/unit/helpers.js",
    "chars": 1684,
    "preview": "// Navigation helper for the test iframe. Queues navigation actions and\n// callbacks, then executes them serially with r"
  },
  {
    "path": "test/unit/pjax.js",
    "chars": 32813,
    "preview": "if ($.support.pjax) {\n  module(\"$.pjax\", {\n    setup: function() {\n      var self = this\n      stop()\n      window.ifram"
  },
  {
    "path": "test/unit/pjax_fallback.js",
    "chars": 9868,
    "preview": "// $.pjax fallback tests should run on both pushState and\n// non-pushState compatible browsers.\n$.each([true, false], fu"
  },
  {
    "path": "test/views/aliens.erb",
    "chars": 262,
    "preview": "<%= title 'aliens' %>\n\n<ul>\n  <li><a href=\"/home.html\">home</a></li>\n  <li><a href=\"/dinosaurs.html\">dinosaurs</a></li>\n"
  },
  {
    "path": "test/views/anchor.erb",
    "chars": 224,
    "preview": "<%= title 'Anchor' %>\n<div id=\"top\" style=\"width:500px;height:10000px;\"></div>\n<a name=\"bottom\" style=\"width:500px;heigh"
  },
  {
    "path": "test/views/boom.erb",
    "chars": 11,
    "preview": "<p>500</p>\n"
  },
  {
    "path": "test/views/boom_sans_pjax.erb",
    "chars": 179,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <title>500 sans pjax</title>\n</head>\n<body>\n  <div id"
  },
  {
    "path": "test/views/dinosaurs.erb",
    "chars": 370,
    "preview": "<%= title 'dinosaurs' %>\n\n<ul>\n  <li><a href=\"/home.html\">home</a></li>\n  <li>dinosaurs</li>\n  <li><a href=\"/aliens.html"
  },
  {
    "path": "test/views/double_title.erb",
    "chars": 130,
    "preview": "<%= title 'Hello' %>\n<p><title>World!</title> Hello!</p>\n<script type=\"text/javascript\">window.parent.iframeLoad(window)"
  },
  {
    "path": "test/views/empty.erb",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/views/env.erb",
    "chars": 151,
    "preview": "<div id=\"env\"><%= Rack::Utils.escape_html JSON.generate(request.env) %></div>\n<script type=\"text/javascript\">window.pare"
  },
  {
    "path": "test/views/fragment.erb",
    "chars": 100,
    "preview": "<div id=\"foo\" title=\"Foo\">\n  <p>Foo</p>\n</div>\n\n<div id=\"bar\" data-title=\"Bar\">\n  <p>Bar</p>\n</div>\n"
  },
  {
    "path": "test/views/hello.erb",
    "chars": 124,
    "preview": "<%= title 'Hello' %>\n<p>Hello!</p>\nHow's it going?\n<script type=\"text/javascript\">window.parent.iframeLoad(window)</scri"
  },
  {
    "path": "test/views/home.erb",
    "chars": 501,
    "preview": "<%= title 'Home' %>\n\n<ul>\n  <li>home</li>\n  <li><a href=\"/dinosaurs.html\">dinosaurs</a></li>\n  <li><a href=\"/aliens.html"
  },
  {
    "path": "test/views/layout.erb",
    "chars": 325,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <title><%= @title %></title>\n  <script type=\"text/jav"
  },
  {
    "path": "test/views/long.erb",
    "chars": 158,
    "preview": "<%= title 'Long' %>\n<p>Long Page</p>\n<div style=\"width:500px;height:10000px;\"></div>\n<script type=\"text/javascript\">wind"
  },
  {
    "path": "test/views/nested_title.erb",
    "chars": 108,
    "preview": "<p><%= title 'Hello' %> Hello!</p>\n<script type=\"text/javascript\">window.parent.iframeLoad(window)</script>\n"
  },
  {
    "path": "test/views/qunit.erb",
    "chars": 857,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <link rel=\"stylesheet\" href=\"/vendor/qunit.css\">\n  <m"
  },
  {
    "path": "test/views/referer.erb",
    "chars": 116,
    "preview": "<p id=\"referer\"><%= request.referer %></p>\n<script type=\"text/javascript\">window.parent.iframeLoad(window)</script>\n"
  },
  {
    "path": "test/views/scripts.erb",
    "chars": 365,
    "preview": "<p>Got some script tags here</p>\n<script type=\"text/javascript\" src=\"/test/evaled.js?1\"></script>\n<script src=\"/test/eva"
  },
  {
    "path": "test/views/timeout.erb",
    "chars": 117,
    "preview": "<%= title 'Timeout!' %>\n\n<p>SLOW DOWN!</p>\n\n<script type=\"text/javascript\">window.parent.iframeLoad(window)</script>\n"
  },
  {
    "path": "vendor/jquery-1.12.js",
    "chars": 293430,
    "preview": "/*!\n * jQuery JavaScript Library v1.12.4\n * http://jquery.com/\n *\n * Includes Sizzle.js\n * http://sizzlejs.com/\n *\n * Co"
  },
  {
    "path": "vendor/jquery-2.2.js",
    "chars": 257551,
    "preview": "/*!\n * jQuery JavaScript Library v2.2.4\n * http://jquery.com/\n *\n * Includes Sizzle.js\n * http://sizzlejs.com/\n *\n * Cop"
  },
  {
    "path": "vendor/jquery-3.2.js",
    "chars": 268039,
    "preview": "/*!\n * jQuery JavaScript Library v3.2.1\n * https://jquery.com/\n *\n * Includes Sizzle.js\n * https://sizzlejs.com/\n *\n * C"
  },
  {
    "path": "vendor/qunit.css",
    "chars": 4668,
    "preview": "/**\n * QUnit v1.11.0 - A JavaScript Unit Testing Framework\n *\n * http://qunitjs.com\n *\n * Copyright 2012 jQuery Foundati"
  },
  {
    "path": "vendor/qunit.js",
    "chars": 56903,
    "preview": "/**\n * QUnit v1.11.0 - A JavaScript Unit Testing Framework\n *\n * http://qunitjs.com\n *\n * Copyright 2012 jQuery Foundati"
  }
]

About this extraction

This page contains the full source code of the defunkt/jquery-pjax GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 43 files (956.5 KB), approximately 274.8k tokens, and a symbol index with 281 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!